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 "TreeTransform.h"
14 #include "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/CommentDiagnostic.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/NonTrivialTypeVisitor.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaInternal.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/Triple.h"
48 #include <algorithm>
49 #include <cstring>
50 #include <functional>
51
52 using namespace clang;
53 using namespace sema;
54
ConvertDeclToDeclGroup(Decl * Ptr,Decl * OwnedType)55 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
56 if (OwnedType) {
57 Decl *Group[2] = { OwnedType, Ptr };
58 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
59 }
60
61 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
62 }
63
64 namespace {
65
66 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
67 public:
TypeNameValidatorCCC(bool AllowInvalid,bool WantClass=false,bool AllowTemplates=false,bool AllowNonTemplates=true)68 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
69 bool AllowTemplates = false,
70 bool AllowNonTemplates = true)
71 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
72 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
73 WantExpressionKeywords = false;
74 WantCXXNamedCasts = false;
75 WantRemainingKeywords = false;
76 }
77
ValidateCandidate(const TypoCorrection & candidate)78 bool ValidateCandidate(const TypoCorrection &candidate) override {
79 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
80 if (!AllowInvalidDecl && ND->isInvalidDecl())
81 return false;
82
83 if (getAsTypeTemplateDecl(ND))
84 return AllowTemplates;
85
86 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
87 if (!IsType)
88 return false;
89
90 if (AllowNonTemplates)
91 return true;
92
93 // An injected-class-name of a class template (specialization) is valid
94 // as a template or as a non-template.
95 if (AllowTemplates) {
96 auto *RD = dyn_cast<CXXRecordDecl>(ND);
97 if (!RD || !RD->isInjectedClassName())
98 return false;
99 RD = cast<CXXRecordDecl>(RD->getDeclContext());
100 return RD->getDescribedClassTemplate() ||
101 isa<ClassTemplateSpecializationDecl>(RD);
102 }
103
104 return false;
105 }
106
107 return !WantClassName && candidate.isKeyword();
108 }
109
clone()110 std::unique_ptr<CorrectionCandidateCallback> clone() override {
111 return std::make_unique<TypeNameValidatorCCC>(*this);
112 }
113
114 private:
115 bool AllowInvalidDecl;
116 bool WantClassName;
117 bool AllowTemplates;
118 bool AllowNonTemplates;
119 };
120
121 } // end anonymous namespace
122
123 /// Determine whether the token kind starts a simple-type-specifier.
isSimpleTypeSpecifier(tok::TokenKind Kind) const124 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
125 switch (Kind) {
126 // FIXME: Take into account the current language when deciding whether a
127 // token kind is a valid type specifier
128 case tok::kw_short:
129 case tok::kw_long:
130 case tok::kw___int64:
131 case tok::kw___int128:
132 case tok::kw_signed:
133 case tok::kw_unsigned:
134 case tok::kw_void:
135 case tok::kw_char:
136 case tok::kw_int:
137 case tok::kw_half:
138 case tok::kw_float:
139 case tok::kw_double:
140 case tok::kw__Float16:
141 case tok::kw___float128:
142 case tok::kw_wchar_t:
143 case tok::kw_bool:
144 case tok::kw___underlying_type:
145 case tok::kw___auto_type:
146 return true;
147
148 case tok::annot_typename:
149 case tok::kw_char16_t:
150 case tok::kw_char32_t:
151 case tok::kw_typeof:
152 case tok::annot_decltype:
153 case tok::kw_decltype:
154 return getLangOpts().CPlusPlus;
155
156 case tok::kw_char8_t:
157 return getLangOpts().Char8;
158
159 default:
160 break;
161 }
162
163 return false;
164 }
165
166 namespace {
167 enum class UnqualifiedTypeNameLookupResult {
168 NotFound,
169 FoundNonType,
170 FoundType
171 };
172 } // end anonymous namespace
173
174 /// Tries to perform unqualified lookup of the type decls in bases for
175 /// dependent class.
176 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
177 /// type decl, \a FoundType if only type decls are found.
178 static UnqualifiedTypeNameLookupResult
lookupUnqualifiedTypeNameInBase(Sema & S,const IdentifierInfo & II,SourceLocation NameLoc,const CXXRecordDecl * RD)179 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
180 SourceLocation NameLoc,
181 const CXXRecordDecl *RD) {
182 if (!RD->hasDefinition())
183 return UnqualifiedTypeNameLookupResult::NotFound;
184 // Look for type decls in base classes.
185 UnqualifiedTypeNameLookupResult FoundTypeDecl =
186 UnqualifiedTypeNameLookupResult::NotFound;
187 for (const auto &Base : RD->bases()) {
188 const CXXRecordDecl *BaseRD = nullptr;
189 if (auto *BaseTT = Base.getType()->getAs<TagType>())
190 BaseRD = BaseTT->getAsCXXRecordDecl();
191 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
192 // Look for type decls in dependent base classes that have known primary
193 // templates.
194 if (!TST || !TST->isDependentType())
195 continue;
196 auto *TD = TST->getTemplateName().getAsTemplateDecl();
197 if (!TD)
198 continue;
199 if (auto *BasePrimaryTemplate =
200 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
201 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
202 BaseRD = BasePrimaryTemplate;
203 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
204 if (const ClassTemplatePartialSpecializationDecl *PS =
205 CTD->findPartialSpecialization(Base.getType()))
206 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
207 BaseRD = PS;
208 }
209 }
210 }
211 if (BaseRD) {
212 for (NamedDecl *ND : BaseRD->lookup(&II)) {
213 if (!isa<TypeDecl>(ND))
214 return UnqualifiedTypeNameLookupResult::FoundNonType;
215 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
216 }
217 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
218 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
219 case UnqualifiedTypeNameLookupResult::FoundNonType:
220 return UnqualifiedTypeNameLookupResult::FoundNonType;
221 case UnqualifiedTypeNameLookupResult::FoundType:
222 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
223 break;
224 case UnqualifiedTypeNameLookupResult::NotFound:
225 break;
226 }
227 }
228 }
229 }
230
231 return FoundTypeDecl;
232 }
233
recoverFromTypeInKnownDependentBase(Sema & S,const IdentifierInfo & II,SourceLocation NameLoc)234 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
235 const IdentifierInfo &II,
236 SourceLocation NameLoc) {
237 // Lookup in the parent class template context, if any.
238 const CXXRecordDecl *RD = nullptr;
239 UnqualifiedTypeNameLookupResult FoundTypeDecl =
240 UnqualifiedTypeNameLookupResult::NotFound;
241 for (DeclContext *DC = S.CurContext;
242 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
243 DC = DC->getParent()) {
244 // Look for type decls in dependent base classes that have known primary
245 // templates.
246 RD = dyn_cast<CXXRecordDecl>(DC);
247 if (RD && RD->getDescribedClassTemplate())
248 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
249 }
250 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
251 return nullptr;
252
253 // We found some types in dependent base classes. Recover as if the user
254 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
255 // lookup during template instantiation.
256 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
257
258 ASTContext &Context = S.Context;
259 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
260 cast<Type>(Context.getRecordType(RD)));
261 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
262
263 CXXScopeSpec SS;
264 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
265
266 TypeLocBuilder Builder;
267 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
268 DepTL.setNameLoc(NameLoc);
269 DepTL.setElaboratedKeywordLoc(SourceLocation());
270 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
271 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
272 }
273
274 /// If the identifier refers to a type name within this scope,
275 /// return the declaration of that type.
276 ///
277 /// This routine performs ordinary name lookup of the identifier II
278 /// within the given scope, with optional C++ scope specifier SS, to
279 /// determine whether the name refers to a type. If so, returns an
280 /// opaque pointer (actually a QualType) corresponding to that
281 /// 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)282 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
283 Scope *S, CXXScopeSpec *SS,
284 bool isClassName, bool HasTrailingDot,
285 ParsedType ObjectTypePtr,
286 bool IsCtorOrDtorName,
287 bool WantNontrivialTypeSourceInfo,
288 bool IsClassTemplateDeductionContext,
289 IdentifierInfo **CorrectedII) {
290 // FIXME: Consider allowing this outside C++1z mode as an extension.
291 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
292 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
293 !isClassName && !HasTrailingDot;
294
295 // Determine where we will perform name lookup.
296 DeclContext *LookupCtx = nullptr;
297 if (ObjectTypePtr) {
298 QualType ObjectType = ObjectTypePtr.get();
299 if (ObjectType->isRecordType())
300 LookupCtx = computeDeclContext(ObjectType);
301 } else if (SS && SS->isNotEmpty()) {
302 LookupCtx = computeDeclContext(*SS, false);
303
304 if (!LookupCtx) {
305 if (isDependentScopeSpecifier(*SS)) {
306 // C++ [temp.res]p3:
307 // A qualified-id that refers to a type and in which the
308 // nested-name-specifier depends on a template-parameter (14.6.2)
309 // shall be prefixed by the keyword typename to indicate that the
310 // qualified-id denotes a type, forming an
311 // elaborated-type-specifier (7.1.5.3).
312 //
313 // We therefore do not perform any name lookup if the result would
314 // refer to a member of an unknown specialization.
315 if (!isClassName && !IsCtorOrDtorName)
316 return nullptr;
317
318 // We know from the grammar that this name refers to a type,
319 // so build a dependent node to describe the type.
320 if (WantNontrivialTypeSourceInfo)
321 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
322
323 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
324 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
325 II, NameLoc);
326 return ParsedType::make(T);
327 }
328
329 return nullptr;
330 }
331
332 if (!LookupCtx->isDependentContext() &&
333 RequireCompleteDeclContext(*SS, LookupCtx))
334 return nullptr;
335 }
336
337 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
338 // lookup for class-names.
339 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
340 LookupOrdinaryName;
341 LookupResult Result(*this, &II, NameLoc, Kind);
342 if (LookupCtx) {
343 // Perform "qualified" name lookup into the declaration context we
344 // computed, which is either the type of the base of a member access
345 // expression or the declaration context associated with a prior
346 // nested-name-specifier.
347 LookupQualifiedName(Result, LookupCtx);
348
349 if (ObjectTypePtr && Result.empty()) {
350 // C++ [basic.lookup.classref]p3:
351 // If the unqualified-id is ~type-name, the type-name is looked up
352 // in the context of the entire postfix-expression. If the type T of
353 // the object expression is of a class type C, the type-name is also
354 // looked up in the scope of class C. At least one of the lookups shall
355 // find a name that refers to (possibly cv-qualified) T.
356 LookupName(Result, S);
357 }
358 } else {
359 // Perform unqualified name lookup.
360 LookupName(Result, S);
361
362 // For unqualified lookup in a class template in MSVC mode, look into
363 // dependent base classes where the primary class template is known.
364 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
365 if (ParsedType TypeInBase =
366 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
367 return TypeInBase;
368 }
369 }
370
371 NamedDecl *IIDecl = nullptr;
372 switch (Result.getResultKind()) {
373 case LookupResult::NotFound:
374 case LookupResult::NotFoundInCurrentInstantiation:
375 if (CorrectedII) {
376 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
377 AllowDeducedTemplate);
378 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
379 S, SS, CCC, CTK_ErrorRecovery);
380 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
381 TemplateTy Template;
382 bool MemberOfUnknownSpecialization;
383 UnqualifiedId TemplateName;
384 TemplateName.setIdentifier(NewII, NameLoc);
385 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
386 CXXScopeSpec NewSS, *NewSSPtr = SS;
387 if (SS && NNS) {
388 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
389 NewSSPtr = &NewSS;
390 }
391 if (Correction && (NNS || NewII != &II) &&
392 // Ignore a correction to a template type as the to-be-corrected
393 // identifier is not a template (typo correction for template names
394 // is handled elsewhere).
395 !(getLangOpts().CPlusPlus && NewSSPtr &&
396 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
397 Template, MemberOfUnknownSpecialization))) {
398 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
399 isClassName, HasTrailingDot, ObjectTypePtr,
400 IsCtorOrDtorName,
401 WantNontrivialTypeSourceInfo,
402 IsClassTemplateDeductionContext);
403 if (Ty) {
404 diagnoseTypo(Correction,
405 PDiag(diag::err_unknown_type_or_class_name_suggest)
406 << Result.getLookupName() << isClassName);
407 if (SS && NNS)
408 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
409 *CorrectedII = NewII;
410 return Ty;
411 }
412 }
413 }
414 // If typo correction failed or was not performed, fall through
415 LLVM_FALLTHROUGH;
416 case LookupResult::FoundOverloaded:
417 case LookupResult::FoundUnresolvedValue:
418 Result.suppressDiagnostics();
419 return nullptr;
420
421 case LookupResult::Ambiguous:
422 // Recover from type-hiding ambiguities by hiding the type. We'll
423 // do the lookup again when looking for an object, and we can
424 // diagnose the error then. If we don't do this, then the error
425 // about hiding the type will be immediately followed by an error
426 // that only makes sense if the identifier was treated like a type.
427 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
428 Result.suppressDiagnostics();
429 return nullptr;
430 }
431
432 // Look to see if we have a type anywhere in the list of results.
433 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
434 Res != ResEnd; ++Res) {
435 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
436 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
437 if (!IIDecl ||
438 (*Res)->getLocation().getRawEncoding() <
439 IIDecl->getLocation().getRawEncoding())
440 IIDecl = *Res;
441 }
442 }
443
444 if (!IIDecl) {
445 // None of the entities we found is a type, so there is no way
446 // to even assume that the result is a type. In this case, don't
447 // complain about the ambiguity. The parser will either try to
448 // perform this lookup again (e.g., as an object name), which
449 // will produce the ambiguity, or will complain that it expected
450 // a type name.
451 Result.suppressDiagnostics();
452 return nullptr;
453 }
454
455 // We found a type within the ambiguous lookup; diagnose the
456 // ambiguity and then return that type. This might be the right
457 // answer, or it might not be, but it suppresses any attempt to
458 // perform the name lookup again.
459 break;
460
461 case LookupResult::Found:
462 IIDecl = Result.getFoundDecl();
463 break;
464 }
465
466 assert(IIDecl && "Didn't find decl");
467
468 QualType T;
469 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
470 // C++ [class.qual]p2: A lookup that would find the injected-class-name
471 // instead names the constructors of the class, except when naming a class.
472 // This is ill-formed when we're not actually forming a ctor or dtor name.
473 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
474 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
475 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
476 FoundRD->isInjectedClassName() &&
477 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
478 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
479 << &II << /*Type*/1;
480
481 DiagnoseUseOfDecl(IIDecl, NameLoc);
482
483 T = Context.getTypeDeclType(TD);
484 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
485 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
486 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
487 if (!HasTrailingDot)
488 T = Context.getObjCInterfaceType(IDecl);
489 } else if (AllowDeducedTemplate) {
490 if (auto *TD = getAsTypeTemplateDecl(IIDecl))
491 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
492 QualType(), false);
493 }
494
495 if (T.isNull()) {
496 // If it's not plausibly a type, suppress diagnostics.
497 Result.suppressDiagnostics();
498 return nullptr;
499 }
500
501 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
502 // constructor or destructor name (in such a case, the scope specifier
503 // will be attached to the enclosing Expr or Decl node).
504 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
505 !isa<ObjCInterfaceDecl>(IIDecl)) {
506 if (WantNontrivialTypeSourceInfo) {
507 // Construct a type with type-source information.
508 TypeLocBuilder Builder;
509 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
510
511 T = getElaboratedType(ETK_None, *SS, T);
512 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
513 ElabTL.setElaboratedKeywordLoc(SourceLocation());
514 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
515 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
516 } else {
517 T = getElaboratedType(ETK_None, *SS, T);
518 }
519 }
520
521 return ParsedType::make(T);
522 }
523
524 // Builds a fake NNS for the given decl context.
525 static NestedNameSpecifier *
synthesizeCurrentNestedNameSpecifier(ASTContext & Context,DeclContext * DC)526 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
527 for (;; DC = DC->getLookupParent()) {
528 DC = DC->getPrimaryContext();
529 auto *ND = dyn_cast<NamespaceDecl>(DC);
530 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
531 return NestedNameSpecifier::Create(Context, nullptr, ND);
532 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
533 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
534 RD->getTypeForDecl());
535 else if (isa<TranslationUnitDecl>(DC))
536 return NestedNameSpecifier::GlobalSpecifier(Context);
537 }
538 llvm_unreachable("something isn't in TU scope?");
539 }
540
541 /// Find the parent class with dependent bases of the innermost enclosing method
542 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
543 /// up allowing unqualified dependent type names at class-level, which MSVC
544 /// correctly rejects.
545 static const CXXRecordDecl *
findRecordWithDependentBasesOfEnclosingMethod(const DeclContext * DC)546 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
547 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
548 DC = DC->getPrimaryContext();
549 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
550 if (MD->getParent()->hasAnyDependentBases())
551 return MD->getParent();
552 }
553 return nullptr;
554 }
555
ActOnMSVCUnknownTypeName(const IdentifierInfo & II,SourceLocation NameLoc,bool IsTemplateTypeArg)556 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
557 SourceLocation NameLoc,
558 bool IsTemplateTypeArg) {
559 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
560
561 NestedNameSpecifier *NNS = nullptr;
562 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
563 // If we weren't able to parse a default template argument, delay lookup
564 // until instantiation time by making a non-dependent DependentTypeName. We
565 // pretend we saw a NestedNameSpecifier referring to the current scope, and
566 // lookup is retried.
567 // FIXME: This hurts our diagnostic quality, since we get errors like "no
568 // type named 'Foo' in 'current_namespace'" when the user didn't write any
569 // name specifiers.
570 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
571 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
572 } else if (const CXXRecordDecl *RD =
573 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
574 // Build a DependentNameType that will perform lookup into RD at
575 // instantiation time.
576 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
577 RD->getTypeForDecl());
578
579 // Diagnose that this identifier was undeclared, and retry the lookup during
580 // template instantiation.
581 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
582 << RD;
583 } else {
584 // This is not a situation that we should recover from.
585 return ParsedType();
586 }
587
588 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
589
590 // Build type location information. We synthesized the qualifier, so we have
591 // to build a fake NestedNameSpecifierLoc.
592 NestedNameSpecifierLocBuilder NNSLocBuilder;
593 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
594 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
595
596 TypeLocBuilder Builder;
597 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
598 DepTL.setNameLoc(NameLoc);
599 DepTL.setElaboratedKeywordLoc(SourceLocation());
600 DepTL.setQualifierLoc(QualifierLoc);
601 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
602 }
603
604 /// isTagName() - This method is called *for error recovery purposes only*
605 /// to determine if the specified name is a valid tag name ("struct foo"). If
606 /// so, this returns the TST for the tag corresponding to it (TST_enum,
607 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
608 /// cases in C where the user forgot to specify the tag.
isTagName(IdentifierInfo & II,Scope * S)609 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
610 // Do a tag name lookup in this scope.
611 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
612 LookupName(R, S, false);
613 R.suppressDiagnostics();
614 if (R.getResultKind() == LookupResult::Found)
615 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
616 switch (TD->getTagKind()) {
617 case TTK_Struct: return DeclSpec::TST_struct;
618 case TTK_Interface: return DeclSpec::TST_interface;
619 case TTK_Union: return DeclSpec::TST_union;
620 case TTK_Class: return DeclSpec::TST_class;
621 case TTK_Enum: return DeclSpec::TST_enum;
622 }
623 }
624
625 return DeclSpec::TST_unspecified;
626 }
627
628 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
629 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
630 /// then downgrade the missing typename error to a warning.
631 /// This is needed for MSVC compatibility; Example:
632 /// @code
633 /// template<class T> class A {
634 /// public:
635 /// typedef int TYPE;
636 /// };
637 /// template<class T> class B : public A<T> {
638 /// public:
639 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
640 /// };
641 /// @endcode
isMicrosoftMissingTypename(const CXXScopeSpec * SS,Scope * S)642 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
643 if (CurContext->isRecord()) {
644 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
645 return true;
646
647 const Type *Ty = SS->getScopeRep()->getAsType();
648
649 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
650 for (const auto &Base : RD->bases())
651 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
652 return true;
653 return S->isFunctionPrototypeScope();
654 }
655 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
656 }
657
DiagnoseUnknownTypeName(IdentifierInfo * & II,SourceLocation IILoc,Scope * S,CXXScopeSpec * SS,ParsedType & SuggestedType,bool IsTemplateName)658 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
659 SourceLocation IILoc,
660 Scope *S,
661 CXXScopeSpec *SS,
662 ParsedType &SuggestedType,
663 bool IsTemplateName) {
664 // Don't report typename errors for editor placeholders.
665 if (II->isEditorPlaceholder())
666 return;
667 // We don't have anything to suggest (yet).
668 SuggestedType = nullptr;
669
670 // There may have been a typo in the name of the type. Look up typo
671 // results, in case we have something that we can suggest.
672 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
673 /*AllowTemplates=*/IsTemplateName,
674 /*AllowNonTemplates=*/!IsTemplateName);
675 if (TypoCorrection Corrected =
676 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
677 CCC, CTK_ErrorRecovery)) {
678 // FIXME: Support error recovery for the template-name case.
679 bool CanRecover = !IsTemplateName;
680 if (Corrected.isKeyword()) {
681 // We corrected to a keyword.
682 diagnoseTypo(Corrected,
683 PDiag(IsTemplateName ? diag::err_no_template_suggest
684 : diag::err_unknown_typename_suggest)
685 << II);
686 II = Corrected.getCorrectionAsIdentifierInfo();
687 } else {
688 // We found a similarly-named type or interface; suggest that.
689 if (!SS || !SS->isSet()) {
690 diagnoseTypo(Corrected,
691 PDiag(IsTemplateName ? diag::err_no_template_suggest
692 : diag::err_unknown_typename_suggest)
693 << II, CanRecover);
694 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
695 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
696 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
697 II->getName().equals(CorrectedStr);
698 diagnoseTypo(Corrected,
699 PDiag(IsTemplateName
700 ? diag::err_no_member_template_suggest
701 : diag::err_unknown_nested_typename_suggest)
702 << II << DC << DroppedSpecifier << SS->getRange(),
703 CanRecover);
704 } else {
705 llvm_unreachable("could not have corrected a typo here");
706 }
707
708 if (!CanRecover)
709 return;
710
711 CXXScopeSpec tmpSS;
712 if (Corrected.getCorrectionSpecifier())
713 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
714 SourceRange(IILoc));
715 // FIXME: Support class template argument deduction here.
716 SuggestedType =
717 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
718 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
719 /*IsCtorOrDtorName=*/false,
720 /*WantNontrivialTypeSourceInfo=*/true);
721 }
722 return;
723 }
724
725 if (getLangOpts().CPlusPlus && !IsTemplateName) {
726 // See if II is a class template that the user forgot to pass arguments to.
727 UnqualifiedId Name;
728 Name.setIdentifier(II, IILoc);
729 CXXScopeSpec EmptySS;
730 TemplateTy TemplateResult;
731 bool MemberOfUnknownSpecialization;
732 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
733 Name, nullptr, true, TemplateResult,
734 MemberOfUnknownSpecialization) == TNK_Type_template) {
735 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
736 return;
737 }
738 }
739
740 // FIXME: Should we move the logic that tries to recover from a missing tag
741 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
742
743 if (!SS || (!SS->isSet() && !SS->isInvalid()))
744 Diag(IILoc, IsTemplateName ? diag::err_no_template
745 : diag::err_unknown_typename)
746 << II;
747 else if (DeclContext *DC = computeDeclContext(*SS, false))
748 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
749 : diag::err_typename_nested_not_found)
750 << II << DC << SS->getRange();
751 else if (isDependentScopeSpecifier(*SS)) {
752 unsigned DiagID = diag::err_typename_missing;
753 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
754 DiagID = diag::ext_typename_missing;
755
756 Diag(SS->getRange().getBegin(), DiagID)
757 << SS->getScopeRep() << II->getName()
758 << SourceRange(SS->getRange().getBegin(), IILoc)
759 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
760 SuggestedType = ActOnTypenameType(S, SourceLocation(),
761 *SS, *II, IILoc).get();
762 } else {
763 assert(SS && SS->isInvalid() &&
764 "Invalid scope specifier has already been diagnosed");
765 }
766 }
767
768 /// Determine whether the given result set contains either a type name
769 /// or
isResultTypeOrTemplate(LookupResult & R,const Token & NextToken)770 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
771 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
772 NextToken.is(tok::less);
773
774 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
775 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
776 return true;
777
778 if (CheckTemplate && isa<TemplateDecl>(*I))
779 return true;
780 }
781
782 return false;
783 }
784
isTagTypeWithMissingTag(Sema & SemaRef,LookupResult & Result,Scope * S,CXXScopeSpec & SS,IdentifierInfo * & Name,SourceLocation NameLoc)785 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
786 Scope *S, CXXScopeSpec &SS,
787 IdentifierInfo *&Name,
788 SourceLocation NameLoc) {
789 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
790 SemaRef.LookupParsedName(R, S, &SS);
791 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
792 StringRef FixItTagName;
793 switch (Tag->getTagKind()) {
794 case TTK_Class:
795 FixItTagName = "class ";
796 break;
797
798 case TTK_Enum:
799 FixItTagName = "enum ";
800 break;
801
802 case TTK_Struct:
803 FixItTagName = "struct ";
804 break;
805
806 case TTK_Interface:
807 FixItTagName = "__interface ";
808 break;
809
810 case TTK_Union:
811 FixItTagName = "union ";
812 break;
813 }
814
815 StringRef TagName = FixItTagName.drop_back();
816 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
817 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
818 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
819
820 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
821 I != IEnd; ++I)
822 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
823 << Name << TagName;
824
825 // Replace lookup results with just the tag decl.
826 Result.clear(Sema::LookupTagName);
827 SemaRef.LookupParsedName(Result, S, &SS);
828 return true;
829 }
830
831 return false;
832 }
833
834 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
buildNestedType(Sema & S,CXXScopeSpec & SS,QualType T,SourceLocation NameLoc)835 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
836 QualType T, SourceLocation NameLoc) {
837 ASTContext &Context = S.Context;
838
839 TypeLocBuilder Builder;
840 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
841
842 T = S.getElaboratedType(ETK_None, SS, T);
843 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
844 ElabTL.setElaboratedKeywordLoc(SourceLocation());
845 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
846 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
847 }
848
ClassifyName(Scope * S,CXXScopeSpec & SS,IdentifierInfo * & Name,SourceLocation NameLoc,const Token & NextToken,CorrectionCandidateCallback * CCC)849 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
850 IdentifierInfo *&Name,
851 SourceLocation NameLoc,
852 const Token &NextToken,
853 CorrectionCandidateCallback *CCC) {
854 DeclarationNameInfo NameInfo(Name, NameLoc);
855 ObjCMethodDecl *CurMethod = getCurMethodDecl();
856
857 assert(NextToken.isNot(tok::coloncolon) &&
858 "parse nested name specifiers before calling ClassifyName");
859 if (getLangOpts().CPlusPlus && SS.isSet() &&
860 isCurrentClassName(*Name, S, &SS)) {
861 // Per [class.qual]p2, this names the constructors of SS, not the
862 // injected-class-name. We don't have a classification for that.
863 // There's not much point caching this result, since the parser
864 // will reject it later.
865 return NameClassification::Unknown();
866 }
867
868 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
869 LookupParsedName(Result, S, &SS, !CurMethod);
870
871 if (SS.isInvalid())
872 return NameClassification::Error();
873
874 // For unqualified lookup in a class template in MSVC mode, look into
875 // dependent base classes where the primary class template is known.
876 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
877 if (ParsedType TypeInBase =
878 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
879 return TypeInBase;
880 }
881
882 // Perform lookup for Objective-C instance variables (including automatically
883 // synthesized instance variables), if we're in an Objective-C method.
884 // FIXME: This lookup really, really needs to be folded in to the normal
885 // unqualified lookup mechanism.
886 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
887 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
888 if (Ivar.isInvalid())
889 return NameClassification::Error();
890 if (Ivar.isUsable())
891 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
892
893 // We defer builtin creation until after ivar lookup inside ObjC methods.
894 if (Result.empty())
895 LookupBuiltin(Result);
896 }
897
898 bool SecondTry = false;
899 bool IsFilteredTemplateName = false;
900
901 Corrected:
902 switch (Result.getResultKind()) {
903 case LookupResult::NotFound:
904 // If an unqualified-id is followed by a '(', then we have a function
905 // call.
906 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
907 // In C++, this is an ADL-only call.
908 // FIXME: Reference?
909 if (getLangOpts().CPlusPlus)
910 return NameClassification::UndeclaredNonType();
911
912 // C90 6.3.2.2:
913 // If the expression that precedes the parenthesized argument list in a
914 // function call consists solely of an identifier, and if no
915 // declaration is visible for this identifier, the identifier is
916 // implicitly declared exactly as if, in the innermost block containing
917 // the function call, the declaration
918 //
919 // extern int identifier ();
920 //
921 // appeared.
922 //
923 // We also allow this in C99 as an extension.
924 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
925 return NameClassification::NonType(D);
926 }
927
928 if (getLangOpts().CPlusPlus2a && SS.isEmpty() && NextToken.is(tok::less)) {
929 // In C++20 onwards, this could be an ADL-only call to a function
930 // template, and we're required to assume that this is a template name.
931 //
932 // FIXME: Find a way to still do typo correction in this case.
933 TemplateName Template =
934 Context.getAssumedTemplateName(NameInfo.getName());
935 return NameClassification::UndeclaredTemplate(Template);
936 }
937
938 // In C, we first see whether there is a tag type by the same name, in
939 // which case it's likely that the user just forgot to write "enum",
940 // "struct", or "union".
941 if (!getLangOpts().CPlusPlus && !SecondTry &&
942 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
943 break;
944 }
945
946 // Perform typo correction to determine if there is another name that is
947 // close to this name.
948 if (!SecondTry && CCC) {
949 SecondTry = true;
950 if (TypoCorrection Corrected =
951 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
952 &SS, *CCC, CTK_ErrorRecovery)) {
953 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
954 unsigned QualifiedDiag = diag::err_no_member_suggest;
955
956 NamedDecl *FirstDecl = Corrected.getFoundDecl();
957 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
958 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
959 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
960 UnqualifiedDiag = diag::err_no_template_suggest;
961 QualifiedDiag = diag::err_no_member_template_suggest;
962 } else if (UnderlyingFirstDecl &&
963 (isa<TypeDecl>(UnderlyingFirstDecl) ||
964 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
965 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
966 UnqualifiedDiag = diag::err_unknown_typename_suggest;
967 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
968 }
969
970 if (SS.isEmpty()) {
971 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
972 } else {// FIXME: is this even reachable? Test it.
973 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
974 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
975 Name->getName().equals(CorrectedStr);
976 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
977 << Name << computeDeclContext(SS, false)
978 << DroppedSpecifier << SS.getRange());
979 }
980
981 // Update the name, so that the caller has the new name.
982 Name = Corrected.getCorrectionAsIdentifierInfo();
983
984 // Typo correction corrected to a keyword.
985 if (Corrected.isKeyword())
986 return Name;
987
988 // Also update the LookupResult...
989 // FIXME: This should probably go away at some point
990 Result.clear();
991 Result.setLookupName(Corrected.getCorrection());
992 if (FirstDecl)
993 Result.addDecl(FirstDecl);
994
995 // If we found an Objective-C instance variable, let
996 // LookupInObjCMethod build the appropriate expression to
997 // reference the ivar.
998 // FIXME: This is a gross hack.
999 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1000 DeclResult R =
1001 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1002 if (R.isInvalid())
1003 return NameClassification::Error();
1004 if (R.isUsable())
1005 return NameClassification::NonType(Ivar);
1006 }
1007
1008 goto Corrected;
1009 }
1010 }
1011
1012 // We failed to correct; just fall through and let the parser deal with it.
1013 Result.suppressDiagnostics();
1014 return NameClassification::Unknown();
1015
1016 case LookupResult::NotFoundInCurrentInstantiation: {
1017 // We performed name lookup into the current instantiation, and there were
1018 // dependent bases, so we treat this result the same way as any other
1019 // dependent nested-name-specifier.
1020
1021 // C++ [temp.res]p2:
1022 // A name used in a template declaration or definition and that is
1023 // dependent on a template-parameter is assumed not to name a type
1024 // unless the applicable name lookup finds a type name or the name is
1025 // qualified by the keyword typename.
1026 //
1027 // FIXME: If the next token is '<', we might want to ask the parser to
1028 // perform some heroics to see if we actually have a
1029 // template-argument-list, which would indicate a missing 'template'
1030 // keyword here.
1031 return NameClassification::DependentNonType();
1032 }
1033
1034 case LookupResult::Found:
1035 case LookupResult::FoundOverloaded:
1036 case LookupResult::FoundUnresolvedValue:
1037 break;
1038
1039 case LookupResult::Ambiguous:
1040 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1041 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1042 /*AllowDependent=*/false)) {
1043 // C++ [temp.local]p3:
1044 // A lookup that finds an injected-class-name (10.2) can result in an
1045 // ambiguity in certain cases (for example, if it is found in more than
1046 // one base class). If all of the injected-class-names that are found
1047 // refer to specializations of the same class template, and if the name
1048 // is followed by a template-argument-list, the reference refers to the
1049 // class template itself and not a specialization thereof, and is not
1050 // ambiguous.
1051 //
1052 // This filtering can make an ambiguous result into an unambiguous one,
1053 // so try again after filtering out template names.
1054 FilterAcceptableTemplateNames(Result);
1055 if (!Result.isAmbiguous()) {
1056 IsFilteredTemplateName = true;
1057 break;
1058 }
1059 }
1060
1061 // Diagnose the ambiguity and return an error.
1062 return NameClassification::Error();
1063 }
1064
1065 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1066 (IsFilteredTemplateName ||
1067 hasAnyAcceptableTemplateNames(
1068 Result, /*AllowFunctionTemplates=*/true,
1069 /*AllowDependent=*/false,
1070 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1071 getLangOpts().CPlusPlus2a))) {
1072 // C++ [temp.names]p3:
1073 // After name lookup (3.4) finds that a name is a template-name or that
1074 // an operator-function-id or a literal- operator-id refers to a set of
1075 // overloaded functions any member of which is a function template if
1076 // this is followed by a <, the < is always taken as the delimiter of a
1077 // template-argument-list and never as the less-than operator.
1078 // C++2a [temp.names]p2:
1079 // A name is also considered to refer to a template if it is an
1080 // unqualified-id followed by a < and name lookup finds either one
1081 // or more functions or finds nothing.
1082 if (!IsFilteredTemplateName)
1083 FilterAcceptableTemplateNames(Result);
1084
1085 bool IsFunctionTemplate;
1086 bool IsVarTemplate;
1087 TemplateName Template;
1088 if (Result.end() - Result.begin() > 1) {
1089 IsFunctionTemplate = true;
1090 Template = Context.getOverloadedTemplateName(Result.begin(),
1091 Result.end());
1092 } else if (!Result.empty()) {
1093 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1094 *Result.begin(), /*AllowFunctionTemplates=*/true,
1095 /*AllowDependent=*/false));
1096 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1097 IsVarTemplate = isa<VarTemplateDecl>(TD);
1098
1099 if (SS.isNotEmpty())
1100 Template =
1101 Context.getQualifiedTemplateName(SS.getScopeRep(),
1102 /*TemplateKeyword=*/false, TD);
1103 else
1104 Template = TemplateName(TD);
1105 } else {
1106 // All results were non-template functions. This is a function template
1107 // name.
1108 IsFunctionTemplate = true;
1109 Template = Context.getAssumedTemplateName(NameInfo.getName());
1110 }
1111
1112 if (IsFunctionTemplate) {
1113 // Function templates always go through overload resolution, at which
1114 // point we'll perform the various checks (e.g., accessibility) we need
1115 // to based on which function we selected.
1116 Result.suppressDiagnostics();
1117
1118 return NameClassification::FunctionTemplate(Template);
1119 }
1120
1121 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1122 : NameClassification::TypeTemplate(Template);
1123 }
1124
1125 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1126 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1127 DiagnoseUseOfDecl(Type, NameLoc);
1128 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1129 QualType T = Context.getTypeDeclType(Type);
1130 if (SS.isNotEmpty())
1131 return buildNestedType(*this, SS, T, NameLoc);
1132 return ParsedType::make(T);
1133 }
1134
1135 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1136 if (!Class) {
1137 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1138 if (ObjCCompatibleAliasDecl *Alias =
1139 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1140 Class = Alias->getClassInterface();
1141 }
1142
1143 if (Class) {
1144 DiagnoseUseOfDecl(Class, NameLoc);
1145
1146 if (NextToken.is(tok::period)) {
1147 // Interface. <something> is parsed as a property reference expression.
1148 // Just return "unknown" as a fall-through for now.
1149 Result.suppressDiagnostics();
1150 return NameClassification::Unknown();
1151 }
1152
1153 QualType T = Context.getObjCInterfaceType(Class);
1154 return ParsedType::make(T);
1155 }
1156
1157 if (isa<ConceptDecl>(FirstDecl))
1158 return NameClassification::Concept(
1159 TemplateName(cast<TemplateDecl>(FirstDecl)));
1160
1161 // We can have a type template here if we're classifying a template argument.
1162 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1163 !isa<VarTemplateDecl>(FirstDecl))
1164 return NameClassification::TypeTemplate(
1165 TemplateName(cast<TemplateDecl>(FirstDecl)));
1166
1167 // Check for a tag type hidden by a non-type decl in a few cases where it
1168 // seems likely a type is wanted instead of the non-type that was found.
1169 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1170 if ((NextToken.is(tok::identifier) ||
1171 (NextIsOp &&
1172 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1173 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1174 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1175 DiagnoseUseOfDecl(Type, NameLoc);
1176 QualType T = Context.getTypeDeclType(Type);
1177 if (SS.isNotEmpty())
1178 return buildNestedType(*this, SS, T, NameLoc);
1179 return ParsedType::make(T);
1180 }
1181
1182 // FIXME: This is context-dependent. We need to defer building the member
1183 // expression until the classification is consumed.
1184 if (FirstDecl->isCXXClassMember())
1185 return NameClassification::ContextIndependentExpr(
1186 BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr,
1187 S));
1188
1189 // If we already know which single declaration is referenced, just annotate
1190 // that declaration directly.
1191 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1192 if (Result.isSingleResult() && !ADL)
1193 return NameClassification::NonType(Result.getRepresentativeDecl());
1194
1195 // Build an UnresolvedLookupExpr. Note that this doesn't depend on the
1196 // context in which we performed classification, so it's safe to do now.
1197 return NameClassification::ContextIndependentExpr(
1198 BuildDeclarationNameExpr(SS, Result, ADL));
1199 }
1200
1201 ExprResult
ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo * Name,SourceLocation NameLoc)1202 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1203 SourceLocation NameLoc) {
1204 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1205 CXXScopeSpec SS;
1206 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1207 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1208 }
1209
1210 ExprResult
ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation NameLoc,bool IsAddressOfOperand)1211 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1212 IdentifierInfo *Name,
1213 SourceLocation NameLoc,
1214 bool IsAddressOfOperand) {
1215 DeclarationNameInfo NameInfo(Name, NameLoc);
1216 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1217 NameInfo, IsAddressOfOperand,
1218 /*TemplateArgs=*/nullptr);
1219 }
1220
ActOnNameClassifiedAsNonType(Scope * S,const CXXScopeSpec & SS,NamedDecl * Found,SourceLocation NameLoc,const Token & NextToken)1221 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1222 NamedDecl *Found,
1223 SourceLocation NameLoc,
1224 const Token &NextToken) {
1225 if (getCurMethodDecl() && SS.isEmpty())
1226 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1227 return BuildIvarRefExpr(S, NameLoc, Ivar);
1228
1229 // Reconstruct the lookup result.
1230 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1231 Result.addDecl(Found);
1232 Result.resolveKind();
1233
1234 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1235 return BuildDeclarationNameExpr(SS, Result, ADL);
1236 }
1237
1238 Sema::TemplateNameKindForDiagnostics
getTemplateNameKindForDiagnostics(TemplateName Name)1239 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1240 auto *TD = Name.getAsTemplateDecl();
1241 if (!TD)
1242 return TemplateNameKindForDiagnostics::DependentTemplate;
1243 if (isa<ClassTemplateDecl>(TD))
1244 return TemplateNameKindForDiagnostics::ClassTemplate;
1245 if (isa<FunctionTemplateDecl>(TD))
1246 return TemplateNameKindForDiagnostics::FunctionTemplate;
1247 if (isa<VarTemplateDecl>(TD))
1248 return TemplateNameKindForDiagnostics::VarTemplate;
1249 if (isa<TypeAliasTemplateDecl>(TD))
1250 return TemplateNameKindForDiagnostics::AliasTemplate;
1251 if (isa<TemplateTemplateParmDecl>(TD))
1252 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1253 if (isa<ConceptDecl>(TD))
1254 return TemplateNameKindForDiagnostics::Concept;
1255 return TemplateNameKindForDiagnostics::DependentTemplate;
1256 }
1257
1258 // Determines the context to return to after temporarily entering a
1259 // context. This depends in an unnecessarily complicated way on the
1260 // exact ordering of callbacks from the parser.
getContainingDC(DeclContext * DC)1261 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1262
1263 // Functions defined inline within classes aren't parsed until we've
1264 // finished parsing the top-level class, so the top-level class is
1265 // the context we'll need to return to.
1266 // A Lambda call operator whose parent is a class must not be treated
1267 // as an inline member function. A Lambda can be used legally
1268 // either as an in-class member initializer or a default argument. These
1269 // are parsed once the class has been marked complete and so the containing
1270 // context would be the nested class (when the lambda is defined in one);
1271 // If the class is not complete, then the lambda is being used in an
1272 // ill-formed fashion (such as to specify the width of a bit-field, or
1273 // in an array-bound) - in which case we still want to return the
1274 // lexically containing DC (which could be a nested class).
1275 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1276 DC = DC->getLexicalParent();
1277
1278 // A function not defined within a class will always return to its
1279 // lexical context.
1280 if (!isa<CXXRecordDecl>(DC))
1281 return DC;
1282
1283 // A C++ inline method/friend is parsed *after* the topmost class
1284 // it was declared in is fully parsed ("complete"); the topmost
1285 // class is the context we need to return to.
1286 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1287 DC = RD;
1288
1289 // Return the declaration context of the topmost class the inline method is
1290 // declared in.
1291 return DC;
1292 }
1293
1294 return DC->getLexicalParent();
1295 }
1296
PushDeclContext(Scope * S,DeclContext * DC)1297 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1298 assert(getContainingDC(DC) == CurContext &&
1299 "The next DeclContext should be lexically contained in the current one.");
1300 CurContext = DC;
1301 S->setEntity(DC);
1302 }
1303
PopDeclContext()1304 void Sema::PopDeclContext() {
1305 assert(CurContext && "DeclContext imbalance!");
1306
1307 CurContext = getContainingDC(CurContext);
1308 assert(CurContext && "Popped translation unit!");
1309 }
1310
ActOnTagStartSkippedDefinition(Scope * S,Decl * D)1311 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1312 Decl *D) {
1313 // Unlike PushDeclContext, the context to which we return is not necessarily
1314 // the containing DC of TD, because the new context will be some pre-existing
1315 // TagDecl definition instead of a fresh one.
1316 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1317 CurContext = cast<TagDecl>(D)->getDefinition();
1318 assert(CurContext && "skipping definition of undefined tag");
1319 // Start lookups from the parent of the current context; we don't want to look
1320 // into the pre-existing complete definition.
1321 S->setEntity(CurContext->getLookupParent());
1322 return Result;
1323 }
1324
ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)1325 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1326 CurContext = static_cast<decltype(CurContext)>(Context);
1327 }
1328
1329 /// EnterDeclaratorContext - Used when we must lookup names in the context
1330 /// of a declarator's nested name specifier.
1331 ///
EnterDeclaratorContext(Scope * S,DeclContext * DC)1332 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1333 // C++0x [basic.lookup.unqual]p13:
1334 // A name used in the definition of a static data member of class
1335 // X (after the qualified-id of the static member) is looked up as
1336 // if the name was used in a member function of X.
1337 // C++0x [basic.lookup.unqual]p14:
1338 // If a variable member of a namespace is defined outside of the
1339 // scope of its namespace then any name used in the definition of
1340 // the variable member (after the declarator-id) is looked up as
1341 // if the definition of the variable member occurred in its
1342 // namespace.
1343 // Both of these imply that we should push a scope whose context
1344 // is the semantic context of the declaration. We can't use
1345 // PushDeclContext here because that context is not necessarily
1346 // lexically contained in the current context. Fortunately,
1347 // the containing scope should have the appropriate information.
1348
1349 assert(!S->getEntity() && "scope already has entity");
1350
1351 #ifndef NDEBUG
1352 Scope *Ancestor = S->getParent();
1353 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1354 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1355 #endif
1356
1357 CurContext = DC;
1358 S->setEntity(DC);
1359 }
1360
ExitDeclaratorContext(Scope * S)1361 void Sema::ExitDeclaratorContext(Scope *S) {
1362 assert(S->getEntity() == CurContext && "Context imbalance!");
1363
1364 // Switch back to the lexical context. The safety of this is
1365 // enforced by an assert in EnterDeclaratorContext.
1366 Scope *Ancestor = S->getParent();
1367 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1368 CurContext = Ancestor->getEntity();
1369
1370 // We don't need to do anything with the scope, which is going to
1371 // disappear.
1372 }
1373
ActOnReenterFunctionContext(Scope * S,Decl * D)1374 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1375 // We assume that the caller has already called
1376 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1377 FunctionDecl *FD = D->getAsFunction();
1378 if (!FD)
1379 return;
1380
1381 // Same implementation as PushDeclContext, but enters the context
1382 // from the lexical parent, rather than the top-level class.
1383 assert(CurContext == FD->getLexicalParent() &&
1384 "The next DeclContext should be lexically contained in the current one.");
1385 CurContext = FD;
1386 S->setEntity(CurContext);
1387
1388 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1389 ParmVarDecl *Param = FD->getParamDecl(P);
1390 // If the parameter has an identifier, then add it to the scope
1391 if (Param->getIdentifier()) {
1392 S->AddDecl(Param);
1393 IdResolver.AddDecl(Param);
1394 }
1395 }
1396 }
1397
ActOnExitFunctionContext()1398 void Sema::ActOnExitFunctionContext() {
1399 // Same implementation as PopDeclContext, but returns to the lexical parent,
1400 // rather than the top-level class.
1401 assert(CurContext && "DeclContext imbalance!");
1402 CurContext = CurContext->getLexicalParent();
1403 assert(CurContext && "Popped translation unit!");
1404 }
1405
1406 /// Determine whether we allow overloading of the function
1407 /// PrevDecl with another declaration.
1408 ///
1409 /// This routine determines whether overloading is possible, not
1410 /// whether some new function is actually an overload. It will return
1411 /// true in C++ (where we can always provide overloads) or, as an
1412 /// extension, in C when the previous function is already an
1413 /// overloaded function declaration or has the "overloadable"
1414 /// attribute.
AllowOverloadingOfFunction(LookupResult & Previous,ASTContext & Context,const FunctionDecl * New)1415 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1416 ASTContext &Context,
1417 const FunctionDecl *New) {
1418 if (Context.getLangOpts().CPlusPlus)
1419 return true;
1420
1421 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1422 return true;
1423
1424 return Previous.getResultKind() == LookupResult::Found &&
1425 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1426 New->hasAttr<OverloadableAttr>());
1427 }
1428
1429 /// Add this decl to the scope shadowed decl chains.
PushOnScopeChains(NamedDecl * D,Scope * S,bool AddToContext)1430 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1431 // Move up the scope chain until we find the nearest enclosing
1432 // non-transparent context. The declaration will be introduced into this
1433 // scope.
1434 while (S->getEntity() && S->getEntity()->isTransparentContext())
1435 S = S->getParent();
1436
1437 // Add scoped declarations into their context, so that they can be
1438 // found later. Declarations without a context won't be inserted
1439 // into any context.
1440 if (AddToContext)
1441 CurContext->addDecl(D);
1442
1443 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1444 // are function-local declarations.
1445 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1446 !D->getDeclContext()->getRedeclContext()->Equals(
1447 D->getLexicalDeclContext()->getRedeclContext()) &&
1448 !D->getLexicalDeclContext()->isFunctionOrMethod())
1449 return;
1450
1451 // Template instantiations should also not be pushed into scope.
1452 if (isa<FunctionDecl>(D) &&
1453 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1454 return;
1455
1456 // If this replaces anything in the current scope,
1457 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1458 IEnd = IdResolver.end();
1459 for (; I != IEnd; ++I) {
1460 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1461 S->RemoveDecl(*I);
1462 IdResolver.RemoveDecl(*I);
1463
1464 // Should only need to replace one decl.
1465 break;
1466 }
1467 }
1468
1469 S->AddDecl(D);
1470
1471 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1472 // Implicitly-generated labels may end up getting generated in an order that
1473 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1474 // the label at the appropriate place in the identifier chain.
1475 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1476 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1477 if (IDC == CurContext) {
1478 if (!S->isDeclScope(*I))
1479 continue;
1480 } else if (IDC->Encloses(CurContext))
1481 break;
1482 }
1483
1484 IdResolver.InsertDeclAfter(I, D);
1485 } else {
1486 IdResolver.AddDecl(D);
1487 }
1488 }
1489
isDeclInScope(NamedDecl * D,DeclContext * Ctx,Scope * S,bool AllowInlineNamespace)1490 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1491 bool AllowInlineNamespace) {
1492 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1493 }
1494
getScopeForDeclContext(Scope * S,DeclContext * DC)1495 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1496 DeclContext *TargetDC = DC->getPrimaryContext();
1497 do {
1498 if (DeclContext *ScopeDC = S->getEntity())
1499 if (ScopeDC->getPrimaryContext() == TargetDC)
1500 return S;
1501 } while ((S = S->getParent()));
1502
1503 return nullptr;
1504 }
1505
1506 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1507 DeclContext*,
1508 ASTContext&);
1509
1510 /// Filters out lookup results that don't fall within the given scope
1511 /// as determined by isDeclInScope.
FilterLookupForScope(LookupResult & R,DeclContext * Ctx,Scope * S,bool ConsiderLinkage,bool AllowInlineNamespace)1512 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1513 bool ConsiderLinkage,
1514 bool AllowInlineNamespace) {
1515 LookupResult::Filter F = R.makeFilter();
1516 while (F.hasNext()) {
1517 NamedDecl *D = F.next();
1518
1519 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1520 continue;
1521
1522 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1523 continue;
1524
1525 F.erase();
1526 }
1527
1528 F.done();
1529 }
1530
1531 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1532 /// have compatible owning modules.
CheckRedeclarationModuleOwnership(NamedDecl * New,NamedDecl * Old)1533 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1534 // FIXME: The Modules TS is not clear about how friend declarations are
1535 // to be treated. It's not meaningful to have different owning modules for
1536 // linkage in redeclarations of the same entity, so for now allow the
1537 // redeclaration and change the owning modules to match.
1538 if (New->getFriendObjectKind() &&
1539 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1540 New->setLocalOwningModule(Old->getOwningModule());
1541 makeMergedDefinitionVisible(New);
1542 return false;
1543 }
1544
1545 Module *NewM = New->getOwningModule();
1546 Module *OldM = Old->getOwningModule();
1547
1548 if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1549 NewM = NewM->Parent;
1550 if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1551 OldM = OldM->Parent;
1552
1553 if (NewM == OldM)
1554 return false;
1555
1556 bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1557 bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1558 if (NewIsModuleInterface || OldIsModuleInterface) {
1559 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1560 // if a declaration of D [...] appears in the purview of a module, all
1561 // other such declarations shall appear in the purview of the same module
1562 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1563 << New
1564 << NewIsModuleInterface
1565 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1566 << OldIsModuleInterface
1567 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1568 Diag(Old->getLocation(), diag::note_previous_declaration);
1569 New->setInvalidDecl();
1570 return true;
1571 }
1572
1573 return false;
1574 }
1575
isUsingDecl(NamedDecl * D)1576 static bool isUsingDecl(NamedDecl *D) {
1577 return isa<UsingShadowDecl>(D) ||
1578 isa<UnresolvedUsingTypenameDecl>(D) ||
1579 isa<UnresolvedUsingValueDecl>(D);
1580 }
1581
1582 /// Removes using shadow declarations from the lookup results.
RemoveUsingDecls(LookupResult & R)1583 static void RemoveUsingDecls(LookupResult &R) {
1584 LookupResult::Filter F = R.makeFilter();
1585 while (F.hasNext())
1586 if (isUsingDecl(F.next()))
1587 F.erase();
1588
1589 F.done();
1590 }
1591
1592 /// Check for this common pattern:
1593 /// @code
1594 /// class S {
1595 /// S(const S&); // DO NOT IMPLEMENT
1596 /// void operator=(const S&); // DO NOT IMPLEMENT
1597 /// };
1598 /// @endcode
IsDisallowedCopyOrAssign(const CXXMethodDecl * D)1599 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1600 // FIXME: Should check for private access too but access is set after we get
1601 // the decl here.
1602 if (D->doesThisDeclarationHaveABody())
1603 return false;
1604
1605 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1606 return CD->isCopyConstructor();
1607 return D->isCopyAssignmentOperator();
1608 }
1609
1610 // We need this to handle
1611 //
1612 // typedef struct {
1613 // void *foo() { return 0; }
1614 // } A;
1615 //
1616 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1617 // for example. If 'A', foo will have external linkage. If we have '*A',
1618 // foo will have no linkage. Since we can't know until we get to the end
1619 // of the typedef, this function finds out if D might have non-external linkage.
1620 // Callers should verify at the end of the TU if it D has external linkage or
1621 // not.
mightHaveNonExternalLinkage(const DeclaratorDecl * D)1622 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1623 const DeclContext *DC = D->getDeclContext();
1624 while (!DC->isTranslationUnit()) {
1625 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1626 if (!RD->hasNameForLinkage())
1627 return true;
1628 }
1629 DC = DC->getParent();
1630 }
1631
1632 return !D->isExternallyVisible();
1633 }
1634
1635 // FIXME: This needs to be refactored; some other isInMainFile users want
1636 // these semantics.
isMainFileLoc(const Sema & S,SourceLocation Loc)1637 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1638 if (S.TUKind != TU_Complete)
1639 return false;
1640 return S.SourceMgr.isInMainFile(Loc);
1641 }
1642
ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl * D) const1643 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1644 assert(D);
1645
1646 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1647 return false;
1648
1649 // Ignore all entities declared within templates, and out-of-line definitions
1650 // of members of class templates.
1651 if (D->getDeclContext()->isDependentContext() ||
1652 D->getLexicalDeclContext()->isDependentContext())
1653 return false;
1654
1655 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1656 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1657 return false;
1658 // A non-out-of-line declaration of a member specialization was implicitly
1659 // instantiated; it's the out-of-line declaration that we're interested in.
1660 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1661 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1662 return false;
1663
1664 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1665 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1666 return false;
1667 } else {
1668 // 'static inline' functions are defined in headers; don't warn.
1669 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1670 return false;
1671 }
1672
1673 if (FD->doesThisDeclarationHaveABody() &&
1674 Context.DeclMustBeEmitted(FD))
1675 return false;
1676 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1677 // Constants and utility variables are defined in headers with internal
1678 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1679 // like "inline".)
1680 if (!isMainFileLoc(*this, VD->getLocation()))
1681 return false;
1682
1683 if (Context.DeclMustBeEmitted(VD))
1684 return false;
1685
1686 if (VD->isStaticDataMember() &&
1687 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1688 return false;
1689 if (VD->isStaticDataMember() &&
1690 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1691 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1692 return false;
1693
1694 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1695 return false;
1696 } else {
1697 return false;
1698 }
1699
1700 // Only warn for unused decls internal to the translation unit.
1701 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1702 // for inline functions defined in the main source file, for instance.
1703 return mightHaveNonExternalLinkage(D);
1704 }
1705
MarkUnusedFileScopedDecl(const DeclaratorDecl * D)1706 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1707 if (!D)
1708 return;
1709
1710 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1711 const FunctionDecl *First = FD->getFirstDecl();
1712 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1713 return; // First should already be in the vector.
1714 }
1715
1716 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1717 const VarDecl *First = VD->getFirstDecl();
1718 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1719 return; // First should already be in the vector.
1720 }
1721
1722 if (ShouldWarnIfUnusedFileScopedDecl(D))
1723 UnusedFileScopedDecls.push_back(D);
1724 }
1725
ShouldDiagnoseUnusedDecl(const NamedDecl * D)1726 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1727 if (D->isInvalidDecl())
1728 return false;
1729
1730 bool Referenced = false;
1731 if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1732 // For a decomposition declaration, warn if none of the bindings are
1733 // referenced, instead of if the variable itself is referenced (which
1734 // it is, by the bindings' expressions).
1735 for (auto *BD : DD->bindings()) {
1736 if (BD->isReferenced()) {
1737 Referenced = true;
1738 break;
1739 }
1740 }
1741 } else if (!D->getDeclName()) {
1742 return false;
1743 } else if (D->isReferenced() || D->isUsed()) {
1744 Referenced = true;
1745 }
1746
1747 if (Referenced || D->hasAttr<UnusedAttr>() ||
1748 D->hasAttr<ObjCPreciseLifetimeAttr>())
1749 return false;
1750
1751 if (isa<LabelDecl>(D))
1752 return true;
1753
1754 // Except for labels, we only care about unused decls that are local to
1755 // functions.
1756 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1757 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1758 // For dependent types, the diagnostic is deferred.
1759 WithinFunction =
1760 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1761 if (!WithinFunction)
1762 return false;
1763
1764 if (isa<TypedefNameDecl>(D))
1765 return true;
1766
1767 // White-list anything that isn't a local variable.
1768 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1769 return false;
1770
1771 // Types of valid local variables should be complete, so this should succeed.
1772 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1773
1774 // White-list anything with an __attribute__((unused)) type.
1775 const auto *Ty = VD->getType().getTypePtr();
1776
1777 // Only look at the outermost level of typedef.
1778 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1779 if (TT->getDecl()->hasAttr<UnusedAttr>())
1780 return false;
1781 }
1782
1783 // If we failed to complete the type for some reason, or if the type is
1784 // dependent, don't diagnose the variable.
1785 if (Ty->isIncompleteType() || Ty->isDependentType())
1786 return false;
1787
1788 // Look at the element type to ensure that the warning behaviour is
1789 // consistent for both scalars and arrays.
1790 Ty = Ty->getBaseElementTypeUnsafe();
1791
1792 if (const TagType *TT = Ty->getAs<TagType>()) {
1793 const TagDecl *Tag = TT->getDecl();
1794 if (Tag->hasAttr<UnusedAttr>())
1795 return false;
1796
1797 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1798 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1799 return false;
1800
1801 if (const Expr *Init = VD->getInit()) {
1802 if (const ExprWithCleanups *Cleanups =
1803 dyn_cast<ExprWithCleanups>(Init))
1804 Init = Cleanups->getSubExpr();
1805 const CXXConstructExpr *Construct =
1806 dyn_cast<CXXConstructExpr>(Init);
1807 if (Construct && !Construct->isElidable()) {
1808 CXXConstructorDecl *CD = Construct->getConstructor();
1809 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1810 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1811 return false;
1812 }
1813
1814 // Suppress the warning if we don't know how this is constructed, and
1815 // it could possibly be non-trivial constructor.
1816 if (Init->isTypeDependent())
1817 for (const CXXConstructorDecl *Ctor : RD->ctors())
1818 if (!Ctor->isTrivial())
1819 return false;
1820 }
1821 }
1822 }
1823
1824 // TODO: __attribute__((unused)) templates?
1825 }
1826
1827 return true;
1828 }
1829
GenerateFixForUnusedDecl(const NamedDecl * D,ASTContext & Ctx,FixItHint & Hint)1830 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1831 FixItHint &Hint) {
1832 if (isa<LabelDecl>(D)) {
1833 SourceLocation AfterColon = Lexer::findLocationAfterToken(
1834 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1835 true);
1836 if (AfterColon.isInvalid())
1837 return;
1838 Hint = FixItHint::CreateRemoval(
1839 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1840 }
1841 }
1842
DiagnoseUnusedNestedTypedefs(const RecordDecl * D)1843 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1844 if (D->getTypeForDecl()->isDependentType())
1845 return;
1846
1847 for (auto *TmpD : D->decls()) {
1848 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1849 DiagnoseUnusedDecl(T);
1850 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1851 DiagnoseUnusedNestedTypedefs(R);
1852 }
1853 }
1854
1855 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1856 /// unless they are marked attr(unused).
DiagnoseUnusedDecl(const NamedDecl * D)1857 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1858 if (!ShouldDiagnoseUnusedDecl(D))
1859 return;
1860
1861 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1862 // typedefs can be referenced later on, so the diagnostics are emitted
1863 // at end-of-translation-unit.
1864 UnusedLocalTypedefNameCandidates.insert(TD);
1865 return;
1866 }
1867
1868 FixItHint Hint;
1869 GenerateFixForUnusedDecl(D, Context, Hint);
1870
1871 unsigned DiagID;
1872 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1873 DiagID = diag::warn_unused_exception_param;
1874 else if (isa<LabelDecl>(D))
1875 DiagID = diag::warn_unused_label;
1876 else
1877 DiagID = diag::warn_unused_variable;
1878
1879 Diag(D->getLocation(), DiagID) << D << Hint;
1880 }
1881
CheckPoppedLabel(LabelDecl * L,Sema & S)1882 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1883 // Verify that we have no forward references left. If so, there was a goto
1884 // or address of a label taken, but no definition of it. Label fwd
1885 // definitions are indicated with a null substmt which is also not a resolved
1886 // MS inline assembly label name.
1887 bool Diagnose = false;
1888 if (L->isMSAsmLabel())
1889 Diagnose = !L->isResolvedMSAsmLabel();
1890 else
1891 Diagnose = L->getStmt() == nullptr;
1892 if (Diagnose)
1893 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1894 }
1895
ActOnPopScope(SourceLocation Loc,Scope * S)1896 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1897 S->mergeNRVOIntoParent();
1898
1899 if (S->decl_empty()) return;
1900 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1901 "Scope shouldn't contain decls!");
1902
1903 for (auto *TmpD : S->decls()) {
1904 assert(TmpD && "This decl didn't get pushed??");
1905
1906 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1907 NamedDecl *D = cast<NamedDecl>(TmpD);
1908
1909 // Diagnose unused variables in this scope.
1910 if (!S->hasUnrecoverableErrorOccurred()) {
1911 DiagnoseUnusedDecl(D);
1912 if (const auto *RD = dyn_cast<RecordDecl>(D))
1913 DiagnoseUnusedNestedTypedefs(RD);
1914 }
1915
1916 if (!D->getDeclName()) continue;
1917
1918 // If this was a forward reference to a label, verify it was defined.
1919 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1920 CheckPoppedLabel(LD, *this);
1921
1922 // Remove this name from our lexical scope, and warn on it if we haven't
1923 // already.
1924 IdResolver.RemoveDecl(D);
1925 auto ShadowI = ShadowingDecls.find(D);
1926 if (ShadowI != ShadowingDecls.end()) {
1927 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1928 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1929 << D << FD << FD->getParent();
1930 Diag(FD->getLocation(), diag::note_previous_declaration);
1931 }
1932 ShadowingDecls.erase(ShadowI);
1933 }
1934 }
1935 }
1936
1937 /// Look for an Objective-C class in the translation unit.
1938 ///
1939 /// \param Id The name of the Objective-C class we're looking for. If
1940 /// typo-correction fixes this name, the Id will be updated
1941 /// to the fixed name.
1942 ///
1943 /// \param IdLoc The location of the name in the translation unit.
1944 ///
1945 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1946 /// if there is no class with the given name.
1947 ///
1948 /// \returns The declaration of the named Objective-C class, or NULL if the
1949 /// class could not be found.
getObjCInterfaceDecl(IdentifierInfo * & Id,SourceLocation IdLoc,bool DoTypoCorrection)1950 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1951 SourceLocation IdLoc,
1952 bool DoTypoCorrection) {
1953 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1954 // creation from this context.
1955 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1956
1957 if (!IDecl && DoTypoCorrection) {
1958 // Perform typo correction at the given location, but only if we
1959 // find an Objective-C class name.
1960 DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1961 if (TypoCorrection C =
1962 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1963 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1964 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1965 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1966 Id = IDecl->getIdentifier();
1967 }
1968 }
1969 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1970 // This routine must always return a class definition, if any.
1971 if (Def && Def->getDefinition())
1972 Def = Def->getDefinition();
1973 return Def;
1974 }
1975
1976 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1977 /// from S, where a non-field would be declared. This routine copes
1978 /// with the difference between C and C++ scoping rules in structs and
1979 /// unions. For example, the following code is well-formed in C but
1980 /// ill-formed in C++:
1981 /// @code
1982 /// struct S6 {
1983 /// enum { BAR } e;
1984 /// };
1985 ///
1986 /// void test_S6() {
1987 /// struct S6 a;
1988 /// a.e = BAR;
1989 /// }
1990 /// @endcode
1991 /// For the declaration of BAR, this routine will return a different
1992 /// scope. The scope S will be the scope of the unnamed enumeration
1993 /// within S6. In C++, this routine will return the scope associated
1994 /// with S6, because the enumeration's scope is a transparent
1995 /// context but structures can contain non-field names. In C, this
1996 /// routine will return the translation unit scope, since the
1997 /// enumeration's scope is a transparent context and structures cannot
1998 /// contain non-field names.
getNonFieldDeclScope(Scope * S)1999 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2000 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2001 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2002 (S->isClassScope() && !getLangOpts().CPlusPlus))
2003 S = S->getParent();
2004 return S;
2005 }
2006
2007 /// Looks up the declaration of "struct objc_super" and
2008 /// saves it for later use in building builtin declaration of
2009 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
2010 /// pre-existing declaration exists no action takes place.
LookupPredefedObjCSuperType(Sema & ThisSema,Scope * S,IdentifierInfo * II)2011 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
2012 IdentifierInfo *II) {
2013 if (!II->isStr("objc_msgSendSuper"))
2014 return;
2015 ASTContext &Context = ThisSema.Context;
2016
2017 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
2018 SourceLocation(), Sema::LookupTagName);
2019 ThisSema.LookupName(Result, S);
2020 if (Result.getResultKind() == LookupResult::Found)
2021 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
2022 Context.setObjCSuperType(Context.getTagDeclType(TD));
2023 }
2024
getHeaderName(Builtin::Context & BuiltinInfo,unsigned ID,ASTContext::GetBuiltinTypeError Error)2025 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2026 ASTContext::GetBuiltinTypeError Error) {
2027 switch (Error) {
2028 case ASTContext::GE_None:
2029 return "";
2030 case ASTContext::GE_Missing_type:
2031 return BuiltinInfo.getHeaderName(ID);
2032 case ASTContext::GE_Missing_stdio:
2033 return "stdio.h";
2034 case ASTContext::GE_Missing_setjmp:
2035 return "setjmp.h";
2036 case ASTContext::GE_Missing_ucontext:
2037 return "ucontext.h";
2038 }
2039 llvm_unreachable("unhandled error kind");
2040 }
2041
2042 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2043 /// file scope. lazily create a decl for it. ForRedeclaration is true
2044 /// if we're creating this built-in in anticipation of redeclaring the
2045 /// built-in.
LazilyCreateBuiltin(IdentifierInfo * II,unsigned ID,Scope * S,bool ForRedeclaration,SourceLocation Loc)2046 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2047 Scope *S, bool ForRedeclaration,
2048 SourceLocation Loc) {
2049 LookupPredefedObjCSuperType(*this, S, II);
2050
2051 ASTContext::GetBuiltinTypeError Error;
2052 QualType R = Context.GetBuiltinType(ID, Error);
2053 if (Error) {
2054 if (!ForRedeclaration)
2055 return nullptr;
2056
2057 // If we have a builtin without an associated type we should not emit a
2058 // warning when we were not able to find a type for it.
2059 if (Error == ASTContext::GE_Missing_type)
2060 return nullptr;
2061
2062 // If we could not find a type for setjmp it is because the jmp_buf type was
2063 // not defined prior to the setjmp declaration.
2064 if (Error == ASTContext::GE_Missing_setjmp) {
2065 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2066 << Context.BuiltinInfo.getName(ID);
2067 return nullptr;
2068 }
2069
2070 // Generally, we emit a warning that the declaration requires the
2071 // appropriate header.
2072 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2073 << getHeaderName(Context.BuiltinInfo, ID, Error)
2074 << Context.BuiltinInfo.getName(ID);
2075 return nullptr;
2076 }
2077
2078 if (!ForRedeclaration &&
2079 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2080 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2081 Diag(Loc, diag::ext_implicit_lib_function_decl)
2082 << Context.BuiltinInfo.getName(ID) << R;
2083 if (Context.BuiltinInfo.getHeaderName(ID) &&
2084 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2085 Diag(Loc, diag::note_include_header_or_declare)
2086 << Context.BuiltinInfo.getHeaderName(ID)
2087 << Context.BuiltinInfo.getName(ID);
2088 }
2089
2090 if (R.isNull())
2091 return nullptr;
2092
2093 DeclContext *Parent = Context.getTranslationUnitDecl();
2094 if (getLangOpts().CPlusPlus) {
2095 LinkageSpecDecl *CLinkageDecl =
2096 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
2097 LinkageSpecDecl::lang_c, false);
2098 CLinkageDecl->setImplicit();
2099 Parent->addDecl(CLinkageDecl);
2100 Parent = CLinkageDecl;
2101 }
2102
2103 FunctionDecl *New = FunctionDecl::Create(Context,
2104 Parent,
2105 Loc, Loc, II, R, /*TInfo=*/nullptr,
2106 SC_Extern,
2107 false,
2108 R->isFunctionProtoType());
2109 New->setImplicit();
2110
2111 // Create Decl objects for each parameter, adding them to the
2112 // FunctionDecl.
2113 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2114 SmallVector<ParmVarDecl*, 16> Params;
2115 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2116 ParmVarDecl *parm =
2117 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2118 nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2119 SC_None, nullptr);
2120 parm->setScopeInfo(0, i);
2121 Params.push_back(parm);
2122 }
2123 New->setParams(Params);
2124 }
2125
2126 AddKnownFunctionAttributes(New);
2127 RegisterLocallyScopedExternCDecl(New, S);
2128
2129 // TUScope is the translation-unit scope to insert this function into.
2130 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2131 // relate Scopes to DeclContexts, and probably eliminate CurContext
2132 // entirely, but we're not there yet.
2133 DeclContext *SavedContext = CurContext;
2134 CurContext = Parent;
2135 PushOnScopeChains(New, TUScope);
2136 CurContext = SavedContext;
2137 return New;
2138 }
2139
2140 /// Typedef declarations don't have linkage, but they still denote the same
2141 /// entity if their types are the same.
2142 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2143 /// isSameEntity.
filterNonConflictingPreviousTypedefDecls(Sema & S,TypedefNameDecl * Decl,LookupResult & Previous)2144 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2145 TypedefNameDecl *Decl,
2146 LookupResult &Previous) {
2147 // This is only interesting when modules are enabled.
2148 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2149 return;
2150
2151 // Empty sets are uninteresting.
2152 if (Previous.empty())
2153 return;
2154
2155 LookupResult::Filter Filter = Previous.makeFilter();
2156 while (Filter.hasNext()) {
2157 NamedDecl *Old = Filter.next();
2158
2159 // Non-hidden declarations are never ignored.
2160 if (S.isVisible(Old))
2161 continue;
2162
2163 // Declarations of the same entity are not ignored, even if they have
2164 // different linkages.
2165 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2166 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2167 Decl->getUnderlyingType()))
2168 continue;
2169
2170 // If both declarations give a tag declaration a typedef name for linkage
2171 // purposes, then they declare the same entity.
2172 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2173 Decl->getAnonDeclWithTypedefName())
2174 continue;
2175 }
2176
2177 Filter.erase();
2178 }
2179
2180 Filter.done();
2181 }
2182
isIncompatibleTypedef(TypeDecl * Old,TypedefNameDecl * New)2183 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2184 QualType OldType;
2185 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2186 OldType = OldTypedef->getUnderlyingType();
2187 else
2188 OldType = Context.getTypeDeclType(Old);
2189 QualType NewType = New->getUnderlyingType();
2190
2191 if (NewType->isVariablyModifiedType()) {
2192 // Must not redefine a typedef with a variably-modified type.
2193 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2194 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2195 << Kind << NewType;
2196 if (Old->getLocation().isValid())
2197 notePreviousDefinition(Old, New->getLocation());
2198 New->setInvalidDecl();
2199 return true;
2200 }
2201
2202 if (OldType != NewType &&
2203 !OldType->isDependentType() &&
2204 !NewType->isDependentType() &&
2205 !Context.hasSameType(OldType, NewType)) {
2206 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2207 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2208 << Kind << NewType << OldType;
2209 if (Old->getLocation().isValid())
2210 notePreviousDefinition(Old, New->getLocation());
2211 New->setInvalidDecl();
2212 return true;
2213 }
2214 return false;
2215 }
2216
2217 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2218 /// same name and scope as a previous declaration 'Old'. Figure out
2219 /// how to resolve this situation, merging decls or emitting
2220 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2221 ///
MergeTypedefNameDecl(Scope * S,TypedefNameDecl * New,LookupResult & OldDecls)2222 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2223 LookupResult &OldDecls) {
2224 // If the new decl is known invalid already, don't bother doing any
2225 // merging checks.
2226 if (New->isInvalidDecl()) return;
2227
2228 // Allow multiple definitions for ObjC built-in typedefs.
2229 // FIXME: Verify the underlying types are equivalent!
2230 if (getLangOpts().ObjC) {
2231 const IdentifierInfo *TypeID = New->getIdentifier();
2232 switch (TypeID->getLength()) {
2233 default: break;
2234 case 2:
2235 {
2236 if (!TypeID->isStr("id"))
2237 break;
2238 QualType T = New->getUnderlyingType();
2239 if (!T->isPointerType())
2240 break;
2241 if (!T->isVoidPointerType()) {
2242 QualType PT = T->castAs<PointerType>()->getPointeeType();
2243 if (!PT->isStructureType())
2244 break;
2245 }
2246 Context.setObjCIdRedefinitionType(T);
2247 // Install the built-in type for 'id', ignoring the current definition.
2248 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2249 return;
2250 }
2251 case 5:
2252 if (!TypeID->isStr("Class"))
2253 break;
2254 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2255 // Install the built-in type for 'Class', ignoring the current definition.
2256 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2257 return;
2258 case 3:
2259 if (!TypeID->isStr("SEL"))
2260 break;
2261 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2262 // Install the built-in type for 'SEL', ignoring the current definition.
2263 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2264 return;
2265 }
2266 // Fall through - the typedef name was not a builtin type.
2267 }
2268
2269 // Verify the old decl was also a type.
2270 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2271 if (!Old) {
2272 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2273 << New->getDeclName();
2274
2275 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2276 if (OldD->getLocation().isValid())
2277 notePreviousDefinition(OldD, New->getLocation());
2278
2279 return New->setInvalidDecl();
2280 }
2281
2282 // If the old declaration is invalid, just give up here.
2283 if (Old->isInvalidDecl())
2284 return New->setInvalidDecl();
2285
2286 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2287 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2288 auto *NewTag = New->getAnonDeclWithTypedefName();
2289 NamedDecl *Hidden = nullptr;
2290 if (OldTag && NewTag &&
2291 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2292 !hasVisibleDefinition(OldTag, &Hidden)) {
2293 // There is a definition of this tag, but it is not visible. Use it
2294 // instead of our tag.
2295 New->setTypeForDecl(OldTD->getTypeForDecl());
2296 if (OldTD->isModed())
2297 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2298 OldTD->getUnderlyingType());
2299 else
2300 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2301
2302 // Make the old tag definition visible.
2303 makeMergedDefinitionVisible(Hidden);
2304
2305 // If this was an unscoped enumeration, yank all of its enumerators
2306 // out of the scope.
2307 if (isa<EnumDecl>(NewTag)) {
2308 Scope *EnumScope = getNonFieldDeclScope(S);
2309 for (auto *D : NewTag->decls()) {
2310 auto *ED = cast<EnumConstantDecl>(D);
2311 assert(EnumScope->isDeclScope(ED));
2312 EnumScope->RemoveDecl(ED);
2313 IdResolver.RemoveDecl(ED);
2314 ED->getLexicalDeclContext()->removeDecl(ED);
2315 }
2316 }
2317 }
2318 }
2319
2320 // If the typedef types are not identical, reject them in all languages and
2321 // with any extensions enabled.
2322 if (isIncompatibleTypedef(Old, New))
2323 return;
2324
2325 // The types match. Link up the redeclaration chain and merge attributes if
2326 // the old declaration was a typedef.
2327 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2328 New->setPreviousDecl(Typedef);
2329 mergeDeclAttributes(New, Old);
2330 }
2331
2332 if (getLangOpts().MicrosoftExt)
2333 return;
2334
2335 if (getLangOpts().CPlusPlus) {
2336 // C++ [dcl.typedef]p2:
2337 // In a given non-class scope, a typedef specifier can be used to
2338 // redefine the name of any type declared in that scope to refer
2339 // to the type to which it already refers.
2340 if (!isa<CXXRecordDecl>(CurContext))
2341 return;
2342
2343 // C++0x [dcl.typedef]p4:
2344 // In a given class scope, a typedef specifier can be used to redefine
2345 // any class-name declared in that scope that is not also a typedef-name
2346 // to refer to the type to which it already refers.
2347 //
2348 // This wording came in via DR424, which was a correction to the
2349 // wording in DR56, which accidentally banned code like:
2350 //
2351 // struct S {
2352 // typedef struct A { } A;
2353 // };
2354 //
2355 // in the C++03 standard. We implement the C++0x semantics, which
2356 // allow the above but disallow
2357 //
2358 // struct S {
2359 // typedef int I;
2360 // typedef int I;
2361 // };
2362 //
2363 // since that was the intent of DR56.
2364 if (!isa<TypedefNameDecl>(Old))
2365 return;
2366
2367 Diag(New->getLocation(), diag::err_redefinition)
2368 << New->getDeclName();
2369 notePreviousDefinition(Old, New->getLocation());
2370 return New->setInvalidDecl();
2371 }
2372
2373 // Modules always permit redefinition of typedefs, as does C11.
2374 if (getLangOpts().Modules || getLangOpts().C11)
2375 return;
2376
2377 // If we have a redefinition of a typedef in C, emit a warning. This warning
2378 // is normally mapped to an error, but can be controlled with
2379 // -Wtypedef-redefinition. If either the original or the redefinition is
2380 // in a system header, don't emit this for compatibility with GCC.
2381 if (getDiagnostics().getSuppressSystemWarnings() &&
2382 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2383 (Old->isImplicit() ||
2384 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2385 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2386 return;
2387
2388 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2389 << New->getDeclName();
2390 notePreviousDefinition(Old, New->getLocation());
2391 }
2392
2393 /// DeclhasAttr - returns true if decl Declaration already has the target
2394 /// attribute.
DeclHasAttr(const Decl * D,const Attr * A)2395 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2396 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2397 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2398 for (const auto *i : D->attrs())
2399 if (i->getKind() == A->getKind()) {
2400 if (Ann) {
2401 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2402 return true;
2403 continue;
2404 }
2405 // FIXME: Don't hardcode this check
2406 if (OA && isa<OwnershipAttr>(i))
2407 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2408 return true;
2409 }
2410
2411 return false;
2412 }
2413
isAttributeTargetADefinition(Decl * D)2414 static bool isAttributeTargetADefinition(Decl *D) {
2415 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2416 return VD->isThisDeclarationADefinition();
2417 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2418 return TD->isCompleteDefinition() || TD->isBeingDefined();
2419 return true;
2420 }
2421
2422 /// Merge alignment attributes from \p Old to \p New, taking into account the
2423 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2424 ///
2425 /// \return \c true if any attributes were added to \p New.
mergeAlignedAttrs(Sema & S,NamedDecl * New,Decl * Old)2426 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2427 // Look for alignas attributes on Old, and pick out whichever attribute
2428 // specifies the strictest alignment requirement.
2429 AlignedAttr *OldAlignasAttr = nullptr;
2430 AlignedAttr *OldStrictestAlignAttr = nullptr;
2431 unsigned OldAlign = 0;
2432 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2433 // FIXME: We have no way of representing inherited dependent alignments
2434 // in a case like:
2435 // template<int A, int B> struct alignas(A) X;
2436 // template<int A, int B> struct alignas(B) X {};
2437 // For now, we just ignore any alignas attributes which are not on the
2438 // definition in such a case.
2439 if (I->isAlignmentDependent())
2440 return false;
2441
2442 if (I->isAlignas())
2443 OldAlignasAttr = I;
2444
2445 unsigned Align = I->getAlignment(S.Context);
2446 if (Align > OldAlign) {
2447 OldAlign = Align;
2448 OldStrictestAlignAttr = I;
2449 }
2450 }
2451
2452 // Look for alignas attributes on New.
2453 AlignedAttr *NewAlignasAttr = nullptr;
2454 unsigned NewAlign = 0;
2455 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2456 if (I->isAlignmentDependent())
2457 return false;
2458
2459 if (I->isAlignas())
2460 NewAlignasAttr = I;
2461
2462 unsigned Align = I->getAlignment(S.Context);
2463 if (Align > NewAlign)
2464 NewAlign = Align;
2465 }
2466
2467 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2468 // Both declarations have 'alignas' attributes. We require them to match.
2469 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2470 // fall short. (If two declarations both have alignas, they must both match
2471 // every definition, and so must match each other if there is a definition.)
2472
2473 // If either declaration only contains 'alignas(0)' specifiers, then it
2474 // specifies the natural alignment for the type.
2475 if (OldAlign == 0 || NewAlign == 0) {
2476 QualType Ty;
2477 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2478 Ty = VD->getType();
2479 else
2480 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2481
2482 if (OldAlign == 0)
2483 OldAlign = S.Context.getTypeAlign(Ty);
2484 if (NewAlign == 0)
2485 NewAlign = S.Context.getTypeAlign(Ty);
2486 }
2487
2488 if (OldAlign != NewAlign) {
2489 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2490 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2491 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2492 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2493 }
2494 }
2495
2496 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2497 // C++11 [dcl.align]p6:
2498 // if any declaration of an entity has an alignment-specifier,
2499 // every defining declaration of that entity shall specify an
2500 // equivalent alignment.
2501 // C11 6.7.5/7:
2502 // If the definition of an object does not have an alignment
2503 // specifier, any other declaration of that object shall also
2504 // have no alignment specifier.
2505 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2506 << OldAlignasAttr;
2507 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2508 << OldAlignasAttr;
2509 }
2510
2511 bool AnyAdded = false;
2512
2513 // Ensure we have an attribute representing the strictest alignment.
2514 if (OldAlign > NewAlign) {
2515 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2516 Clone->setInherited(true);
2517 New->addAttr(Clone);
2518 AnyAdded = true;
2519 }
2520
2521 // Ensure we have an alignas attribute if the old declaration had one.
2522 if (OldAlignasAttr && !NewAlignasAttr &&
2523 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2524 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2525 Clone->setInherited(true);
2526 New->addAttr(Clone);
2527 AnyAdded = true;
2528 }
2529
2530 return AnyAdded;
2531 }
2532
mergeDeclAttribute(Sema & S,NamedDecl * D,const InheritableAttr * Attr,Sema::AvailabilityMergeKind AMK)2533 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2534 const InheritableAttr *Attr,
2535 Sema::AvailabilityMergeKind AMK) {
2536 // This function copies an attribute Attr from a previous declaration to the
2537 // new declaration D if the new declaration doesn't itself have that attribute
2538 // yet or if that attribute allows duplicates.
2539 // If you're adding a new attribute that requires logic different from
2540 // "use explicit attribute on decl if present, else use attribute from
2541 // previous decl", for example if the attribute needs to be consistent
2542 // between redeclarations, you need to call a custom merge function here.
2543 InheritableAttr *NewAttr = nullptr;
2544 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2545 NewAttr = S.mergeAvailabilityAttr(
2546 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2547 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2548 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2549 AA->getPriority());
2550 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2551 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2552 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2553 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2554 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2555 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2556 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2557 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2558 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2559 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2560 FA->getFirstArg());
2561 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2562 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2563 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2564 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2565 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2566 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2567 IA->getInheritanceModel());
2568 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2569 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2570 &S.Context.Idents.get(AA->getSpelling()));
2571 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2572 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2573 isa<CUDAGlobalAttr>(Attr))) {
2574 // CUDA target attributes are part of function signature for
2575 // overloading purposes and must not be merged.
2576 return false;
2577 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2578 NewAttr = S.mergeMinSizeAttr(D, *MA);
2579 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2580 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2581 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2582 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2583 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2584 NewAttr = S.mergeCommonAttr(D, *CommonA);
2585 else if (isa<AlignedAttr>(Attr))
2586 // AlignedAttrs are handled separately, because we need to handle all
2587 // such attributes on a declaration at the same time.
2588 NewAttr = nullptr;
2589 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2590 (AMK == Sema::AMK_Override ||
2591 AMK == Sema::AMK_ProtocolImplementation))
2592 NewAttr = nullptr;
2593 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2594 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid());
2595 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2596 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2597 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2598 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2599 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2600 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2601
2602 if (NewAttr) {
2603 NewAttr->setInherited(true);
2604 D->addAttr(NewAttr);
2605 if (isa<MSInheritanceAttr>(NewAttr))
2606 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2607 return true;
2608 }
2609
2610 return false;
2611 }
2612
getDefinition(const Decl * D)2613 static const NamedDecl *getDefinition(const Decl *D) {
2614 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2615 return TD->getDefinition();
2616 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2617 const VarDecl *Def = VD->getDefinition();
2618 if (Def)
2619 return Def;
2620 return VD->getActingDefinition();
2621 }
2622 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2623 return FD->getDefinition();
2624 return nullptr;
2625 }
2626
hasAttribute(const Decl * D,attr::Kind Kind)2627 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2628 for (const auto *Attribute : D->attrs())
2629 if (Attribute->getKind() == Kind)
2630 return true;
2631 return false;
2632 }
2633
2634 /// checkNewAttributesAfterDef - If we already have a definition, check that
2635 /// there are no new attributes in this declaration.
checkNewAttributesAfterDef(Sema & S,Decl * New,const Decl * Old)2636 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2637 if (!New->hasAttrs())
2638 return;
2639
2640 const NamedDecl *Def = getDefinition(Old);
2641 if (!Def || Def == New)
2642 return;
2643
2644 AttrVec &NewAttributes = New->getAttrs();
2645 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2646 const Attr *NewAttribute = NewAttributes[I];
2647
2648 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2649 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2650 Sema::SkipBodyInfo SkipBody;
2651 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2652
2653 // If we're skipping this definition, drop the "alias" attribute.
2654 if (SkipBody.ShouldSkip) {
2655 NewAttributes.erase(NewAttributes.begin() + I);
2656 --E;
2657 continue;
2658 }
2659 } else {
2660 VarDecl *VD = cast<VarDecl>(New);
2661 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2662 VarDecl::TentativeDefinition
2663 ? diag::err_alias_after_tentative
2664 : diag::err_redefinition;
2665 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2666 if (Diag == diag::err_redefinition)
2667 S.notePreviousDefinition(Def, VD->getLocation());
2668 else
2669 S.Diag(Def->getLocation(), diag::note_previous_definition);
2670 VD->setInvalidDecl();
2671 }
2672 ++I;
2673 continue;
2674 }
2675
2676 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2677 // Tentative definitions are only interesting for the alias check above.
2678 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2679 ++I;
2680 continue;
2681 }
2682 }
2683
2684 if (hasAttribute(Def, NewAttribute->getKind())) {
2685 ++I;
2686 continue; // regular attr merging will take care of validating this.
2687 }
2688
2689 if (isa<C11NoReturnAttr>(NewAttribute)) {
2690 // C's _Noreturn is allowed to be added to a function after it is defined.
2691 ++I;
2692 continue;
2693 } else if (isa<UuidAttr>(NewAttribute)) {
2694 // msvc will allow a subsequent definition to add an uuid to a class
2695 ++I;
2696 continue;
2697 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2698 if (AA->isAlignas()) {
2699 // C++11 [dcl.align]p6:
2700 // if any declaration of an entity has an alignment-specifier,
2701 // every defining declaration of that entity shall specify an
2702 // equivalent alignment.
2703 // C11 6.7.5/7:
2704 // If the definition of an object does not have an alignment
2705 // specifier, any other declaration of that object shall also
2706 // have no alignment specifier.
2707 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2708 << AA;
2709 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2710 << AA;
2711 NewAttributes.erase(NewAttributes.begin() + I);
2712 --E;
2713 continue;
2714 }
2715 } else if (isa<SelectAnyAttr>(NewAttribute) &&
2716 cast<VarDecl>(New)->isInline() &&
2717 !cast<VarDecl>(New)->isInlineSpecified()) {
2718 // Don't warn about applying selectany to implicitly inline variables.
2719 // Older compilers and language modes would require the use of selectany
2720 // to make such variables inline, and it would have no effect if we
2721 // honored it.
2722 ++I;
2723 continue;
2724 }
2725
2726 S.Diag(NewAttribute->getLocation(),
2727 diag::warn_attribute_precede_definition);
2728 S.Diag(Def->getLocation(), diag::note_previous_definition);
2729 NewAttributes.erase(NewAttributes.begin() + I);
2730 --E;
2731 }
2732 }
2733
diagnoseMissingConstinit(Sema & S,const VarDecl * InitDecl,const ConstInitAttr * CIAttr,bool AttrBeforeInit)2734 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2735 const ConstInitAttr *CIAttr,
2736 bool AttrBeforeInit) {
2737 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2738
2739 // Figure out a good way to write this specifier on the old declaration.
2740 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2741 // enough of the attribute list spelling information to extract that without
2742 // heroics.
2743 std::string SuitableSpelling;
2744 if (S.getLangOpts().CPlusPlus2a)
2745 SuitableSpelling =
2746 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit});
2747 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2748 SuitableSpelling = S.PP.getLastMacroWithSpelling(
2749 InsertLoc,
2750 {tok::l_square, tok::l_square, S.PP.getIdentifierInfo("clang"),
2751 tok::coloncolon,
2752 S.PP.getIdentifierInfo("require_constant_initialization"),
2753 tok::r_square, tok::r_square});
2754 if (SuitableSpelling.empty())
2755 SuitableSpelling = S.PP.getLastMacroWithSpelling(
2756 InsertLoc,
2757 {tok::kw___attribute, tok::l_paren, tok::r_paren,
2758 S.PP.getIdentifierInfo("require_constant_initialization"),
2759 tok::r_paren, tok::r_paren});
2760 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a)
2761 SuitableSpelling = "constinit";
2762 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2763 SuitableSpelling = "[[clang::require_constant_initialization]]";
2764 if (SuitableSpelling.empty())
2765 SuitableSpelling = "__attribute__((require_constant_initialization))";
2766 SuitableSpelling += " ";
2767
2768 if (AttrBeforeInit) {
2769 // extern constinit int a;
2770 // int a = 0; // error (missing 'constinit'), accepted as extension
2771 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2772 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2773 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2774 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2775 } else {
2776 // int a = 0;
2777 // constinit extern int a; // error (missing 'constinit')
2778 S.Diag(CIAttr->getLocation(),
2779 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2780 : diag::warn_require_const_init_added_too_late)
2781 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2782 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2783 << CIAttr->isConstinit()
2784 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2785 }
2786 }
2787
2788 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
mergeDeclAttributes(NamedDecl * New,Decl * Old,AvailabilityMergeKind AMK)2789 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2790 AvailabilityMergeKind AMK) {
2791 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2792 UsedAttr *NewAttr = OldAttr->clone(Context);
2793 NewAttr->setInherited(true);
2794 New->addAttr(NewAttr);
2795 }
2796
2797 if (!Old->hasAttrs() && !New->hasAttrs())
2798 return;
2799
2800 // [dcl.constinit]p1:
2801 // If the [constinit] specifier is applied to any declaration of a
2802 // variable, it shall be applied to the initializing declaration.
2803 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2804 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2805 if (bool(OldConstInit) != bool(NewConstInit)) {
2806 const auto *OldVD = cast<VarDecl>(Old);
2807 auto *NewVD = cast<VarDecl>(New);
2808
2809 // Find the initializing declaration. Note that we might not have linked
2810 // the new declaration into the redeclaration chain yet.
2811 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2812 if (!InitDecl &&
2813 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2814 InitDecl = NewVD;
2815
2816 if (InitDecl == NewVD) {
2817 // This is the initializing declaration. If it would inherit 'constinit',
2818 // that's ill-formed. (Note that we do not apply this to the attribute
2819 // form).
2820 if (OldConstInit && OldConstInit->isConstinit())
2821 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2822 /*AttrBeforeInit=*/true);
2823 } else if (NewConstInit) {
2824 // This is the first time we've been told that this declaration should
2825 // have a constant initializer. If we already saw the initializing
2826 // declaration, this is too late.
2827 if (InitDecl && InitDecl != NewVD) {
2828 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2829 /*AttrBeforeInit=*/false);
2830 NewVD->dropAttr<ConstInitAttr>();
2831 }
2832 }
2833 }
2834
2835 // Attributes declared post-definition are currently ignored.
2836 checkNewAttributesAfterDef(*this, New, Old);
2837
2838 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2839 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2840 if (!OldA->isEquivalent(NewA)) {
2841 // This redeclaration changes __asm__ label.
2842 Diag(New->getLocation(), diag::err_different_asm_label);
2843 Diag(OldA->getLocation(), diag::note_previous_declaration);
2844 }
2845 } else if (Old->isUsed()) {
2846 // This redeclaration adds an __asm__ label to a declaration that has
2847 // already been ODR-used.
2848 Diag(New->getLocation(), diag::err_late_asm_label_name)
2849 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2850 }
2851 }
2852
2853 // Re-declaration cannot add abi_tag's.
2854 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2855 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2856 for (const auto &NewTag : NewAbiTagAttr->tags()) {
2857 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2858 NewTag) == OldAbiTagAttr->tags_end()) {
2859 Diag(NewAbiTagAttr->getLocation(),
2860 diag::err_new_abi_tag_on_redeclaration)
2861 << NewTag;
2862 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2863 }
2864 }
2865 } else {
2866 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2867 Diag(Old->getLocation(), diag::note_previous_declaration);
2868 }
2869 }
2870
2871 // This redeclaration adds a section attribute.
2872 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2873 if (auto *VD = dyn_cast<VarDecl>(New)) {
2874 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2875 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2876 Diag(Old->getLocation(), diag::note_previous_declaration);
2877 }
2878 }
2879 }
2880
2881 // Redeclaration adds code-seg attribute.
2882 const auto *NewCSA = New->getAttr<CodeSegAttr>();
2883 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2884 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2885 Diag(New->getLocation(), diag::warn_mismatched_section)
2886 << 0 /*codeseg*/;
2887 Diag(Old->getLocation(), diag::note_previous_declaration);
2888 }
2889
2890 if (!Old->hasAttrs())
2891 return;
2892
2893 bool foundAny = New->hasAttrs();
2894
2895 // Ensure that any moving of objects within the allocated map is done before
2896 // we process them.
2897 if (!foundAny) New->setAttrs(AttrVec());
2898
2899 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2900 // Ignore deprecated/unavailable/availability attributes if requested.
2901 AvailabilityMergeKind LocalAMK = AMK_None;
2902 if (isa<DeprecatedAttr>(I) ||
2903 isa<UnavailableAttr>(I) ||
2904 isa<AvailabilityAttr>(I)) {
2905 switch (AMK) {
2906 case AMK_None:
2907 continue;
2908
2909 case AMK_Redeclaration:
2910 case AMK_Override:
2911 case AMK_ProtocolImplementation:
2912 LocalAMK = AMK;
2913 break;
2914 }
2915 }
2916
2917 // Already handled.
2918 if (isa<UsedAttr>(I))
2919 continue;
2920
2921 if (mergeDeclAttribute(*this, New, I, LocalAMK))
2922 foundAny = true;
2923 }
2924
2925 if (mergeAlignedAttrs(*this, New, Old))
2926 foundAny = true;
2927
2928 if (!foundAny) New->dropAttrs();
2929 }
2930
2931 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2932 /// to the new one.
mergeParamDeclAttributes(ParmVarDecl * newDecl,const ParmVarDecl * oldDecl,Sema & S)2933 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2934 const ParmVarDecl *oldDecl,
2935 Sema &S) {
2936 // C++11 [dcl.attr.depend]p2:
2937 // The first declaration of a function shall specify the
2938 // carries_dependency attribute for its declarator-id if any declaration
2939 // of the function specifies the carries_dependency attribute.
2940 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2941 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2942 S.Diag(CDA->getLocation(),
2943 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2944 // Find the first declaration of the parameter.
2945 // FIXME: Should we build redeclaration chains for function parameters?
2946 const FunctionDecl *FirstFD =
2947 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2948 const ParmVarDecl *FirstVD =
2949 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2950 S.Diag(FirstVD->getLocation(),
2951 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2952 }
2953
2954 if (!oldDecl->hasAttrs())
2955 return;
2956
2957 bool foundAny = newDecl->hasAttrs();
2958
2959 // Ensure that any moving of objects within the allocated map is
2960 // done before we process them.
2961 if (!foundAny) newDecl->setAttrs(AttrVec());
2962
2963 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2964 if (!DeclHasAttr(newDecl, I)) {
2965 InheritableAttr *newAttr =
2966 cast<InheritableParamAttr>(I->clone(S.Context));
2967 newAttr->setInherited(true);
2968 newDecl->addAttr(newAttr);
2969 foundAny = true;
2970 }
2971 }
2972
2973 if (!foundAny) newDecl->dropAttrs();
2974 }
2975
mergeParamDeclTypes(ParmVarDecl * NewParam,const ParmVarDecl * OldParam,Sema & S)2976 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2977 const ParmVarDecl *OldParam,
2978 Sema &S) {
2979 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2980 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2981 if (*Oldnullability != *Newnullability) {
2982 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2983 << DiagNullabilityKind(
2984 *Newnullability,
2985 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2986 != 0))
2987 << DiagNullabilityKind(
2988 *Oldnullability,
2989 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2990 != 0));
2991 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2992 }
2993 } else {
2994 QualType NewT = NewParam->getType();
2995 NewT = S.Context.getAttributedType(
2996 AttributedType::getNullabilityAttrKind(*Oldnullability),
2997 NewT, NewT);
2998 NewParam->setType(NewT);
2999 }
3000 }
3001 }
3002
3003 namespace {
3004
3005 /// Used in MergeFunctionDecl to keep track of function parameters in
3006 /// C.
3007 struct GNUCompatibleParamWarning {
3008 ParmVarDecl *OldParm;
3009 ParmVarDecl *NewParm;
3010 QualType PromotedType;
3011 };
3012
3013 } // end anonymous namespace
3014
3015 // Determine whether the previous declaration was a definition, implicit
3016 // declaration, or a declaration.
3017 template <typename T>
3018 static std::pair<diag::kind, SourceLocation>
getNoteDiagForInvalidRedeclaration(const T * Old,const T * New)3019 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3020 diag::kind PrevDiag;
3021 SourceLocation OldLocation = Old->getLocation();
3022 if (Old->isThisDeclarationADefinition())
3023 PrevDiag = diag::note_previous_definition;
3024 else if (Old->isImplicit()) {
3025 PrevDiag = diag::note_previous_implicit_declaration;
3026 if (OldLocation.isInvalid())
3027 OldLocation = New->getLocation();
3028 } else
3029 PrevDiag = diag::note_previous_declaration;
3030 return std::make_pair(PrevDiag, OldLocation);
3031 }
3032
3033 /// canRedefineFunction - checks if a function can be redefined. Currently,
3034 /// only extern inline functions can be redefined, and even then only in
3035 /// GNU89 mode.
canRedefineFunction(const FunctionDecl * FD,const LangOptions & LangOpts)3036 static bool canRedefineFunction(const FunctionDecl *FD,
3037 const LangOptions& LangOpts) {
3038 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3039 !LangOpts.CPlusPlus &&
3040 FD->isInlineSpecified() &&
3041 FD->getStorageClass() == SC_Extern);
3042 }
3043
getCallingConvAttributedType(QualType T) const3044 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3045 const AttributedType *AT = T->getAs<AttributedType>();
3046 while (AT && !AT->isCallingConv())
3047 AT = AT->getModifiedType()->getAs<AttributedType>();
3048 return AT;
3049 }
3050
3051 template <typename T>
haveIncompatibleLanguageLinkages(const T * Old,const T * New)3052 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3053 const DeclContext *DC = Old->getDeclContext();
3054 if (DC->isRecord())
3055 return false;
3056
3057 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3058 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3059 return true;
3060 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3061 return true;
3062 return false;
3063 }
3064
isExternC(T * D)3065 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
isExternC(VarTemplateDecl *)3066 static bool isExternC(VarTemplateDecl *) { return false; }
3067
3068 /// Check whether a redeclaration of an entity introduced by a
3069 /// using-declaration is valid, given that we know it's not an overload
3070 /// (nor a hidden tag declaration).
3071 template<typename ExpectedDecl>
checkUsingShadowRedecl(Sema & S,UsingShadowDecl * OldS,ExpectedDecl * New)3072 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3073 ExpectedDecl *New) {
3074 // C++11 [basic.scope.declarative]p4:
3075 // Given a set of declarations in a single declarative region, each of
3076 // which specifies the same unqualified name,
3077 // -- they shall all refer to the same entity, or all refer to functions
3078 // and function templates; or
3079 // -- exactly one declaration shall declare a class name or enumeration
3080 // name that is not a typedef name and the other declarations shall all
3081 // refer to the same variable or enumerator, or all refer to functions
3082 // and function templates; in this case the class name or enumeration
3083 // name is hidden (3.3.10).
3084
3085 // C++11 [namespace.udecl]p14:
3086 // If a function declaration in namespace scope or block scope has the
3087 // same name and the same parameter-type-list as a function introduced
3088 // by a using-declaration, and the declarations do not declare the same
3089 // function, the program is ill-formed.
3090
3091 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3092 if (Old &&
3093 !Old->getDeclContext()->getRedeclContext()->Equals(
3094 New->getDeclContext()->getRedeclContext()) &&
3095 !(isExternC(Old) && isExternC(New)))
3096 Old = nullptr;
3097
3098 if (!Old) {
3099 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3100 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3101 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3102 return true;
3103 }
3104 return false;
3105 }
3106
hasIdenticalPassObjectSizeAttrs(const FunctionDecl * A,const FunctionDecl * B)3107 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3108 const FunctionDecl *B) {
3109 assert(A->getNumParams() == B->getNumParams());
3110
3111 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3112 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3113 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3114 if (AttrA == AttrB)
3115 return true;
3116 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3117 AttrA->isDynamic() == AttrB->isDynamic();
3118 };
3119
3120 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3121 }
3122
3123 /// If necessary, adjust the semantic declaration context for a qualified
3124 /// declaration to name the correct inline namespace within the qualifier.
adjustDeclContextForDeclaratorDecl(DeclaratorDecl * NewD,DeclaratorDecl * OldD)3125 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3126 DeclaratorDecl *OldD) {
3127 // The only case where we need to update the DeclContext is when
3128 // redeclaration lookup for a qualified name finds a declaration
3129 // in an inline namespace within the context named by the qualifier:
3130 //
3131 // inline namespace N { int f(); }
3132 // int ::f(); // Sema DC needs adjusting from :: to N::.
3133 //
3134 // For unqualified declarations, the semantic context *can* change
3135 // along the redeclaration chain (for local extern declarations,
3136 // extern "C" declarations, and friend declarations in particular).
3137 if (!NewD->getQualifier())
3138 return;
3139
3140 // NewD is probably already in the right context.
3141 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3142 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3143 if (NamedDC->Equals(SemaDC))
3144 return;
3145
3146 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3147 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3148 "unexpected context for redeclaration");
3149
3150 auto *LexDC = NewD->getLexicalDeclContext();
3151 auto FixSemaDC = [=](NamedDecl *D) {
3152 if (!D)
3153 return;
3154 D->setDeclContext(SemaDC);
3155 D->setLexicalDeclContext(LexDC);
3156 };
3157
3158 FixSemaDC(NewD);
3159 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3160 FixSemaDC(FD->getDescribedFunctionTemplate());
3161 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3162 FixSemaDC(VD->getDescribedVarTemplate());
3163 }
3164
3165 /// MergeFunctionDecl - We just parsed a function 'New' from
3166 /// declarator D which has the same name and scope as a previous
3167 /// declaration 'Old'. Figure out how to resolve this situation,
3168 /// merging decls or emitting diagnostics as appropriate.
3169 ///
3170 /// In C++, New and Old must be declarations that are not
3171 /// overloaded. Use IsOverload to determine whether New and Old are
3172 /// overloaded, and to select the Old declaration that New should be
3173 /// merged with.
3174 ///
3175 /// Returns true if there was an error, false otherwise.
MergeFunctionDecl(FunctionDecl * New,NamedDecl * & OldD,Scope * S,bool MergeTypeWithOld)3176 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3177 Scope *S, bool MergeTypeWithOld) {
3178 // Verify the old decl was also a function.
3179 FunctionDecl *Old = OldD->getAsFunction();
3180 if (!Old) {
3181 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3182 if (New->getFriendObjectKind()) {
3183 Diag(New->getLocation(), diag::err_using_decl_friend);
3184 Diag(Shadow->getTargetDecl()->getLocation(),
3185 diag::note_using_decl_target);
3186 Diag(Shadow->getUsingDecl()->getLocation(),
3187 diag::note_using_decl) << 0;
3188 return true;
3189 }
3190
3191 // Check whether the two declarations might declare the same function.
3192 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3193 return true;
3194 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3195 } else {
3196 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3197 << New->getDeclName();
3198 notePreviousDefinition(OldD, New->getLocation());
3199 return true;
3200 }
3201 }
3202
3203 // If the old declaration is invalid, just give up here.
3204 if (Old->isInvalidDecl())
3205 return true;
3206
3207 // Disallow redeclaration of some builtins.
3208 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3209 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3210 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3211 << Old << Old->getType();
3212 return true;
3213 }
3214
3215 diag::kind PrevDiag;
3216 SourceLocation OldLocation;
3217 std::tie(PrevDiag, OldLocation) =
3218 getNoteDiagForInvalidRedeclaration(Old, New);
3219
3220 // Don't complain about this if we're in GNU89 mode and the old function
3221 // is an extern inline function.
3222 // Don't complain about specializations. They are not supposed to have
3223 // storage classes.
3224 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3225 New->getStorageClass() == SC_Static &&
3226 Old->hasExternalFormalLinkage() &&
3227 !New->getTemplateSpecializationInfo() &&
3228 !canRedefineFunction(Old, getLangOpts())) {
3229 if (getLangOpts().MicrosoftExt) {
3230 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3231 Diag(OldLocation, PrevDiag);
3232 } else {
3233 Diag(New->getLocation(), diag::err_static_non_static) << New;
3234 Diag(OldLocation, PrevDiag);
3235 return true;
3236 }
3237 }
3238
3239 if (New->hasAttr<InternalLinkageAttr>() &&
3240 !Old->hasAttr<InternalLinkageAttr>()) {
3241 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3242 << New->getDeclName();
3243 notePreviousDefinition(Old, New->getLocation());
3244 New->dropAttr<InternalLinkageAttr>();
3245 }
3246
3247 if (CheckRedeclarationModuleOwnership(New, Old))
3248 return true;
3249
3250 if (!getLangOpts().CPlusPlus) {
3251 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3252 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3253 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3254 << New << OldOvl;
3255
3256 // Try our best to find a decl that actually has the overloadable
3257 // attribute for the note. In most cases (e.g. programs with only one
3258 // broken declaration/definition), this won't matter.
3259 //
3260 // FIXME: We could do this if we juggled some extra state in
3261 // OverloadableAttr, rather than just removing it.
3262 const Decl *DiagOld = Old;
3263 if (OldOvl) {
3264 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3265 const auto *A = D->getAttr<OverloadableAttr>();
3266 return A && !A->isImplicit();
3267 });
3268 // If we've implicitly added *all* of the overloadable attrs to this
3269 // chain, emitting a "previous redecl" note is pointless.
3270 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3271 }
3272
3273 if (DiagOld)
3274 Diag(DiagOld->getLocation(),
3275 diag::note_attribute_overloadable_prev_overload)
3276 << OldOvl;
3277
3278 if (OldOvl)
3279 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3280 else
3281 New->dropAttr<OverloadableAttr>();
3282 }
3283 }
3284
3285 // If a function is first declared with a calling convention, but is later
3286 // declared or defined without one, all following decls assume the calling
3287 // convention of the first.
3288 //
3289 // It's OK if a function is first declared without a calling convention,
3290 // but is later declared or defined with the default calling convention.
3291 //
3292 // To test if either decl has an explicit calling convention, we look for
3293 // AttributedType sugar nodes on the type as written. If they are missing or
3294 // were canonicalized away, we assume the calling convention was implicit.
3295 //
3296 // Note also that we DO NOT return at this point, because we still have
3297 // other tests to run.
3298 QualType OldQType = Context.getCanonicalType(Old->getType());
3299 QualType NewQType = Context.getCanonicalType(New->getType());
3300 const FunctionType *OldType = cast<FunctionType>(OldQType);
3301 const FunctionType *NewType = cast<FunctionType>(NewQType);
3302 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3303 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3304 bool RequiresAdjustment = false;
3305
3306 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3307 FunctionDecl *First = Old->getFirstDecl();
3308 const FunctionType *FT =
3309 First->getType().getCanonicalType()->castAs<FunctionType>();
3310 FunctionType::ExtInfo FI = FT->getExtInfo();
3311 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3312 if (!NewCCExplicit) {
3313 // Inherit the CC from the previous declaration if it was specified
3314 // there but not here.
3315 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3316 RequiresAdjustment = true;
3317 } else if (New->getBuiltinID()) {
3318 // Calling Conventions on a Builtin aren't really useful and setting a
3319 // default calling convention and cdecl'ing some builtin redeclarations is
3320 // common, so warn and ignore the calling convention on the redeclaration.
3321 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3322 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3323 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3324 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3325 RequiresAdjustment = true;
3326 } else {
3327 // Calling conventions aren't compatible, so complain.
3328 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3329 Diag(New->getLocation(), diag::err_cconv_change)
3330 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3331 << !FirstCCExplicit
3332 << (!FirstCCExplicit ? "" :
3333 FunctionType::getNameForCallConv(FI.getCC()));
3334
3335 // Put the note on the first decl, since it is the one that matters.
3336 Diag(First->getLocation(), diag::note_previous_declaration);
3337 return true;
3338 }
3339 }
3340
3341 // FIXME: diagnose the other way around?
3342 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3343 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3344 RequiresAdjustment = true;
3345 }
3346
3347 // Merge regparm attribute.
3348 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3349 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3350 if (NewTypeInfo.getHasRegParm()) {
3351 Diag(New->getLocation(), diag::err_regparm_mismatch)
3352 << NewType->getRegParmType()
3353 << OldType->getRegParmType();
3354 Diag(OldLocation, diag::note_previous_declaration);
3355 return true;
3356 }
3357
3358 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3359 RequiresAdjustment = true;
3360 }
3361
3362 // Merge ns_returns_retained attribute.
3363 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3364 if (NewTypeInfo.getProducesResult()) {
3365 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3366 << "'ns_returns_retained'";
3367 Diag(OldLocation, diag::note_previous_declaration);
3368 return true;
3369 }
3370
3371 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3372 RequiresAdjustment = true;
3373 }
3374
3375 if (OldTypeInfo.getNoCallerSavedRegs() !=
3376 NewTypeInfo.getNoCallerSavedRegs()) {
3377 if (NewTypeInfo.getNoCallerSavedRegs()) {
3378 AnyX86NoCallerSavedRegistersAttr *Attr =
3379 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3380 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3381 Diag(OldLocation, diag::note_previous_declaration);
3382 return true;
3383 }
3384
3385 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3386 RequiresAdjustment = true;
3387 }
3388
3389 if (RequiresAdjustment) {
3390 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3391 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3392 New->setType(QualType(AdjustedType, 0));
3393 NewQType = Context.getCanonicalType(New->getType());
3394 }
3395
3396 // If this redeclaration makes the function inline, we may need to add it to
3397 // UndefinedButUsed.
3398 if (!Old->isInlined() && New->isInlined() &&
3399 !New->hasAttr<GNUInlineAttr>() &&
3400 !getLangOpts().GNUInline &&
3401 Old->isUsed(false) &&
3402 !Old->isDefined() && !New->isThisDeclarationADefinition())
3403 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3404 SourceLocation()));
3405
3406 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3407 // about it.
3408 if (New->hasAttr<GNUInlineAttr>() &&
3409 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3410 UndefinedButUsed.erase(Old->getCanonicalDecl());
3411 }
3412
3413 // If pass_object_size params don't match up perfectly, this isn't a valid
3414 // redeclaration.
3415 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3416 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3417 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3418 << New->getDeclName();
3419 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3420 return true;
3421 }
3422
3423 if (getLangOpts().CPlusPlus) {
3424 // C++1z [over.load]p2
3425 // Certain function declarations cannot be overloaded:
3426 // -- Function declarations that differ only in the return type,
3427 // the exception specification, or both cannot be overloaded.
3428
3429 // Check the exception specifications match. This may recompute the type of
3430 // both Old and New if it resolved exception specifications, so grab the
3431 // types again after this. Because this updates the type, we do this before
3432 // any of the other checks below, which may update the "de facto" NewQType
3433 // but do not necessarily update the type of New.
3434 if (CheckEquivalentExceptionSpec(Old, New))
3435 return true;
3436 OldQType = Context.getCanonicalType(Old->getType());
3437 NewQType = Context.getCanonicalType(New->getType());
3438
3439 // Go back to the type source info to compare the declared return types,
3440 // per C++1y [dcl.type.auto]p13:
3441 // Redeclarations or specializations of a function or function template
3442 // with a declared return type that uses a placeholder type shall also
3443 // use that placeholder, not a deduced type.
3444 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3445 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3446 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3447 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3448 OldDeclaredReturnType)) {
3449 QualType ResQT;
3450 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3451 OldDeclaredReturnType->isObjCObjectPointerType())
3452 // FIXME: This does the wrong thing for a deduced return type.
3453 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3454 if (ResQT.isNull()) {
3455 if (New->isCXXClassMember() && New->isOutOfLine())
3456 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3457 << New << New->getReturnTypeSourceRange();
3458 else
3459 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3460 << New->getReturnTypeSourceRange();
3461 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3462 << Old->getReturnTypeSourceRange();
3463 return true;
3464 }
3465 else
3466 NewQType = ResQT;
3467 }
3468
3469 QualType OldReturnType = OldType->getReturnType();
3470 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3471 if (OldReturnType != NewReturnType) {
3472 // If this function has a deduced return type and has already been
3473 // defined, copy the deduced value from the old declaration.
3474 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3475 if (OldAT && OldAT->isDeduced()) {
3476 New->setType(
3477 SubstAutoType(New->getType(),
3478 OldAT->isDependentType() ? Context.DependentTy
3479 : OldAT->getDeducedType()));
3480 NewQType = Context.getCanonicalType(
3481 SubstAutoType(NewQType,
3482 OldAT->isDependentType() ? Context.DependentTy
3483 : OldAT->getDeducedType()));
3484 }
3485 }
3486
3487 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3488 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3489 if (OldMethod && NewMethod) {
3490 // Preserve triviality.
3491 NewMethod->setTrivial(OldMethod->isTrivial());
3492
3493 // MSVC allows explicit template specialization at class scope:
3494 // 2 CXXMethodDecls referring to the same function will be injected.
3495 // We don't want a redeclaration error.
3496 bool IsClassScopeExplicitSpecialization =
3497 OldMethod->isFunctionTemplateSpecialization() &&
3498 NewMethod->isFunctionTemplateSpecialization();
3499 bool isFriend = NewMethod->getFriendObjectKind();
3500
3501 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3502 !IsClassScopeExplicitSpecialization) {
3503 // -- Member function declarations with the same name and the
3504 // same parameter types cannot be overloaded if any of them
3505 // is a static member function declaration.
3506 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3507 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3508 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3509 return true;
3510 }
3511
3512 // C++ [class.mem]p1:
3513 // [...] A member shall not be declared twice in the
3514 // member-specification, except that a nested class or member
3515 // class template can be declared and then later defined.
3516 if (!inTemplateInstantiation()) {
3517 unsigned NewDiag;
3518 if (isa<CXXConstructorDecl>(OldMethod))
3519 NewDiag = diag::err_constructor_redeclared;
3520 else if (isa<CXXDestructorDecl>(NewMethod))
3521 NewDiag = diag::err_destructor_redeclared;
3522 else if (isa<CXXConversionDecl>(NewMethod))
3523 NewDiag = diag::err_conv_function_redeclared;
3524 else
3525 NewDiag = diag::err_member_redeclared;
3526
3527 Diag(New->getLocation(), NewDiag);
3528 } else {
3529 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3530 << New << New->getType();
3531 }
3532 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3533 return true;
3534
3535 // Complain if this is an explicit declaration of a special
3536 // member that was initially declared implicitly.
3537 //
3538 // As an exception, it's okay to befriend such methods in order
3539 // to permit the implicit constructor/destructor/operator calls.
3540 } else if (OldMethod->isImplicit()) {
3541 if (isFriend) {
3542 NewMethod->setImplicit();
3543 } else {
3544 Diag(NewMethod->getLocation(),
3545 diag::err_definition_of_implicitly_declared_member)
3546 << New << getSpecialMember(OldMethod);
3547 return true;
3548 }
3549 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3550 Diag(NewMethod->getLocation(),
3551 diag::err_definition_of_explicitly_defaulted_member)
3552 << getSpecialMember(OldMethod);
3553 return true;
3554 }
3555 }
3556
3557 // C++11 [dcl.attr.noreturn]p1:
3558 // The first declaration of a function shall specify the noreturn
3559 // attribute if any declaration of that function specifies the noreturn
3560 // attribute.
3561 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3562 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3563 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3564 Diag(Old->getFirstDecl()->getLocation(),
3565 diag::note_noreturn_missing_first_decl);
3566 }
3567
3568 // C++11 [dcl.attr.depend]p2:
3569 // The first declaration of a function shall specify the
3570 // carries_dependency attribute for its declarator-id if any declaration
3571 // of the function specifies the carries_dependency attribute.
3572 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3573 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3574 Diag(CDA->getLocation(),
3575 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3576 Diag(Old->getFirstDecl()->getLocation(),
3577 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3578 }
3579
3580 // (C++98 8.3.5p3):
3581 // All declarations for a function shall agree exactly in both the
3582 // return type and the parameter-type-list.
3583 // We also want to respect all the extended bits except noreturn.
3584
3585 // noreturn should now match unless the old type info didn't have it.
3586 QualType OldQTypeForComparison = OldQType;
3587 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3588 auto *OldType = OldQType->castAs<FunctionProtoType>();
3589 const FunctionType *OldTypeForComparison
3590 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3591 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3592 assert(OldQTypeForComparison.isCanonical());
3593 }
3594
3595 if (haveIncompatibleLanguageLinkages(Old, New)) {
3596 // As a special case, retain the language linkage from previous
3597 // declarations of a friend function as an extension.
3598 //
3599 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3600 // and is useful because there's otherwise no way to specify language
3601 // linkage within class scope.
3602 //
3603 // Check cautiously as the friend object kind isn't yet complete.
3604 if (New->getFriendObjectKind() != Decl::FOK_None) {
3605 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3606 Diag(OldLocation, PrevDiag);
3607 } else {
3608 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3609 Diag(OldLocation, PrevDiag);
3610 return true;
3611 }
3612 }
3613
3614 // If the function types are compatible, merge the declarations. Ignore the
3615 // exception specifier because it was already checked above in
3616 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3617 // about incompatible types under -fms-compatibility.
3618 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3619 NewQType))
3620 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3621
3622 // If the types are imprecise (due to dependent constructs in friends or
3623 // local extern declarations), it's OK if they differ. We'll check again
3624 // during instantiation.
3625 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3626 return false;
3627
3628 // Fall through for conflicting redeclarations and redefinitions.
3629 }
3630
3631 // C: Function types need to be compatible, not identical. This handles
3632 // duplicate function decls like "void f(int); void f(enum X);" properly.
3633 if (!getLangOpts().CPlusPlus &&
3634 Context.typesAreCompatible(OldQType, NewQType)) {
3635 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3636 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3637 const FunctionProtoType *OldProto = nullptr;
3638 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3639 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3640 // The old declaration provided a function prototype, but the
3641 // new declaration does not. Merge in the prototype.
3642 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3643 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3644 NewQType =
3645 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3646 OldProto->getExtProtoInfo());
3647 New->setType(NewQType);
3648 New->setHasInheritedPrototype();
3649
3650 // Synthesize parameters with the same types.
3651 SmallVector<ParmVarDecl*, 16> Params;
3652 for (const auto &ParamType : OldProto->param_types()) {
3653 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3654 SourceLocation(), nullptr,
3655 ParamType, /*TInfo=*/nullptr,
3656 SC_None, nullptr);
3657 Param->setScopeInfo(0, Params.size());
3658 Param->setImplicit();
3659 Params.push_back(Param);
3660 }
3661
3662 New->setParams(Params);
3663 }
3664
3665 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3666 }
3667
3668 // Check if the function types are compatible when pointer size address
3669 // spaces are ignored.
3670 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3671 return false;
3672
3673 // GNU C permits a K&R definition to follow a prototype declaration
3674 // if the declared types of the parameters in the K&R definition
3675 // match the types in the prototype declaration, even when the
3676 // promoted types of the parameters from the K&R definition differ
3677 // from the types in the prototype. GCC then keeps the types from
3678 // the prototype.
3679 //
3680 // If a variadic prototype is followed by a non-variadic K&R definition,
3681 // the K&R definition becomes variadic. This is sort of an edge case, but
3682 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3683 // C99 6.9.1p8.
3684 if (!getLangOpts().CPlusPlus &&
3685 Old->hasPrototype() && !New->hasPrototype() &&
3686 New->getType()->getAs<FunctionProtoType>() &&
3687 Old->getNumParams() == New->getNumParams()) {
3688 SmallVector<QualType, 16> ArgTypes;
3689 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3690 const FunctionProtoType *OldProto
3691 = Old->getType()->getAs<FunctionProtoType>();
3692 const FunctionProtoType *NewProto
3693 = New->getType()->getAs<FunctionProtoType>();
3694
3695 // Determine whether this is the GNU C extension.
3696 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3697 NewProto->getReturnType());
3698 bool LooseCompatible = !MergedReturn.isNull();
3699 for (unsigned Idx = 0, End = Old->getNumParams();
3700 LooseCompatible && Idx != End; ++Idx) {
3701 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3702 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3703 if (Context.typesAreCompatible(OldParm->getType(),
3704 NewProto->getParamType(Idx))) {
3705 ArgTypes.push_back(NewParm->getType());
3706 } else if (Context.typesAreCompatible(OldParm->getType(),
3707 NewParm->getType(),
3708 /*CompareUnqualified=*/true)) {
3709 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3710 NewProto->getParamType(Idx) };
3711 Warnings.push_back(Warn);
3712 ArgTypes.push_back(NewParm->getType());
3713 } else
3714 LooseCompatible = false;
3715 }
3716
3717 if (LooseCompatible) {
3718 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3719 Diag(Warnings[Warn].NewParm->getLocation(),
3720 diag::ext_param_promoted_not_compatible_with_prototype)
3721 << Warnings[Warn].PromotedType
3722 << Warnings[Warn].OldParm->getType();
3723 if (Warnings[Warn].OldParm->getLocation().isValid())
3724 Diag(Warnings[Warn].OldParm->getLocation(),
3725 diag::note_previous_declaration);
3726 }
3727
3728 if (MergeTypeWithOld)
3729 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3730 OldProto->getExtProtoInfo()));
3731 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3732 }
3733
3734 // Fall through to diagnose conflicting types.
3735 }
3736
3737 // A function that has already been declared has been redeclared or
3738 // defined with a different type; show an appropriate diagnostic.
3739
3740 // If the previous declaration was an implicitly-generated builtin
3741 // declaration, then at the very least we should use a specialized note.
3742 unsigned BuiltinID;
3743 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3744 // If it's actually a library-defined builtin function like 'malloc'
3745 // or 'printf', just warn about the incompatible redeclaration.
3746 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3747 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3748 Diag(OldLocation, diag::note_previous_builtin_declaration)
3749 << Old << Old->getType();
3750
3751 // If this is a global redeclaration, just forget hereafter
3752 // about the "builtin-ness" of the function.
3753 //
3754 // Doing this for local extern declarations is problematic. If
3755 // the builtin declaration remains visible, a second invalid
3756 // local declaration will produce a hard error; if it doesn't
3757 // remain visible, a single bogus local redeclaration (which is
3758 // actually only a warning) could break all the downstream code.
3759 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3760 New->getIdentifier()->revertBuiltin();
3761
3762 return false;
3763 }
3764
3765 PrevDiag = diag::note_previous_builtin_declaration;
3766 }
3767
3768 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3769 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3770 return true;
3771 }
3772
3773 /// Completes the merge of two function declarations that are
3774 /// known to be compatible.
3775 ///
3776 /// This routine handles the merging of attributes and other
3777 /// properties of function declarations from the old declaration to
3778 /// the new declaration, once we know that New is in fact a
3779 /// redeclaration of Old.
3780 ///
3781 /// \returns false
MergeCompatibleFunctionDecls(FunctionDecl * New,FunctionDecl * Old,Scope * S,bool MergeTypeWithOld)3782 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3783 Scope *S, bool MergeTypeWithOld) {
3784 // Merge the attributes
3785 mergeDeclAttributes(New, Old);
3786
3787 // Merge "pure" flag.
3788 if (Old->isPure())
3789 New->setPure();
3790
3791 // Merge "used" flag.
3792 if (Old->getMostRecentDecl()->isUsed(false))
3793 New->setIsUsed();
3794
3795 // Merge attributes from the parameters. These can mismatch with K&R
3796 // declarations.
3797 if (New->getNumParams() == Old->getNumParams())
3798 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3799 ParmVarDecl *NewParam = New->getParamDecl(i);
3800 ParmVarDecl *OldParam = Old->getParamDecl(i);
3801 mergeParamDeclAttributes(NewParam, OldParam, *this);
3802 mergeParamDeclTypes(NewParam, OldParam, *this);
3803 }
3804
3805 if (getLangOpts().CPlusPlus)
3806 return MergeCXXFunctionDecl(New, Old, S);
3807
3808 // Merge the function types so the we get the composite types for the return
3809 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3810 // was visible.
3811 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3812 if (!Merged.isNull() && MergeTypeWithOld)
3813 New->setType(Merged);
3814
3815 return false;
3816 }
3817
mergeObjCMethodDecls(ObjCMethodDecl * newMethod,ObjCMethodDecl * oldMethod)3818 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3819 ObjCMethodDecl *oldMethod) {
3820 // Merge the attributes, including deprecated/unavailable
3821 AvailabilityMergeKind MergeKind =
3822 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3823 ? AMK_ProtocolImplementation
3824 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3825 : AMK_Override;
3826
3827 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3828
3829 // Merge attributes from the parameters.
3830 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3831 oe = oldMethod->param_end();
3832 for (ObjCMethodDecl::param_iterator
3833 ni = newMethod->param_begin(), ne = newMethod->param_end();
3834 ni != ne && oi != oe; ++ni, ++oi)
3835 mergeParamDeclAttributes(*ni, *oi, *this);
3836
3837 CheckObjCMethodOverride(newMethod, oldMethod);
3838 }
3839
diagnoseVarDeclTypeMismatch(Sema & S,VarDecl * New,VarDecl * Old)3840 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3841 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3842
3843 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3844 ? diag::err_redefinition_different_type
3845 : diag::err_redeclaration_different_type)
3846 << New->getDeclName() << New->getType() << Old->getType();
3847
3848 diag::kind PrevDiag;
3849 SourceLocation OldLocation;
3850 std::tie(PrevDiag, OldLocation)
3851 = getNoteDiagForInvalidRedeclaration(Old, New);
3852 S.Diag(OldLocation, PrevDiag);
3853 New->setInvalidDecl();
3854 }
3855
3856 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3857 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
3858 /// emitting diagnostics as appropriate.
3859 ///
3860 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3861 /// to here in AddInitializerToDecl. We can't check them before the initializer
3862 /// is attached.
MergeVarDeclTypes(VarDecl * New,VarDecl * Old,bool MergeTypeWithOld)3863 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3864 bool MergeTypeWithOld) {
3865 if (New->isInvalidDecl() || Old->isInvalidDecl())
3866 return;
3867
3868 QualType MergedT;
3869 if (getLangOpts().CPlusPlus) {
3870 if (New->getType()->isUndeducedType()) {
3871 // We don't know what the new type is until the initializer is attached.
3872 return;
3873 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3874 // These could still be something that needs exception specs checked.
3875 return MergeVarDeclExceptionSpecs(New, Old);
3876 }
3877 // C++ [basic.link]p10:
3878 // [...] the types specified by all declarations referring to a given
3879 // object or function shall be identical, except that declarations for an
3880 // array object can specify array types that differ by the presence or
3881 // absence of a major array bound (8.3.4).
3882 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3883 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3884 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3885
3886 // We are merging a variable declaration New into Old. If it has an array
3887 // bound, and that bound differs from Old's bound, we should diagnose the
3888 // mismatch.
3889 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3890 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3891 PrevVD = PrevVD->getPreviousDecl()) {
3892 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3893 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3894 continue;
3895
3896 if (!Context.hasSameType(NewArray, PrevVDTy))
3897 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3898 }
3899 }
3900
3901 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3902 if (Context.hasSameType(OldArray->getElementType(),
3903 NewArray->getElementType()))
3904 MergedT = New->getType();
3905 }
3906 // FIXME: Check visibility. New is hidden but has a complete type. If New
3907 // has no array bound, it should not inherit one from Old, if Old is not
3908 // visible.
3909 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3910 if (Context.hasSameType(OldArray->getElementType(),
3911 NewArray->getElementType()))
3912 MergedT = Old->getType();
3913 }
3914 }
3915 else if (New->getType()->isObjCObjectPointerType() &&
3916 Old->getType()->isObjCObjectPointerType()) {
3917 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3918 Old->getType());
3919 }
3920 } else {
3921 // C 6.2.7p2:
3922 // All declarations that refer to the same object or function shall have
3923 // compatible type.
3924 MergedT = Context.mergeTypes(New->getType(), Old->getType());
3925 }
3926 if (MergedT.isNull()) {
3927 // It's OK if we couldn't merge types if either type is dependent, for a
3928 // block-scope variable. In other cases (static data members of class
3929 // templates, variable templates, ...), we require the types to be
3930 // equivalent.
3931 // FIXME: The C++ standard doesn't say anything about this.
3932 if ((New->getType()->isDependentType() ||
3933 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3934 // If the old type was dependent, we can't merge with it, so the new type
3935 // becomes dependent for now. We'll reproduce the original type when we
3936 // instantiate the TypeSourceInfo for the variable.
3937 if (!New->getType()->isDependentType() && MergeTypeWithOld)
3938 New->setType(Context.DependentTy);
3939 return;
3940 }
3941 return diagnoseVarDeclTypeMismatch(*this, New, Old);
3942 }
3943
3944 // Don't actually update the type on the new declaration if the old
3945 // declaration was an extern declaration in a different scope.
3946 if (MergeTypeWithOld)
3947 New->setType(MergedT);
3948 }
3949
mergeTypeWithPrevious(Sema & S,VarDecl * NewVD,VarDecl * OldVD,LookupResult & Previous)3950 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3951 LookupResult &Previous) {
3952 // C11 6.2.7p4:
3953 // For an identifier with internal or external linkage declared
3954 // in a scope in which a prior declaration of that identifier is
3955 // visible, if the prior declaration specifies internal or
3956 // external linkage, the type of the identifier at the later
3957 // declaration becomes the composite type.
3958 //
3959 // If the variable isn't visible, we do not merge with its type.
3960 if (Previous.isShadowed())
3961 return false;
3962
3963 if (S.getLangOpts().CPlusPlus) {
3964 // C++11 [dcl.array]p3:
3965 // If there is a preceding declaration of the entity in the same
3966 // scope in which the bound was specified, an omitted array bound
3967 // is taken to be the same as in that earlier declaration.
3968 return NewVD->isPreviousDeclInSameBlockScope() ||
3969 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3970 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3971 } else {
3972 // If the old declaration was function-local, don't merge with its
3973 // type unless we're in the same function.
3974 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3975 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3976 }
3977 }
3978
3979 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3980 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
3981 /// situation, merging decls or emitting diagnostics as appropriate.
3982 ///
3983 /// Tentative definition rules (C99 6.9.2p2) are checked by
3984 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3985 /// definitions here, since the initializer hasn't been attached.
3986 ///
MergeVarDecl(VarDecl * New,LookupResult & Previous)3987 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3988 // If the new decl is already invalid, don't do any other checking.
3989 if (New->isInvalidDecl())
3990 return;
3991
3992 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3993 return;
3994
3995 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3996
3997 // Verify the old decl was also a variable or variable template.
3998 VarDecl *Old = nullptr;
3999 VarTemplateDecl *OldTemplate = nullptr;
4000 if (Previous.isSingleResult()) {
4001 if (NewTemplate) {
4002 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4003 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4004
4005 if (auto *Shadow =
4006 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4007 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4008 return New->setInvalidDecl();
4009 } else {
4010 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4011
4012 if (auto *Shadow =
4013 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4014 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4015 return New->setInvalidDecl();
4016 }
4017 }
4018 if (!Old) {
4019 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4020 << New->getDeclName();
4021 notePreviousDefinition(Previous.getRepresentativeDecl(),
4022 New->getLocation());
4023 return New->setInvalidDecl();
4024 }
4025
4026 // Ensure the template parameters are compatible.
4027 if (NewTemplate &&
4028 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4029 OldTemplate->getTemplateParameters(),
4030 /*Complain=*/true, TPL_TemplateMatch))
4031 return New->setInvalidDecl();
4032
4033 // C++ [class.mem]p1:
4034 // A member shall not be declared twice in the member-specification [...]
4035 //
4036 // Here, we need only consider static data members.
4037 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4038 Diag(New->getLocation(), diag::err_duplicate_member)
4039 << New->getIdentifier();
4040 Diag(Old->getLocation(), diag::note_previous_declaration);
4041 New->setInvalidDecl();
4042 }
4043
4044 mergeDeclAttributes(New, Old);
4045 // Warn if an already-declared variable is made a weak_import in a subsequent
4046 // declaration
4047 if (New->hasAttr<WeakImportAttr>() &&
4048 Old->getStorageClass() == SC_None &&
4049 !Old->hasAttr<WeakImportAttr>()) {
4050 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4051 notePreviousDefinition(Old, New->getLocation());
4052 // Remove weak_import attribute on new declaration.
4053 New->dropAttr<WeakImportAttr>();
4054 }
4055
4056 if (New->hasAttr<InternalLinkageAttr>() &&
4057 !Old->hasAttr<InternalLinkageAttr>()) {
4058 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4059 << New->getDeclName();
4060 notePreviousDefinition(Old, New->getLocation());
4061 New->dropAttr<InternalLinkageAttr>();
4062 }
4063
4064 // Merge the types.
4065 VarDecl *MostRecent = Old->getMostRecentDecl();
4066 if (MostRecent != Old) {
4067 MergeVarDeclTypes(New, MostRecent,
4068 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4069 if (New->isInvalidDecl())
4070 return;
4071 }
4072
4073 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4074 if (New->isInvalidDecl())
4075 return;
4076
4077 diag::kind PrevDiag;
4078 SourceLocation OldLocation;
4079 std::tie(PrevDiag, OldLocation) =
4080 getNoteDiagForInvalidRedeclaration(Old, New);
4081
4082 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4083 if (New->getStorageClass() == SC_Static &&
4084 !New->isStaticDataMember() &&
4085 Old->hasExternalFormalLinkage()) {
4086 if (getLangOpts().MicrosoftExt) {
4087 Diag(New->getLocation(), diag::ext_static_non_static)
4088 << New->getDeclName();
4089 Diag(OldLocation, PrevDiag);
4090 } else {
4091 Diag(New->getLocation(), diag::err_static_non_static)
4092 << New->getDeclName();
4093 Diag(OldLocation, PrevDiag);
4094 return New->setInvalidDecl();
4095 }
4096 }
4097 // C99 6.2.2p4:
4098 // For an identifier declared with the storage-class specifier
4099 // extern in a scope in which a prior declaration of that
4100 // identifier is visible,23) if the prior declaration specifies
4101 // internal or external linkage, the linkage of the identifier at
4102 // the later declaration is the same as the linkage specified at
4103 // the prior declaration. If no prior declaration is visible, or
4104 // if the prior declaration specifies no linkage, then the
4105 // identifier has external linkage.
4106 if (New->hasExternalStorage() && Old->hasLinkage())
4107 /* Okay */;
4108 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4109 !New->isStaticDataMember() &&
4110 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4111 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4112 Diag(OldLocation, PrevDiag);
4113 return New->setInvalidDecl();
4114 }
4115
4116 // Check if extern is followed by non-extern and vice-versa.
4117 if (New->hasExternalStorage() &&
4118 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4119 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4120 Diag(OldLocation, PrevDiag);
4121 return New->setInvalidDecl();
4122 }
4123 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4124 !New->hasExternalStorage()) {
4125 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4126 Diag(OldLocation, PrevDiag);
4127 return New->setInvalidDecl();
4128 }
4129
4130 if (CheckRedeclarationModuleOwnership(New, Old))
4131 return;
4132
4133 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4134
4135 // FIXME: The test for external storage here seems wrong? We still
4136 // need to check for mismatches.
4137 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4138 // Don't complain about out-of-line definitions of static members.
4139 !(Old->getLexicalDeclContext()->isRecord() &&
4140 !New->getLexicalDeclContext()->isRecord())) {
4141 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4142 Diag(OldLocation, PrevDiag);
4143 return New->setInvalidDecl();
4144 }
4145
4146 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4147 if (VarDecl *Def = Old->getDefinition()) {
4148 // C++1z [dcl.fcn.spec]p4:
4149 // If the definition of a variable appears in a translation unit before
4150 // its first declaration as inline, the program is ill-formed.
4151 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4152 Diag(Def->getLocation(), diag::note_previous_definition);
4153 }
4154 }
4155
4156 // If this redeclaration makes the variable inline, we may need to add it to
4157 // UndefinedButUsed.
4158 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4159 !Old->getDefinition() && !New->isThisDeclarationADefinition())
4160 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4161 SourceLocation()));
4162
4163 if (New->getTLSKind() != Old->getTLSKind()) {
4164 if (!Old->getTLSKind()) {
4165 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4166 Diag(OldLocation, PrevDiag);
4167 } else if (!New->getTLSKind()) {
4168 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4169 Diag(OldLocation, PrevDiag);
4170 } else {
4171 // Do not allow redeclaration to change the variable between requiring
4172 // static and dynamic initialization.
4173 // FIXME: GCC allows this, but uses the TLS keyword on the first
4174 // declaration to determine the kind. Do we need to be compatible here?
4175 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4176 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4177 Diag(OldLocation, PrevDiag);
4178 }
4179 }
4180
4181 // C++ doesn't have tentative definitions, so go right ahead and check here.
4182 if (getLangOpts().CPlusPlus &&
4183 New->isThisDeclarationADefinition() == VarDecl::Definition) {
4184 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4185 Old->getCanonicalDecl()->isConstexpr()) {
4186 // This definition won't be a definition any more once it's been merged.
4187 Diag(New->getLocation(),
4188 diag::warn_deprecated_redundant_constexpr_static_def);
4189 } else if (VarDecl *Def = Old->getDefinition()) {
4190 if (checkVarDeclRedefinition(Def, New))
4191 return;
4192 }
4193 }
4194
4195 if (haveIncompatibleLanguageLinkages(Old, New)) {
4196 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4197 Diag(OldLocation, PrevDiag);
4198 New->setInvalidDecl();
4199 return;
4200 }
4201
4202 // Merge "used" flag.
4203 if (Old->getMostRecentDecl()->isUsed(false))
4204 New->setIsUsed();
4205
4206 // Keep a chain of previous declarations.
4207 New->setPreviousDecl(Old);
4208 if (NewTemplate)
4209 NewTemplate->setPreviousDecl(OldTemplate);
4210 adjustDeclContextForDeclaratorDecl(New, Old);
4211
4212 // Inherit access appropriately.
4213 New->setAccess(Old->getAccess());
4214 if (NewTemplate)
4215 NewTemplate->setAccess(New->getAccess());
4216
4217 if (Old->isInline())
4218 New->setImplicitlyInline();
4219 }
4220
notePreviousDefinition(const NamedDecl * Old,SourceLocation New)4221 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4222 SourceManager &SrcMgr = getSourceManager();
4223 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4224 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4225 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4226 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4227 auto &HSI = PP.getHeaderSearchInfo();
4228 StringRef HdrFilename =
4229 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4230
4231 auto noteFromModuleOrInclude = [&](Module *Mod,
4232 SourceLocation IncLoc) -> bool {
4233 // Redefinition errors with modules are common with non modular mapped
4234 // headers, example: a non-modular header H in module A that also gets
4235 // included directly in a TU. Pointing twice to the same header/definition
4236 // is confusing, try to get better diagnostics when modules is on.
4237 if (IncLoc.isValid()) {
4238 if (Mod) {
4239 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4240 << HdrFilename.str() << Mod->getFullModuleName();
4241 if (!Mod->DefinitionLoc.isInvalid())
4242 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4243 << Mod->getFullModuleName();
4244 } else {
4245 Diag(IncLoc, diag::note_redefinition_include_same_file)
4246 << HdrFilename.str();
4247 }
4248 return true;
4249 }
4250
4251 return false;
4252 };
4253
4254 // Is it the same file and same offset? Provide more information on why
4255 // this leads to a redefinition error.
4256 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4257 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4258 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4259 bool EmittedDiag =
4260 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4261 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4262
4263 // If the header has no guards, emit a note suggesting one.
4264 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4265 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4266
4267 if (EmittedDiag)
4268 return;
4269 }
4270
4271 // Redefinition coming from different files or couldn't do better above.
4272 if (Old->getLocation().isValid())
4273 Diag(Old->getLocation(), diag::note_previous_definition);
4274 }
4275
4276 /// We've just determined that \p Old and \p New both appear to be definitions
4277 /// of the same variable. Either diagnose or fix the problem.
checkVarDeclRedefinition(VarDecl * Old,VarDecl * New)4278 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4279 if (!hasVisibleDefinition(Old) &&
4280 (New->getFormalLinkage() == InternalLinkage ||
4281 New->isInline() ||
4282 New->getDescribedVarTemplate() ||
4283 New->getNumTemplateParameterLists() ||
4284 New->getDeclContext()->isDependentContext())) {
4285 // The previous definition is hidden, and multiple definitions are
4286 // permitted (in separate TUs). Demote this to a declaration.
4287 New->demoteThisDefinitionToDeclaration();
4288
4289 // Make the canonical definition visible.
4290 if (auto *OldTD = Old->getDescribedVarTemplate())
4291 makeMergedDefinitionVisible(OldTD);
4292 makeMergedDefinitionVisible(Old);
4293 return false;
4294 } else {
4295 Diag(New->getLocation(), diag::err_redefinition) << New;
4296 notePreviousDefinition(Old, New->getLocation());
4297 New->setInvalidDecl();
4298 return true;
4299 }
4300 }
4301
4302 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4303 /// no declarator (e.g. "struct foo;") is parsed.
4304 Decl *
ParsedFreeStandingDeclSpec(Scope * S,AccessSpecifier AS,DeclSpec & DS,RecordDecl * & AnonRecord)4305 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4306 RecordDecl *&AnonRecord) {
4307 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4308 AnonRecord);
4309 }
4310
4311 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4312 // disambiguate entities defined in different scopes.
4313 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4314 // compatibility.
4315 // We will pick our mangling number depending on which version of MSVC is being
4316 // targeted.
getMSManglingNumber(const LangOptions & LO,Scope * S)4317 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4318 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4319 ? S->getMSCurManglingNumber()
4320 : S->getMSLastManglingNumber();
4321 }
4322
handleTagNumbering(const TagDecl * Tag,Scope * TagScope)4323 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4324 if (!Context.getLangOpts().CPlusPlus)
4325 return;
4326
4327 if (isa<CXXRecordDecl>(Tag->getParent())) {
4328 // If this tag is the direct child of a class, number it if
4329 // it is anonymous.
4330 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4331 return;
4332 MangleNumberingContext &MCtx =
4333 Context.getManglingNumberContext(Tag->getParent());
4334 Context.setManglingNumber(
4335 Tag, MCtx.getManglingNumber(
4336 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4337 return;
4338 }
4339
4340 // If this tag isn't a direct child of a class, number it if it is local.
4341 MangleNumberingContext *MCtx;
4342 Decl *ManglingContextDecl;
4343 std::tie(MCtx, ManglingContextDecl) =
4344 getCurrentMangleNumberContext(Tag->getDeclContext());
4345 if (MCtx) {
4346 Context.setManglingNumber(
4347 Tag, MCtx->getManglingNumber(
4348 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4349 }
4350 }
4351
setTagNameForLinkagePurposes(TagDecl * TagFromDeclSpec,TypedefNameDecl * NewTD)4352 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4353 TypedefNameDecl *NewTD) {
4354 if (TagFromDeclSpec->isInvalidDecl())
4355 return;
4356
4357 // Do nothing if the tag already has a name for linkage purposes.
4358 if (TagFromDeclSpec->hasNameForLinkage())
4359 return;
4360
4361 // A well-formed anonymous tag must always be a TUK_Definition.
4362 assert(TagFromDeclSpec->isThisDeclarationADefinition());
4363
4364 // The type must match the tag exactly; no qualifiers allowed.
4365 if (!Context.hasSameType(NewTD->getUnderlyingType(),
4366 Context.getTagDeclType(TagFromDeclSpec))) {
4367 if (getLangOpts().CPlusPlus)
4368 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4369 return;
4370 }
4371
4372 // If we've already computed linkage for the anonymous tag, then
4373 // adding a typedef name for the anonymous decl can change that
4374 // linkage, which might be a serious problem. Diagnose this as
4375 // unsupported and ignore the typedef name. TODO: we should
4376 // pursue this as a language defect and establish a formal rule
4377 // for how to handle it.
4378 if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4379 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4380
4381 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4382 tagLoc = getLocForEndOfToken(tagLoc);
4383
4384 llvm::SmallString<40> textToInsert;
4385 textToInsert += ' ';
4386 textToInsert += NewTD->getIdentifier()->getName();
4387 Diag(tagLoc, diag::note_typedef_changes_linkage)
4388 << FixItHint::CreateInsertion(tagLoc, textToInsert);
4389 return;
4390 }
4391
4392 // Otherwise, set this is the anon-decl typedef for the tag.
4393 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4394 }
4395
GetDiagnosticTypeSpecifierID(DeclSpec::TST T)4396 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4397 switch (T) {
4398 case DeclSpec::TST_class:
4399 return 0;
4400 case DeclSpec::TST_struct:
4401 return 1;
4402 case DeclSpec::TST_interface:
4403 return 2;
4404 case DeclSpec::TST_union:
4405 return 3;
4406 case DeclSpec::TST_enum:
4407 return 4;
4408 default:
4409 llvm_unreachable("unexpected type specifier");
4410 }
4411 }
4412
4413 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4414 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4415 /// parameters to cope with template friend declarations.
4416 Decl *
ParsedFreeStandingDeclSpec(Scope * S,AccessSpecifier AS,DeclSpec & DS,MultiTemplateParamsArg TemplateParams,bool IsExplicitInstantiation,RecordDecl * & AnonRecord)4417 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4418 MultiTemplateParamsArg TemplateParams,
4419 bool IsExplicitInstantiation,
4420 RecordDecl *&AnonRecord) {
4421 Decl *TagD = nullptr;
4422 TagDecl *Tag = nullptr;
4423 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4424 DS.getTypeSpecType() == DeclSpec::TST_struct ||
4425 DS.getTypeSpecType() == DeclSpec::TST_interface ||
4426 DS.getTypeSpecType() == DeclSpec::TST_union ||
4427 DS.getTypeSpecType() == DeclSpec::TST_enum) {
4428 TagD = DS.getRepAsDecl();
4429
4430 if (!TagD) // We probably had an error
4431 return nullptr;
4432
4433 // Note that the above type specs guarantee that the
4434 // type rep is a Decl, whereas in many of the others
4435 // it's a Type.
4436 if (isa<TagDecl>(TagD))
4437 Tag = cast<TagDecl>(TagD);
4438 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4439 Tag = CTD->getTemplatedDecl();
4440 }
4441
4442 if (Tag) {
4443 handleTagNumbering(Tag, S);
4444 Tag->setFreeStanding();
4445 if (Tag->isInvalidDecl())
4446 return Tag;
4447 }
4448
4449 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4450 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4451 // or incomplete types shall not be restrict-qualified."
4452 if (TypeQuals & DeclSpec::TQ_restrict)
4453 Diag(DS.getRestrictSpecLoc(),
4454 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4455 << DS.getSourceRange();
4456 }
4457
4458 if (DS.isInlineSpecified())
4459 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4460 << getLangOpts().CPlusPlus17;
4461
4462 if (DS.hasConstexprSpecifier()) {
4463 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4464 // and definitions of functions and variables.
4465 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4466 // the declaration of a function or function template
4467 if (Tag)
4468 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4469 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4470 << DS.getConstexprSpecifier();
4471 else
4472 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4473 << DS.getConstexprSpecifier();
4474 // Don't emit warnings after this error.
4475 return TagD;
4476 }
4477
4478 DiagnoseFunctionSpecifiers(DS);
4479
4480 if (DS.isFriendSpecified()) {
4481 // If we're dealing with a decl but not a TagDecl, assume that
4482 // whatever routines created it handled the friendship aspect.
4483 if (TagD && !Tag)
4484 return nullptr;
4485 return ActOnFriendTypeDecl(S, DS, TemplateParams);
4486 }
4487
4488 const CXXScopeSpec &SS = DS.getTypeSpecScope();
4489 bool IsExplicitSpecialization =
4490 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4491 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4492 !IsExplicitInstantiation && !IsExplicitSpecialization &&
4493 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4494 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4495 // nested-name-specifier unless it is an explicit instantiation
4496 // or an explicit specialization.
4497 //
4498 // FIXME: We allow class template partial specializations here too, per the
4499 // obvious intent of DR1819.
4500 //
4501 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4502 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4503 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4504 return nullptr;
4505 }
4506
4507 // Track whether this decl-specifier declares anything.
4508 bool DeclaresAnything = true;
4509
4510 // Handle anonymous struct definitions.
4511 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4512 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4513 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4514 if (getLangOpts().CPlusPlus ||
4515 Record->getDeclContext()->isRecord()) {
4516 // If CurContext is a DeclContext that can contain statements,
4517 // RecursiveASTVisitor won't visit the decls that
4518 // BuildAnonymousStructOrUnion() will put into CurContext.
4519 // Also store them here so that they can be part of the
4520 // DeclStmt that gets created in this case.
4521 // FIXME: Also return the IndirectFieldDecls created by
4522 // BuildAnonymousStructOr union, for the same reason?
4523 if (CurContext->isFunctionOrMethod())
4524 AnonRecord = Record;
4525 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4526 Context.getPrintingPolicy());
4527 }
4528
4529 DeclaresAnything = false;
4530 }
4531 }
4532
4533 // C11 6.7.2.1p2:
4534 // A struct-declaration that does not declare an anonymous structure or
4535 // anonymous union shall contain a struct-declarator-list.
4536 //
4537 // This rule also existed in C89 and C99; the grammar for struct-declaration
4538 // did not permit a struct-declaration without a struct-declarator-list.
4539 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4540 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4541 // Check for Microsoft C extension: anonymous struct/union member.
4542 // Handle 2 kinds of anonymous struct/union:
4543 // struct STRUCT;
4544 // union UNION;
4545 // and
4546 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4547 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4548 if ((Tag && Tag->getDeclName()) ||
4549 DS.getTypeSpecType() == DeclSpec::TST_typename) {
4550 RecordDecl *Record = nullptr;
4551 if (Tag)
4552 Record = dyn_cast<RecordDecl>(Tag);
4553 else if (const RecordType *RT =
4554 DS.getRepAsType().get()->getAsStructureType())
4555 Record = RT->getDecl();
4556 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4557 Record = UT->getDecl();
4558
4559 if (Record && getLangOpts().MicrosoftExt) {
4560 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4561 << Record->isUnion() << DS.getSourceRange();
4562 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4563 }
4564
4565 DeclaresAnything = false;
4566 }
4567 }
4568
4569 // Skip all the checks below if we have a type error.
4570 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4571 (TagD && TagD->isInvalidDecl()))
4572 return TagD;
4573
4574 if (getLangOpts().CPlusPlus &&
4575 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4576 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4577 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4578 !Enum->getIdentifier() && !Enum->isInvalidDecl())
4579 DeclaresAnything = false;
4580
4581 if (!DS.isMissingDeclaratorOk()) {
4582 // Customize diagnostic for a typedef missing a name.
4583 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4584 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4585 << DS.getSourceRange();
4586 else
4587 DeclaresAnything = false;
4588 }
4589
4590 if (DS.isModulePrivateSpecified() &&
4591 Tag && Tag->getDeclContext()->isFunctionOrMethod())
4592 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4593 << Tag->getTagKind()
4594 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4595
4596 ActOnDocumentableDecl(TagD);
4597
4598 // C 6.7/2:
4599 // A declaration [...] shall declare at least a declarator [...], a tag,
4600 // or the members of an enumeration.
4601 // C++ [dcl.dcl]p3:
4602 // [If there are no declarators], and except for the declaration of an
4603 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4604 // names into the program, or shall redeclare a name introduced by a
4605 // previous declaration.
4606 if (!DeclaresAnything) {
4607 // In C, we allow this as a (popular) extension / bug. Don't bother
4608 // producing further diagnostics for redundant qualifiers after this.
4609 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4610 return TagD;
4611 }
4612
4613 // C++ [dcl.stc]p1:
4614 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4615 // init-declarator-list of the declaration shall not be empty.
4616 // C++ [dcl.fct.spec]p1:
4617 // If a cv-qualifier appears in a decl-specifier-seq, the
4618 // init-declarator-list of the declaration shall not be empty.
4619 //
4620 // Spurious qualifiers here appear to be valid in C.
4621 unsigned DiagID = diag::warn_standalone_specifier;
4622 if (getLangOpts().CPlusPlus)
4623 DiagID = diag::ext_standalone_specifier;
4624
4625 // Note that a linkage-specification sets a storage class, but
4626 // 'extern "C" struct foo;' is actually valid and not theoretically
4627 // useless.
4628 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4629 if (SCS == DeclSpec::SCS_mutable)
4630 // Since mutable is not a viable storage class specifier in C, there is
4631 // no reason to treat it as an extension. Instead, diagnose as an error.
4632 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4633 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4634 Diag(DS.getStorageClassSpecLoc(), DiagID)
4635 << DeclSpec::getSpecifierName(SCS);
4636 }
4637
4638 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4639 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4640 << DeclSpec::getSpecifierName(TSCS);
4641 if (DS.getTypeQualifiers()) {
4642 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4643 Diag(DS.getConstSpecLoc(), DiagID) << "const";
4644 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4645 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4646 // Restrict is covered above.
4647 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4648 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4649 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4650 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4651 }
4652
4653 // Warn about ignored type attributes, for example:
4654 // __attribute__((aligned)) struct A;
4655 // Attributes should be placed after tag to apply to type declaration.
4656 if (!DS.getAttributes().empty()) {
4657 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4658 if (TypeSpecType == DeclSpec::TST_class ||
4659 TypeSpecType == DeclSpec::TST_struct ||
4660 TypeSpecType == DeclSpec::TST_interface ||
4661 TypeSpecType == DeclSpec::TST_union ||
4662 TypeSpecType == DeclSpec::TST_enum) {
4663 for (const ParsedAttr &AL : DS.getAttributes())
4664 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4665 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4666 }
4667 }
4668
4669 return TagD;
4670 }
4671
4672 /// We are trying to inject an anonymous member into the given scope;
4673 /// check if there's an existing declaration that can't be overloaded.
4674 ///
4675 /// \return true if this is a forbidden redeclaration
CheckAnonMemberRedeclaration(Sema & SemaRef,Scope * S,DeclContext * Owner,DeclarationName Name,SourceLocation NameLoc,bool IsUnion)4676 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4677 Scope *S,
4678 DeclContext *Owner,
4679 DeclarationName Name,
4680 SourceLocation NameLoc,
4681 bool IsUnion) {
4682 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4683 Sema::ForVisibleRedeclaration);
4684 if (!SemaRef.LookupName(R, S)) return false;
4685
4686 // Pick a representative declaration.
4687 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4688 assert(PrevDecl && "Expected a non-null Decl");
4689
4690 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4691 return false;
4692
4693 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4694 << IsUnion << Name;
4695 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4696
4697 return true;
4698 }
4699
4700 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4701 /// anonymous struct or union AnonRecord into the owning context Owner
4702 /// and scope S. This routine will be invoked just after we realize
4703 /// that an unnamed union or struct is actually an anonymous union or
4704 /// struct, e.g.,
4705 ///
4706 /// @code
4707 /// union {
4708 /// int i;
4709 /// float f;
4710 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4711 /// // f into the surrounding scope.x
4712 /// @endcode
4713 ///
4714 /// This routine is recursive, injecting the names of nested anonymous
4715 /// structs/unions into the owning context and scope as well.
4716 static bool
InjectAnonymousStructOrUnionMembers(Sema & SemaRef,Scope * S,DeclContext * Owner,RecordDecl * AnonRecord,AccessSpecifier AS,SmallVectorImpl<NamedDecl * > & Chaining)4717 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4718 RecordDecl *AnonRecord, AccessSpecifier AS,
4719 SmallVectorImpl<NamedDecl *> &Chaining) {
4720 bool Invalid = false;
4721
4722 // Look every FieldDecl and IndirectFieldDecl with a name.
4723 for (auto *D : AnonRecord->decls()) {
4724 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4725 cast<NamedDecl>(D)->getDeclName()) {
4726 ValueDecl *VD = cast<ValueDecl>(D);
4727 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4728 VD->getLocation(),
4729 AnonRecord->isUnion())) {
4730 // C++ [class.union]p2:
4731 // The names of the members of an anonymous union shall be
4732 // distinct from the names of any other entity in the
4733 // scope in which the anonymous union is declared.
4734 Invalid = true;
4735 } else {
4736 // C++ [class.union]p2:
4737 // For the purpose of name lookup, after the anonymous union
4738 // definition, the members of the anonymous union are
4739 // considered to have been defined in the scope in which the
4740 // anonymous union is declared.
4741 unsigned OldChainingSize = Chaining.size();
4742 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4743 Chaining.append(IF->chain_begin(), IF->chain_end());
4744 else
4745 Chaining.push_back(VD);
4746
4747 assert(Chaining.size() >= 2);
4748 NamedDecl **NamedChain =
4749 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4750 for (unsigned i = 0; i < Chaining.size(); i++)
4751 NamedChain[i] = Chaining[i];
4752
4753 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4754 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4755 VD->getType(), {NamedChain, Chaining.size()});
4756
4757 for (const auto *Attr : VD->attrs())
4758 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4759
4760 IndirectField->setAccess(AS);
4761 IndirectField->setImplicit();
4762 SemaRef.PushOnScopeChains(IndirectField, S);
4763
4764 // That includes picking up the appropriate access specifier.
4765 if (AS != AS_none) IndirectField->setAccess(AS);
4766
4767 Chaining.resize(OldChainingSize);
4768 }
4769 }
4770 }
4771
4772 return Invalid;
4773 }
4774
4775 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4776 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4777 /// illegal input values are mapped to SC_None.
4778 static StorageClass
StorageClassSpecToVarDeclStorageClass(const DeclSpec & DS)4779 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4780 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4781 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4782 "Parser allowed 'typedef' as storage class VarDecl.");
4783 switch (StorageClassSpec) {
4784 case DeclSpec::SCS_unspecified: return SC_None;
4785 case DeclSpec::SCS_extern:
4786 if (DS.isExternInLinkageSpec())
4787 return SC_None;
4788 return SC_Extern;
4789 case DeclSpec::SCS_static: return SC_Static;
4790 case DeclSpec::SCS_auto: return SC_Auto;
4791 case DeclSpec::SCS_register: return SC_Register;
4792 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4793 // Illegal SCSs map to None: error reporting is up to the caller.
4794 case DeclSpec::SCS_mutable: // Fall through.
4795 case DeclSpec::SCS_typedef: return SC_None;
4796 }
4797 llvm_unreachable("unknown storage class specifier");
4798 }
4799
findDefaultInitializer(const CXXRecordDecl * Record)4800 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4801 assert(Record->hasInClassInitializer());
4802
4803 for (const auto *I : Record->decls()) {
4804 const auto *FD = dyn_cast<FieldDecl>(I);
4805 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4806 FD = IFD->getAnonField();
4807 if (FD && FD->hasInClassInitializer())
4808 return FD->getLocation();
4809 }
4810
4811 llvm_unreachable("couldn't find in-class initializer");
4812 }
4813
checkDuplicateDefaultInit(Sema & S,CXXRecordDecl * Parent,SourceLocation DefaultInitLoc)4814 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4815 SourceLocation DefaultInitLoc) {
4816 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4817 return;
4818
4819 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4820 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4821 }
4822
checkDuplicateDefaultInit(Sema & S,CXXRecordDecl * Parent,CXXRecordDecl * AnonUnion)4823 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4824 CXXRecordDecl *AnonUnion) {
4825 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4826 return;
4827
4828 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4829 }
4830
4831 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4832 /// anonymous structure or union. Anonymous unions are a C++ feature
4833 /// (C++ [class.union]) and a C11 feature; anonymous structures
4834 /// are a C11 feature and GNU C++ extension.
BuildAnonymousStructOrUnion(Scope * S,DeclSpec & DS,AccessSpecifier AS,RecordDecl * Record,const PrintingPolicy & Policy)4835 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4836 AccessSpecifier AS,
4837 RecordDecl *Record,
4838 const PrintingPolicy &Policy) {
4839 DeclContext *Owner = Record->getDeclContext();
4840
4841 // Diagnose whether this anonymous struct/union is an extension.
4842 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4843 Diag(Record->getLocation(), diag::ext_anonymous_union);
4844 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4845 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4846 else if (!Record->isUnion() && !getLangOpts().C11)
4847 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4848
4849 // C and C++ require different kinds of checks for anonymous
4850 // structs/unions.
4851 bool Invalid = false;
4852 if (getLangOpts().CPlusPlus) {
4853 const char *PrevSpec = nullptr;
4854 if (Record->isUnion()) {
4855 // C++ [class.union]p6:
4856 // C++17 [class.union.anon]p2:
4857 // Anonymous unions declared in a named namespace or in the
4858 // global namespace shall be declared static.
4859 unsigned DiagID;
4860 DeclContext *OwnerScope = Owner->getRedeclContext();
4861 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4862 (OwnerScope->isTranslationUnit() ||
4863 (OwnerScope->isNamespace() &&
4864 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4865 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4866 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4867
4868 // Recover by adding 'static'.
4869 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4870 PrevSpec, DiagID, Policy);
4871 }
4872 // C++ [class.union]p6:
4873 // A storage class is not allowed in a declaration of an
4874 // anonymous union in a class scope.
4875 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4876 isa<RecordDecl>(Owner)) {
4877 Diag(DS.getStorageClassSpecLoc(),
4878 diag::err_anonymous_union_with_storage_spec)
4879 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4880
4881 // Recover by removing the storage specifier.
4882 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4883 SourceLocation(),
4884 PrevSpec, DiagID, Context.getPrintingPolicy());
4885 }
4886 }
4887
4888 // Ignore const/volatile/restrict qualifiers.
4889 if (DS.getTypeQualifiers()) {
4890 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4891 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4892 << Record->isUnion() << "const"
4893 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4894 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4895 Diag(DS.getVolatileSpecLoc(),
4896 diag::ext_anonymous_struct_union_qualified)
4897 << Record->isUnion() << "volatile"
4898 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4899 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4900 Diag(DS.getRestrictSpecLoc(),
4901 diag::ext_anonymous_struct_union_qualified)
4902 << Record->isUnion() << "restrict"
4903 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4904 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4905 Diag(DS.getAtomicSpecLoc(),
4906 diag::ext_anonymous_struct_union_qualified)
4907 << Record->isUnion() << "_Atomic"
4908 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4909 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4910 Diag(DS.getUnalignedSpecLoc(),
4911 diag::ext_anonymous_struct_union_qualified)
4912 << Record->isUnion() << "__unaligned"
4913 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4914
4915 DS.ClearTypeQualifiers();
4916 }
4917
4918 // C++ [class.union]p2:
4919 // The member-specification of an anonymous union shall only
4920 // define non-static data members. [Note: nested types and
4921 // functions cannot be declared within an anonymous union. ]
4922 for (auto *Mem : Record->decls()) {
4923 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4924 // C++ [class.union]p3:
4925 // An anonymous union shall not have private or protected
4926 // members (clause 11).
4927 assert(FD->getAccess() != AS_none);
4928 if (FD->getAccess() != AS_public) {
4929 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4930 << Record->isUnion() << (FD->getAccess() == AS_protected);
4931 Invalid = true;
4932 }
4933
4934 // C++ [class.union]p1
4935 // An object of a class with a non-trivial constructor, a non-trivial
4936 // copy constructor, a non-trivial destructor, or a non-trivial copy
4937 // assignment operator cannot be a member of a union, nor can an
4938 // array of such objects.
4939 if (CheckNontrivialField(FD))
4940 Invalid = true;
4941 } else if (Mem->isImplicit()) {
4942 // Any implicit members are fine.
4943 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4944 // This is a type that showed up in an
4945 // elaborated-type-specifier inside the anonymous struct or
4946 // union, but which actually declares a type outside of the
4947 // anonymous struct or union. It's okay.
4948 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4949 if (!MemRecord->isAnonymousStructOrUnion() &&
4950 MemRecord->getDeclName()) {
4951 // Visual C++ allows type definition in anonymous struct or union.
4952 if (getLangOpts().MicrosoftExt)
4953 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4954 << Record->isUnion();
4955 else {
4956 // This is a nested type declaration.
4957 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4958 << Record->isUnion();
4959 Invalid = true;
4960 }
4961 } else {
4962 // This is an anonymous type definition within another anonymous type.
4963 // This is a popular extension, provided by Plan9, MSVC and GCC, but
4964 // not part of standard C++.
4965 Diag(MemRecord->getLocation(),
4966 diag::ext_anonymous_record_with_anonymous_type)
4967 << Record->isUnion();
4968 }
4969 } else if (isa<AccessSpecDecl>(Mem)) {
4970 // Any access specifier is fine.
4971 } else if (isa<StaticAssertDecl>(Mem)) {
4972 // In C++1z, static_assert declarations are also fine.
4973 } else {
4974 // We have something that isn't a non-static data
4975 // member. Complain about it.
4976 unsigned DK = diag::err_anonymous_record_bad_member;
4977 if (isa<TypeDecl>(Mem))
4978 DK = diag::err_anonymous_record_with_type;
4979 else if (isa<FunctionDecl>(Mem))
4980 DK = diag::err_anonymous_record_with_function;
4981 else if (isa<VarDecl>(Mem))
4982 DK = diag::err_anonymous_record_with_static;
4983
4984 // Visual C++ allows type definition in anonymous struct or union.
4985 if (getLangOpts().MicrosoftExt &&
4986 DK == diag::err_anonymous_record_with_type)
4987 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4988 << Record->isUnion();
4989 else {
4990 Diag(Mem->getLocation(), DK) << Record->isUnion();
4991 Invalid = true;
4992 }
4993 }
4994 }
4995
4996 // C++11 [class.union]p8 (DR1460):
4997 // At most one variant member of a union may have a
4998 // brace-or-equal-initializer.
4999 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5000 Owner->isRecord())
5001 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5002 cast<CXXRecordDecl>(Record));
5003 }
5004
5005 if (!Record->isUnion() && !Owner->isRecord()) {
5006 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5007 << getLangOpts().CPlusPlus;
5008 Invalid = true;
5009 }
5010
5011 // C++ [dcl.dcl]p3:
5012 // [If there are no declarators], and except for the declaration of an
5013 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5014 // names into the program
5015 // C++ [class.mem]p2:
5016 // each such member-declaration shall either declare at least one member
5017 // name of the class or declare at least one unnamed bit-field
5018 //
5019 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5020 if (getLangOpts().CPlusPlus && Record->field_empty())
5021 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5022
5023 // Mock up a declarator.
5024 Declarator Dc(DS, DeclaratorContext::MemberContext);
5025 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5026 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5027
5028 // Create a declaration for this anonymous struct/union.
5029 NamedDecl *Anon = nullptr;
5030 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5031 Anon = FieldDecl::Create(
5032 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5033 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5034 /*BitWidth=*/nullptr, /*Mutable=*/false,
5035 /*InitStyle=*/ICIS_NoInit);
5036 Anon->setAccess(AS);
5037 ProcessDeclAttributes(S, Anon, Dc);
5038
5039 if (getLangOpts().CPlusPlus)
5040 FieldCollector->Add(cast<FieldDecl>(Anon));
5041 } else {
5042 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5043 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5044 if (SCSpec == DeclSpec::SCS_mutable) {
5045 // mutable can only appear on non-static class members, so it's always
5046 // an error here
5047 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5048 Invalid = true;
5049 SC = SC_None;
5050 }
5051
5052 assert(DS.getAttributes().empty() && "No attribute expected");
5053 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5054 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5055 Context.getTypeDeclType(Record), TInfo, SC);
5056
5057 // Default-initialize the implicit variable. This initialization will be
5058 // trivial in almost all cases, except if a union member has an in-class
5059 // initializer:
5060 // union { int n = 0; };
5061 ActOnUninitializedDecl(Anon);
5062 }
5063 Anon->setImplicit();
5064
5065 // Mark this as an anonymous struct/union type.
5066 Record->setAnonymousStructOrUnion(true);
5067
5068 // Add the anonymous struct/union object to the current
5069 // context. We'll be referencing this object when we refer to one of
5070 // its members.
5071 Owner->addDecl(Anon);
5072
5073 // Inject the members of the anonymous struct/union into the owning
5074 // context and into the identifier resolver chain for name lookup
5075 // purposes.
5076 SmallVector<NamedDecl*, 2> Chain;
5077 Chain.push_back(Anon);
5078
5079 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5080 Invalid = true;
5081
5082 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5083 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5084 MangleNumberingContext *MCtx;
5085 Decl *ManglingContextDecl;
5086 std::tie(MCtx, ManglingContextDecl) =
5087 getCurrentMangleNumberContext(NewVD->getDeclContext());
5088 if (MCtx) {
5089 Context.setManglingNumber(
5090 NewVD, MCtx->getManglingNumber(
5091 NewVD, getMSManglingNumber(getLangOpts(), S)));
5092 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5093 }
5094 }
5095 }
5096
5097 if (Invalid)
5098 Anon->setInvalidDecl();
5099
5100 return Anon;
5101 }
5102
5103 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5104 /// Microsoft C anonymous structure.
5105 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5106 /// Example:
5107 ///
5108 /// struct A { int a; };
5109 /// struct B { struct A; int b; };
5110 ///
5111 /// void foo() {
5112 /// B var;
5113 /// var.a = 3;
5114 /// }
5115 ///
BuildMicrosoftCAnonymousStruct(Scope * S,DeclSpec & DS,RecordDecl * Record)5116 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5117 RecordDecl *Record) {
5118 assert(Record && "expected a record!");
5119
5120 // Mock up a declarator.
5121 Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5122 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5123 assert(TInfo && "couldn't build declarator info for anonymous struct");
5124
5125 auto *ParentDecl = cast<RecordDecl>(CurContext);
5126 QualType RecTy = Context.getTypeDeclType(Record);
5127
5128 // Create a declaration for this anonymous struct.
5129 NamedDecl *Anon =
5130 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5131 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5132 /*BitWidth=*/nullptr, /*Mutable=*/false,
5133 /*InitStyle=*/ICIS_NoInit);
5134 Anon->setImplicit();
5135
5136 // Add the anonymous struct object to the current context.
5137 CurContext->addDecl(Anon);
5138
5139 // Inject the members of the anonymous struct into the current
5140 // context and into the identifier resolver chain for name lookup
5141 // purposes.
5142 SmallVector<NamedDecl*, 2> Chain;
5143 Chain.push_back(Anon);
5144
5145 RecordDecl *RecordDef = Record->getDefinition();
5146 if (RequireCompleteType(Anon->getLocation(), RecTy,
5147 diag::err_field_incomplete) ||
5148 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5149 AS_none, Chain)) {
5150 Anon->setInvalidDecl();
5151 ParentDecl->setInvalidDecl();
5152 }
5153
5154 return Anon;
5155 }
5156
5157 /// GetNameForDeclarator - Determine the full declaration name for the
5158 /// given Declarator.
GetNameForDeclarator(Declarator & D)5159 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5160 return GetNameFromUnqualifiedId(D.getName());
5161 }
5162
5163 /// Retrieves the declaration name from a parsed unqualified-id.
5164 DeclarationNameInfo
GetNameFromUnqualifiedId(const UnqualifiedId & Name)5165 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5166 DeclarationNameInfo NameInfo;
5167 NameInfo.setLoc(Name.StartLocation);
5168
5169 switch (Name.getKind()) {
5170
5171 case UnqualifiedIdKind::IK_ImplicitSelfParam:
5172 case UnqualifiedIdKind::IK_Identifier:
5173 NameInfo.setName(Name.Identifier);
5174 return NameInfo;
5175
5176 case UnqualifiedIdKind::IK_DeductionGuideName: {
5177 // C++ [temp.deduct.guide]p3:
5178 // The simple-template-id shall name a class template specialization.
5179 // The template-name shall be the same identifier as the template-name
5180 // of the simple-template-id.
5181 // These together intend to imply that the template-name shall name a
5182 // class template.
5183 // FIXME: template<typename T> struct X {};
5184 // template<typename T> using Y = X<T>;
5185 // Y(int) -> Y<int>;
5186 // satisfies these rules but does not name a class template.
5187 TemplateName TN = Name.TemplateName.get().get();
5188 auto *Template = TN.getAsTemplateDecl();
5189 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5190 Diag(Name.StartLocation,
5191 diag::err_deduction_guide_name_not_class_template)
5192 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5193 if (Template)
5194 Diag(Template->getLocation(), diag::note_template_decl_here);
5195 return DeclarationNameInfo();
5196 }
5197
5198 NameInfo.setName(
5199 Context.DeclarationNames.getCXXDeductionGuideName(Template));
5200 return NameInfo;
5201 }
5202
5203 case UnqualifiedIdKind::IK_OperatorFunctionId:
5204 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5205 Name.OperatorFunctionId.Operator));
5206 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5207 = Name.OperatorFunctionId.SymbolLocations[0];
5208 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5209 = Name.EndLocation.getRawEncoding();
5210 return NameInfo;
5211
5212 case UnqualifiedIdKind::IK_LiteralOperatorId:
5213 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5214 Name.Identifier));
5215 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5216 return NameInfo;
5217
5218 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5219 TypeSourceInfo *TInfo;
5220 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5221 if (Ty.isNull())
5222 return DeclarationNameInfo();
5223 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5224 Context.getCanonicalType(Ty)));
5225 NameInfo.setNamedTypeInfo(TInfo);
5226 return NameInfo;
5227 }
5228
5229 case UnqualifiedIdKind::IK_ConstructorName: {
5230 TypeSourceInfo *TInfo;
5231 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5232 if (Ty.isNull())
5233 return DeclarationNameInfo();
5234 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5235 Context.getCanonicalType(Ty)));
5236 NameInfo.setNamedTypeInfo(TInfo);
5237 return NameInfo;
5238 }
5239
5240 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5241 // In well-formed code, we can only have a constructor
5242 // template-id that refers to the current context, so go there
5243 // to find the actual type being constructed.
5244 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5245 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5246 return DeclarationNameInfo();
5247
5248 // Determine the type of the class being constructed.
5249 QualType CurClassType = Context.getTypeDeclType(CurClass);
5250
5251 // FIXME: Check two things: that the template-id names the same type as
5252 // CurClassType, and that the template-id does not occur when the name
5253 // was qualified.
5254
5255 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5256 Context.getCanonicalType(CurClassType)));
5257 // FIXME: should we retrieve TypeSourceInfo?
5258 NameInfo.setNamedTypeInfo(nullptr);
5259 return NameInfo;
5260 }
5261
5262 case UnqualifiedIdKind::IK_DestructorName: {
5263 TypeSourceInfo *TInfo;
5264 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5265 if (Ty.isNull())
5266 return DeclarationNameInfo();
5267 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5268 Context.getCanonicalType(Ty)));
5269 NameInfo.setNamedTypeInfo(TInfo);
5270 return NameInfo;
5271 }
5272
5273 case UnqualifiedIdKind::IK_TemplateId: {
5274 TemplateName TName = Name.TemplateId->Template.get();
5275 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5276 return Context.getNameForTemplate(TName, TNameLoc);
5277 }
5278
5279 } // switch (Name.getKind())
5280
5281 llvm_unreachable("Unknown name kind");
5282 }
5283
getCoreType(QualType Ty)5284 static QualType getCoreType(QualType Ty) {
5285 do {
5286 if (Ty->isPointerType() || Ty->isReferenceType())
5287 Ty = Ty->getPointeeType();
5288 else if (Ty->isArrayType())
5289 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5290 else
5291 return Ty.withoutLocalFastQualifiers();
5292 } while (true);
5293 }
5294
5295 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5296 /// and Definition have "nearly" matching parameters. This heuristic is
5297 /// used to improve diagnostics in the case where an out-of-line function
5298 /// definition doesn't match any declaration within the class or namespace.
5299 /// Also sets Params to the list of indices to the parameters that differ
5300 /// between the declaration and the definition. If hasSimilarParameters
5301 /// returns true and Params is empty, then all of the parameters match.
hasSimilarParameters(ASTContext & Context,FunctionDecl * Declaration,FunctionDecl * Definition,SmallVectorImpl<unsigned> & Params)5302 static bool hasSimilarParameters(ASTContext &Context,
5303 FunctionDecl *Declaration,
5304 FunctionDecl *Definition,
5305 SmallVectorImpl<unsigned> &Params) {
5306 Params.clear();
5307 if (Declaration->param_size() != Definition->param_size())
5308 return false;
5309 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5310 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5311 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5312
5313 // The parameter types are identical
5314 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5315 continue;
5316
5317 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5318 QualType DefParamBaseTy = getCoreType(DefParamTy);
5319 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5320 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5321
5322 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5323 (DeclTyName && DeclTyName == DefTyName))
5324 Params.push_back(Idx);
5325 else // The two parameters aren't even close
5326 return false;
5327 }
5328
5329 return true;
5330 }
5331
5332 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5333 /// declarator needs to be rebuilt in the current instantiation.
5334 /// Any bits of declarator which appear before the name are valid for
5335 /// consideration here. That's specifically the type in the decl spec
5336 /// and the base type in any member-pointer chunks.
RebuildDeclaratorInCurrentInstantiation(Sema & S,Declarator & D,DeclarationName Name)5337 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5338 DeclarationName Name) {
5339 // The types we specifically need to rebuild are:
5340 // - typenames, typeofs, and decltypes
5341 // - types which will become injected class names
5342 // Of course, we also need to rebuild any type referencing such a
5343 // type. It's safest to just say "dependent", but we call out a
5344 // few cases here.
5345
5346 DeclSpec &DS = D.getMutableDeclSpec();
5347 switch (DS.getTypeSpecType()) {
5348 case DeclSpec::TST_typename:
5349 case DeclSpec::TST_typeofType:
5350 case DeclSpec::TST_underlyingType:
5351 case DeclSpec::TST_atomic: {
5352 // Grab the type from the parser.
5353 TypeSourceInfo *TSI = nullptr;
5354 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5355 if (T.isNull() || !T->isDependentType()) break;
5356
5357 // Make sure there's a type source info. This isn't really much
5358 // of a waste; most dependent types should have type source info
5359 // attached already.
5360 if (!TSI)
5361 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5362
5363 // Rebuild the type in the current instantiation.
5364 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5365 if (!TSI) return true;
5366
5367 // Store the new type back in the decl spec.
5368 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5369 DS.UpdateTypeRep(LocType);
5370 break;
5371 }
5372
5373 case DeclSpec::TST_decltype:
5374 case DeclSpec::TST_typeofExpr: {
5375 Expr *E = DS.getRepAsExpr();
5376 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5377 if (Result.isInvalid()) return true;
5378 DS.UpdateExprRep(Result.get());
5379 break;
5380 }
5381
5382 default:
5383 // Nothing to do for these decl specs.
5384 break;
5385 }
5386
5387 // It doesn't matter what order we do this in.
5388 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5389 DeclaratorChunk &Chunk = D.getTypeObject(I);
5390
5391 // The only type information in the declarator which can come
5392 // before the declaration name is the base type of a member
5393 // pointer.
5394 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5395 continue;
5396
5397 // Rebuild the scope specifier in-place.
5398 CXXScopeSpec &SS = Chunk.Mem.Scope();
5399 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5400 return true;
5401 }
5402
5403 return false;
5404 }
5405
ActOnDeclarator(Scope * S,Declarator & D)5406 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5407 D.setFunctionDefinitionKind(FDK_Declaration);
5408 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5409
5410 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5411 Dcl && Dcl->getDeclContext()->isFileContext())
5412 Dcl->setTopLevelDeclInObjCContainer();
5413
5414 if (getLangOpts().OpenCL)
5415 setCurrentOpenCLExtensionForDecl(Dcl);
5416
5417 return Dcl;
5418 }
5419
5420 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5421 /// If T is the name of a class, then each of the following shall have a
5422 /// name different from T:
5423 /// - every static data member of class T;
5424 /// - every member function of class T
5425 /// - every member of class T that is itself a type;
5426 /// \returns true if the declaration name violates these rules.
DiagnoseClassNameShadow(DeclContext * DC,DeclarationNameInfo NameInfo)5427 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5428 DeclarationNameInfo NameInfo) {
5429 DeclarationName Name = NameInfo.getName();
5430
5431 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5432 while (Record && Record->isAnonymousStructOrUnion())
5433 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5434 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5435 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5436 return true;
5437 }
5438
5439 return false;
5440 }
5441
5442 /// Diagnose a declaration whose declarator-id has the given
5443 /// nested-name-specifier.
5444 ///
5445 /// \param SS The nested-name-specifier of the declarator-id.
5446 ///
5447 /// \param DC The declaration context to which the nested-name-specifier
5448 /// resolves.
5449 ///
5450 /// \param Name The name of the entity being declared.
5451 ///
5452 /// \param Loc The location of the name of the entity being declared.
5453 ///
5454 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5455 /// we're declaring an explicit / partial specialization / instantiation.
5456 ///
5457 /// \returns true if we cannot safely recover from this error, false otherwise.
diagnoseQualifiedDeclaration(CXXScopeSpec & SS,DeclContext * DC,DeclarationName Name,SourceLocation Loc,bool IsTemplateId)5458 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5459 DeclarationName Name,
5460 SourceLocation Loc, bool IsTemplateId) {
5461 DeclContext *Cur = CurContext;
5462 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5463 Cur = Cur->getParent();
5464
5465 // If the user provided a superfluous scope specifier that refers back to the
5466 // class in which the entity is already declared, diagnose and ignore it.
5467 //
5468 // class X {
5469 // void X::f();
5470 // };
5471 //
5472 // Note, it was once ill-formed to give redundant qualification in all
5473 // contexts, but that rule was removed by DR482.
5474 if (Cur->Equals(DC)) {
5475 if (Cur->isRecord()) {
5476 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5477 : diag::err_member_extra_qualification)
5478 << Name << FixItHint::CreateRemoval(SS.getRange());
5479 SS.clear();
5480 } else {
5481 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5482 }
5483 return false;
5484 }
5485
5486 // Check whether the qualifying scope encloses the scope of the original
5487 // declaration. For a template-id, we perform the checks in
5488 // CheckTemplateSpecializationScope.
5489 if (!Cur->Encloses(DC) && !IsTemplateId) {
5490 if (Cur->isRecord())
5491 Diag(Loc, diag::err_member_qualification)
5492 << Name << SS.getRange();
5493 else if (isa<TranslationUnitDecl>(DC))
5494 Diag(Loc, diag::err_invalid_declarator_global_scope)
5495 << Name << SS.getRange();
5496 else if (isa<FunctionDecl>(Cur))
5497 Diag(Loc, diag::err_invalid_declarator_in_function)
5498 << Name << SS.getRange();
5499 else if (isa<BlockDecl>(Cur))
5500 Diag(Loc, diag::err_invalid_declarator_in_block)
5501 << Name << SS.getRange();
5502 else
5503 Diag(Loc, diag::err_invalid_declarator_scope)
5504 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5505
5506 return true;
5507 }
5508
5509 if (Cur->isRecord()) {
5510 // Cannot qualify members within a class.
5511 Diag(Loc, diag::err_member_qualification)
5512 << Name << SS.getRange();
5513 SS.clear();
5514
5515 // C++ constructors and destructors with incorrect scopes can break
5516 // our AST invariants by having the wrong underlying types. If
5517 // that's the case, then drop this declaration entirely.
5518 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5519 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5520 !Context.hasSameType(Name.getCXXNameType(),
5521 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5522 return true;
5523
5524 return false;
5525 }
5526
5527 // C++11 [dcl.meaning]p1:
5528 // [...] "The nested-name-specifier of the qualified declarator-id shall
5529 // not begin with a decltype-specifer"
5530 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5531 while (SpecLoc.getPrefix())
5532 SpecLoc = SpecLoc.getPrefix();
5533 if (dyn_cast_or_null<DecltypeType>(
5534 SpecLoc.getNestedNameSpecifier()->getAsType()))
5535 Diag(Loc, diag::err_decltype_in_declarator)
5536 << SpecLoc.getTypeLoc().getSourceRange();
5537
5538 return false;
5539 }
5540
HandleDeclarator(Scope * S,Declarator & D,MultiTemplateParamsArg TemplateParamLists)5541 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5542 MultiTemplateParamsArg TemplateParamLists) {
5543 // TODO: consider using NameInfo for diagnostic.
5544 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5545 DeclarationName Name = NameInfo.getName();
5546
5547 // All of these full declarators require an identifier. If it doesn't have
5548 // one, the ParsedFreeStandingDeclSpec action should be used.
5549 if (D.isDecompositionDeclarator()) {
5550 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5551 } else if (!Name) {
5552 if (!D.isInvalidType()) // Reject this if we think it is valid.
5553 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5554 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5555 return nullptr;
5556 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5557 return nullptr;
5558
5559 // The scope passed in may not be a decl scope. Zip up the scope tree until
5560 // we find one that is.
5561 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5562 (S->getFlags() & Scope::TemplateParamScope) != 0)
5563 S = S->getParent();
5564
5565 DeclContext *DC = CurContext;
5566 if (D.getCXXScopeSpec().isInvalid())
5567 D.setInvalidType();
5568 else if (D.getCXXScopeSpec().isSet()) {
5569 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5570 UPPC_DeclarationQualifier))
5571 return nullptr;
5572
5573 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5574 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5575 if (!DC || isa<EnumDecl>(DC)) {
5576 // If we could not compute the declaration context, it's because the
5577 // declaration context is dependent but does not refer to a class,
5578 // class template, or class template partial specialization. Complain
5579 // and return early, to avoid the coming semantic disaster.
5580 Diag(D.getIdentifierLoc(),
5581 diag::err_template_qualified_declarator_no_match)
5582 << D.getCXXScopeSpec().getScopeRep()
5583 << D.getCXXScopeSpec().getRange();
5584 return nullptr;
5585 }
5586 bool IsDependentContext = DC->isDependentContext();
5587
5588 if (!IsDependentContext &&
5589 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5590 return nullptr;
5591
5592 // If a class is incomplete, do not parse entities inside it.
5593 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5594 Diag(D.getIdentifierLoc(),
5595 diag::err_member_def_undefined_record)
5596 << Name << DC << D.getCXXScopeSpec().getRange();
5597 return nullptr;
5598 }
5599 if (!D.getDeclSpec().isFriendSpecified()) {
5600 if (diagnoseQualifiedDeclaration(
5601 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5602 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5603 if (DC->isRecord())
5604 return nullptr;
5605
5606 D.setInvalidType();
5607 }
5608 }
5609
5610 // Check whether we need to rebuild the type of the given
5611 // declaration in the current instantiation.
5612 if (EnteringContext && IsDependentContext &&
5613 TemplateParamLists.size() != 0) {
5614 ContextRAII SavedContext(*this, DC);
5615 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5616 D.setInvalidType();
5617 }
5618 }
5619
5620 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5621 QualType R = TInfo->getType();
5622
5623 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5624 UPPC_DeclarationType))
5625 D.setInvalidType();
5626
5627 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5628 forRedeclarationInCurContext());
5629
5630 // See if this is a redefinition of a variable in the same scope.
5631 if (!D.getCXXScopeSpec().isSet()) {
5632 bool IsLinkageLookup = false;
5633 bool CreateBuiltins = false;
5634
5635 // If the declaration we're planning to build will be a function
5636 // or object with linkage, then look for another declaration with
5637 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5638 //
5639 // If the declaration we're planning to build will be declared with
5640 // external linkage in the translation unit, create any builtin with
5641 // the same name.
5642 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5643 /* Do nothing*/;
5644 else if (CurContext->isFunctionOrMethod() &&
5645 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5646 R->isFunctionType())) {
5647 IsLinkageLookup = true;
5648 CreateBuiltins =
5649 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5650 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5651 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5652 CreateBuiltins = true;
5653
5654 if (IsLinkageLookup) {
5655 Previous.clear(LookupRedeclarationWithLinkage);
5656 Previous.setRedeclarationKind(ForExternalRedeclaration);
5657 }
5658
5659 LookupName(Previous, S, CreateBuiltins);
5660 } else { // Something like "int foo::x;"
5661 LookupQualifiedName(Previous, DC);
5662
5663 // C++ [dcl.meaning]p1:
5664 // When the declarator-id is qualified, the declaration shall refer to a
5665 // previously declared member of the class or namespace to which the
5666 // qualifier refers (or, in the case of a namespace, of an element of the
5667 // inline namespace set of that namespace (7.3.1)) or to a specialization
5668 // thereof; [...]
5669 //
5670 // Note that we already checked the context above, and that we do not have
5671 // enough information to make sure that Previous contains the declaration
5672 // we want to match. For example, given:
5673 //
5674 // class X {
5675 // void f();
5676 // void f(float);
5677 // };
5678 //
5679 // void X::f(int) { } // ill-formed
5680 //
5681 // In this case, Previous will point to the overload set
5682 // containing the two f's declared in X, but neither of them
5683 // matches.
5684
5685 // C++ [dcl.meaning]p1:
5686 // [...] the member shall not merely have been introduced by a
5687 // using-declaration in the scope of the class or namespace nominated by
5688 // the nested-name-specifier of the declarator-id.
5689 RemoveUsingDecls(Previous);
5690 }
5691
5692 if (Previous.isSingleResult() &&
5693 Previous.getFoundDecl()->isTemplateParameter()) {
5694 // Maybe we will complain about the shadowed template parameter.
5695 if (!D.isInvalidType())
5696 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5697 Previous.getFoundDecl());
5698
5699 // Just pretend that we didn't see the previous declaration.
5700 Previous.clear();
5701 }
5702
5703 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5704 // Forget that the previous declaration is the injected-class-name.
5705 Previous.clear();
5706
5707 // In C++, the previous declaration we find might be a tag type
5708 // (class or enum). In this case, the new declaration will hide the
5709 // tag type. Note that this applies to functions, function templates, and
5710 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5711 if (Previous.isSingleTagDecl() &&
5712 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5713 (TemplateParamLists.size() == 0 || R->isFunctionType()))
5714 Previous.clear();
5715
5716 // Check that there are no default arguments other than in the parameters
5717 // of a function declaration (C++ only).
5718 if (getLangOpts().CPlusPlus)
5719 CheckExtraCXXDefaultArguments(D);
5720
5721 NamedDecl *New;
5722
5723 bool AddToScope = true;
5724 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5725 if (TemplateParamLists.size()) {
5726 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5727 return nullptr;
5728 }
5729
5730 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5731 } else if (R->isFunctionType()) {
5732 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5733 TemplateParamLists,
5734 AddToScope);
5735 } else {
5736 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5737 AddToScope);
5738 }
5739
5740 if (!New)
5741 return nullptr;
5742
5743 // If this has an identifier and is not a function template specialization,
5744 // add it to the scope stack.
5745 if (New->getDeclName() && AddToScope)
5746 PushOnScopeChains(New, S);
5747
5748 if (isInOpenMPDeclareTargetContext())
5749 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5750
5751 return New;
5752 }
5753
5754 /// Helper method to turn variable array types into constant array
5755 /// types in certain situations which would otherwise be errors (for
5756 /// GCC compatibility).
TryToFixInvalidVariablyModifiedType(QualType T,ASTContext & Context,bool & SizeIsNegative,llvm::APSInt & Oversized)5757 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5758 ASTContext &Context,
5759 bool &SizeIsNegative,
5760 llvm::APSInt &Oversized) {
5761 // This method tries to turn a variable array into a constant
5762 // array even when the size isn't an ICE. This is necessary
5763 // for compatibility with code that depends on gcc's buggy
5764 // constant expression folding, like struct {char x[(int)(char*)2];}
5765 SizeIsNegative = false;
5766 Oversized = 0;
5767
5768 if (T->isDependentType())
5769 return QualType();
5770
5771 QualifierCollector Qs;
5772 const Type *Ty = Qs.strip(T);
5773
5774 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5775 QualType Pointee = PTy->getPointeeType();
5776 QualType FixedType =
5777 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5778 Oversized);
5779 if (FixedType.isNull()) return FixedType;
5780 FixedType = Context.getPointerType(FixedType);
5781 return Qs.apply(Context, FixedType);
5782 }
5783 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5784 QualType Inner = PTy->getInnerType();
5785 QualType FixedType =
5786 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5787 Oversized);
5788 if (FixedType.isNull()) return FixedType;
5789 FixedType = Context.getParenType(FixedType);
5790 return Qs.apply(Context, FixedType);
5791 }
5792
5793 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5794 if (!VLATy)
5795 return QualType();
5796 // FIXME: We should probably handle this case
5797 if (VLATy->getElementType()->isVariablyModifiedType())
5798 return QualType();
5799
5800 Expr::EvalResult Result;
5801 if (!VLATy->getSizeExpr() ||
5802 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5803 return QualType();
5804
5805 llvm::APSInt Res = Result.Val.getInt();
5806
5807 // Check whether the array size is negative.
5808 if (Res.isSigned() && Res.isNegative()) {
5809 SizeIsNegative = true;
5810 return QualType();
5811 }
5812
5813 // Check whether the array is too large to be addressed.
5814 unsigned ActiveSizeBits
5815 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5816 Res);
5817 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5818 Oversized = Res;
5819 return QualType();
5820 }
5821
5822 return Context.getConstantArrayType(
5823 VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5824 }
5825
5826 static void
FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL,TypeLoc DstTL)5827 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5828 SrcTL = SrcTL.getUnqualifiedLoc();
5829 DstTL = DstTL.getUnqualifiedLoc();
5830 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5831 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5832 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5833 DstPTL.getPointeeLoc());
5834 DstPTL.setStarLoc(SrcPTL.getStarLoc());
5835 return;
5836 }
5837 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5838 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5839 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5840 DstPTL.getInnerLoc());
5841 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5842 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5843 return;
5844 }
5845 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5846 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5847 TypeLoc SrcElemTL = SrcATL.getElementLoc();
5848 TypeLoc DstElemTL = DstATL.getElementLoc();
5849 DstElemTL.initializeFullCopy(SrcElemTL);
5850 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5851 DstATL.setSizeExpr(SrcATL.getSizeExpr());
5852 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5853 }
5854
5855 /// Helper method to turn variable array types into constant array
5856 /// types in certain situations which would otherwise be errors (for
5857 /// GCC compatibility).
5858 static TypeSourceInfo*
TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo * TInfo,ASTContext & Context,bool & SizeIsNegative,llvm::APSInt & Oversized)5859 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5860 ASTContext &Context,
5861 bool &SizeIsNegative,
5862 llvm::APSInt &Oversized) {
5863 QualType FixedTy
5864 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5865 SizeIsNegative, Oversized);
5866 if (FixedTy.isNull())
5867 return nullptr;
5868 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5869 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5870 FixedTInfo->getTypeLoc());
5871 return FixedTInfo;
5872 }
5873
5874 /// Register the given locally-scoped extern "C" declaration so
5875 /// that it can be found later for redeclarations. We include any extern "C"
5876 /// declaration that is not visible in the translation unit here, not just
5877 /// function-scope declarations.
5878 void
RegisterLocallyScopedExternCDecl(NamedDecl * ND,Scope * S)5879 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5880 if (!getLangOpts().CPlusPlus &&
5881 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5882 // Don't need to track declarations in the TU in C.
5883 return;
5884
5885 // Note that we have a locally-scoped external with this name.
5886 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5887 }
5888
findLocallyScopedExternCDecl(DeclarationName Name)5889 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5890 // FIXME: We can have multiple results via __attribute__((overloadable)).
5891 auto Result = Context.getExternCContextDecl()->lookup(Name);
5892 return Result.empty() ? nullptr : *Result.begin();
5893 }
5894
5895 /// Diagnose function specifiers on a declaration of an identifier that
5896 /// does not identify a function.
DiagnoseFunctionSpecifiers(const DeclSpec & DS)5897 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5898 // FIXME: We should probably indicate the identifier in question to avoid
5899 // confusion for constructs like "virtual int a(), b;"
5900 if (DS.isVirtualSpecified())
5901 Diag(DS.getVirtualSpecLoc(),
5902 diag::err_virtual_non_function);
5903
5904 if (DS.hasExplicitSpecifier())
5905 Diag(DS.getExplicitSpecLoc(),
5906 diag::err_explicit_non_function);
5907
5908 if (DS.isNoreturnSpecified())
5909 Diag(DS.getNoreturnSpecLoc(),
5910 diag::err_noreturn_non_function);
5911 }
5912
5913 NamedDecl*
ActOnTypedefDeclarator(Scope * S,Declarator & D,DeclContext * DC,TypeSourceInfo * TInfo,LookupResult & Previous)5914 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5915 TypeSourceInfo *TInfo, LookupResult &Previous) {
5916 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5917 if (D.getCXXScopeSpec().isSet()) {
5918 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5919 << D.getCXXScopeSpec().getRange();
5920 D.setInvalidType();
5921 // Pretend we didn't see the scope specifier.
5922 DC = CurContext;
5923 Previous.clear();
5924 }
5925
5926 DiagnoseFunctionSpecifiers(D.getDeclSpec());
5927
5928 if (D.getDeclSpec().isInlineSpecified())
5929 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5930 << getLangOpts().CPlusPlus17;
5931 if (D.getDeclSpec().hasConstexprSpecifier())
5932 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5933 << 1 << D.getDeclSpec().getConstexprSpecifier();
5934
5935 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5936 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5937 Diag(D.getName().StartLocation,
5938 diag::err_deduction_guide_invalid_specifier)
5939 << "typedef";
5940 else
5941 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5942 << D.getName().getSourceRange();
5943 return nullptr;
5944 }
5945
5946 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5947 if (!NewTD) return nullptr;
5948
5949 // Handle attributes prior to checking for duplicates in MergeVarDecl
5950 ProcessDeclAttributes(S, NewTD, D);
5951
5952 CheckTypedefForVariablyModifiedType(S, NewTD);
5953
5954 bool Redeclaration = D.isRedeclaration();
5955 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5956 D.setRedeclaration(Redeclaration);
5957 return ND;
5958 }
5959
5960 void
CheckTypedefForVariablyModifiedType(Scope * S,TypedefNameDecl * NewTD)5961 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5962 // C99 6.7.7p2: If a typedef name specifies a variably modified type
5963 // then it shall have block scope.
5964 // Note that variably modified types must be fixed before merging the decl so
5965 // that redeclarations will match.
5966 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5967 QualType T = TInfo->getType();
5968 if (T->isVariablyModifiedType()) {
5969 setFunctionHasBranchProtectedScope();
5970
5971 if (S->getFnParent() == nullptr) {
5972 bool SizeIsNegative;
5973 llvm::APSInt Oversized;
5974 TypeSourceInfo *FixedTInfo =
5975 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5976 SizeIsNegative,
5977 Oversized);
5978 if (FixedTInfo) {
5979 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5980 NewTD->setTypeSourceInfo(FixedTInfo);
5981 } else {
5982 if (SizeIsNegative)
5983 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5984 else if (T->isVariableArrayType())
5985 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5986 else if (Oversized.getBoolValue())
5987 Diag(NewTD->getLocation(), diag::err_array_too_large)
5988 << Oversized.toString(10);
5989 else
5990 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5991 NewTD->setInvalidDecl();
5992 }
5993 }
5994 }
5995 }
5996
5997 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5998 /// declares a typedef-name, either using the 'typedef' type specifier or via
5999 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6000 NamedDecl*
ActOnTypedefNameDecl(Scope * S,DeclContext * DC,TypedefNameDecl * NewTD,LookupResult & Previous,bool & Redeclaration)6001 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6002 LookupResult &Previous, bool &Redeclaration) {
6003
6004 // Find the shadowed declaration before filtering for scope.
6005 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6006
6007 // Merge the decl with the existing one if appropriate. If the decl is
6008 // in an outer scope, it isn't the same thing.
6009 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6010 /*AllowInlineNamespace*/false);
6011 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6012 if (!Previous.empty()) {
6013 Redeclaration = true;
6014 MergeTypedefNameDecl(S, NewTD, Previous);
6015 } else {
6016 inferGslPointerAttribute(NewTD);
6017 }
6018
6019 if (ShadowedDecl && !Redeclaration)
6020 CheckShadow(NewTD, ShadowedDecl, Previous);
6021
6022 // If this is the C FILE type, notify the AST context.
6023 if (IdentifierInfo *II = NewTD->getIdentifier())
6024 if (!NewTD->isInvalidDecl() &&
6025 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6026 if (II->isStr("FILE"))
6027 Context.setFILEDecl(NewTD);
6028 else if (II->isStr("jmp_buf"))
6029 Context.setjmp_bufDecl(NewTD);
6030 else if (II->isStr("sigjmp_buf"))
6031 Context.setsigjmp_bufDecl(NewTD);
6032 else if (II->isStr("ucontext_t"))
6033 Context.setucontext_tDecl(NewTD);
6034 }
6035
6036 return NewTD;
6037 }
6038
6039 /// Determines whether the given declaration is an out-of-scope
6040 /// previous declaration.
6041 ///
6042 /// This routine should be invoked when name lookup has found a
6043 /// previous declaration (PrevDecl) that is not in the scope where a
6044 /// new declaration by the same name is being introduced. If the new
6045 /// declaration occurs in a local scope, previous declarations with
6046 /// linkage may still be considered previous declarations (C99
6047 /// 6.2.2p4-5, C++ [basic.link]p6).
6048 ///
6049 /// \param PrevDecl the previous declaration found by name
6050 /// lookup
6051 ///
6052 /// \param DC the context in which the new declaration is being
6053 /// declared.
6054 ///
6055 /// \returns true if PrevDecl is an out-of-scope previous declaration
6056 /// for a new delcaration with the same name.
6057 static bool
isOutOfScopePreviousDeclaration(NamedDecl * PrevDecl,DeclContext * DC,ASTContext & Context)6058 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6059 ASTContext &Context) {
6060 if (!PrevDecl)
6061 return false;
6062
6063 if (!PrevDecl->hasLinkage())
6064 return false;
6065
6066 if (Context.getLangOpts().CPlusPlus) {
6067 // C++ [basic.link]p6:
6068 // If there is a visible declaration of an entity with linkage
6069 // having the same name and type, ignoring entities declared
6070 // outside the innermost enclosing namespace scope, the block
6071 // scope declaration declares that same entity and receives the
6072 // linkage of the previous declaration.
6073 DeclContext *OuterContext = DC->getRedeclContext();
6074 if (!OuterContext->isFunctionOrMethod())
6075 // This rule only applies to block-scope declarations.
6076 return false;
6077
6078 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6079 if (PrevOuterContext->isRecord())
6080 // We found a member function: ignore it.
6081 return false;
6082
6083 // Find the innermost enclosing namespace for the new and
6084 // previous declarations.
6085 OuterContext = OuterContext->getEnclosingNamespaceContext();
6086 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6087
6088 // The previous declaration is in a different namespace, so it
6089 // isn't the same function.
6090 if (!OuterContext->Equals(PrevOuterContext))
6091 return false;
6092 }
6093
6094 return true;
6095 }
6096
SetNestedNameSpecifier(Sema & S,DeclaratorDecl * DD,Declarator & D)6097 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6098 CXXScopeSpec &SS = D.getCXXScopeSpec();
6099 if (!SS.isSet()) return;
6100 DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6101 }
6102
inferObjCARCLifetime(ValueDecl * decl)6103 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6104 QualType type = decl->getType();
6105 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6106 if (lifetime == Qualifiers::OCL_Autoreleasing) {
6107 // Various kinds of declaration aren't allowed to be __autoreleasing.
6108 unsigned kind = -1U;
6109 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6110 if (var->hasAttr<BlocksAttr>())
6111 kind = 0; // __block
6112 else if (!var->hasLocalStorage())
6113 kind = 1; // global
6114 } else if (isa<ObjCIvarDecl>(decl)) {
6115 kind = 3; // ivar
6116 } else if (isa<FieldDecl>(decl)) {
6117 kind = 2; // field
6118 }
6119
6120 if (kind != -1U) {
6121 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6122 << kind;
6123 }
6124 } else if (lifetime == Qualifiers::OCL_None) {
6125 // Try to infer lifetime.
6126 if (!type->isObjCLifetimeType())
6127 return false;
6128
6129 lifetime = type->getObjCARCImplicitLifetime();
6130 type = Context.getLifetimeQualifiedType(type, lifetime);
6131 decl->setType(type);
6132 }
6133
6134 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6135 // Thread-local variables cannot have lifetime.
6136 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6137 var->getTLSKind()) {
6138 Diag(var->getLocation(), diag::err_arc_thread_ownership)
6139 << var->getType();
6140 return true;
6141 }
6142 }
6143
6144 return false;
6145 }
6146
deduceOpenCLAddressSpace(ValueDecl * Decl)6147 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6148 if (Decl->getType().hasAddressSpace())
6149 return;
6150 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6151 QualType Type = Var->getType();
6152 if (Type->isSamplerT() || Type->isVoidType())
6153 return;
6154 LangAS ImplAS = LangAS::opencl_private;
6155 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6156 Var->hasGlobalStorage())
6157 ImplAS = LangAS::opencl_global;
6158 // If the original type from a decayed type is an array type and that array
6159 // type has no address space yet, deduce it now.
6160 if (auto DT = dyn_cast<DecayedType>(Type)) {
6161 auto OrigTy = DT->getOriginalType();
6162 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6163 // Add the address space to the original array type and then propagate
6164 // that to the element type through `getAsArrayType`.
6165 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6166 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6167 // Re-generate the decayed type.
6168 Type = Context.getDecayedType(OrigTy);
6169 }
6170 }
6171 Type = Context.getAddrSpaceQualType(Type, ImplAS);
6172 // Apply any qualifiers (including address space) from the array type to
6173 // the element type. This implements C99 6.7.3p8: "If the specification of
6174 // an array type includes any type qualifiers, the element type is so
6175 // qualified, not the array type."
6176 if (Type->isArrayType())
6177 Type = QualType(Context.getAsArrayType(Type), 0);
6178 Decl->setType(Type);
6179 }
6180 }
6181
checkAttributesAfterMerging(Sema & S,NamedDecl & ND)6182 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6183 // Ensure that an auto decl is deduced otherwise the checks below might cache
6184 // the wrong linkage.
6185 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6186
6187 // 'weak' only applies to declarations with external linkage.
6188 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6189 if (!ND.isExternallyVisible()) {
6190 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6191 ND.dropAttr<WeakAttr>();
6192 }
6193 }
6194 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6195 if (ND.isExternallyVisible()) {
6196 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6197 ND.dropAttr<WeakRefAttr>();
6198 ND.dropAttr<AliasAttr>();
6199 }
6200 }
6201
6202 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6203 if (VD->hasInit()) {
6204 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6205 assert(VD->isThisDeclarationADefinition() &&
6206 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6207 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6208 VD->dropAttr<AliasAttr>();
6209 }
6210 }
6211 }
6212
6213 // 'selectany' only applies to externally visible variable declarations.
6214 // It does not apply to functions.
6215 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6216 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6217 S.Diag(Attr->getLocation(),
6218 diag::err_attribute_selectany_non_extern_data);
6219 ND.dropAttr<SelectAnyAttr>();
6220 }
6221 }
6222
6223 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6224 auto *VD = dyn_cast<VarDecl>(&ND);
6225 bool IsAnonymousNS = false;
6226 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6227 if (VD) {
6228 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6229 while (NS && !IsAnonymousNS) {
6230 IsAnonymousNS = NS->isAnonymousNamespace();
6231 NS = dyn_cast<NamespaceDecl>(NS->getParent());
6232 }
6233 }
6234 // dll attributes require external linkage. Static locals may have external
6235 // linkage but still cannot be explicitly imported or exported.
6236 // In Microsoft mode, a variable defined in anonymous namespace must have
6237 // external linkage in order to be exported.
6238 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6239 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6240 (!AnonNSInMicrosoftMode &&
6241 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6242 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6243 << &ND << Attr;
6244 ND.setInvalidDecl();
6245 }
6246 }
6247
6248 // Virtual functions cannot be marked as 'notail'.
6249 if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6250 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6251 if (MD->isVirtual()) {
6252 S.Diag(ND.getLocation(),
6253 diag::err_invalid_attribute_on_virtual_function)
6254 << Attr;
6255 ND.dropAttr<NotTailCalledAttr>();
6256 }
6257
6258 // Check the attributes on the function type, if any.
6259 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6260 // Don't declare this variable in the second operand of the for-statement;
6261 // GCC miscompiles that by ending its lifetime before evaluating the
6262 // third operand. See gcc.gnu.org/PR86769.
6263 AttributedTypeLoc ATL;
6264 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6265 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6266 TL = ATL.getModifiedLoc()) {
6267 // The [[lifetimebound]] attribute can be applied to the implicit object
6268 // parameter of a non-static member function (other than a ctor or dtor)
6269 // by applying it to the function type.
6270 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6271 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6272 if (!MD || MD->isStatic()) {
6273 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6274 << !MD << A->getRange();
6275 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6276 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6277 << isa<CXXDestructorDecl>(MD) << A->getRange();
6278 }
6279 }
6280 }
6281 }
6282 }
6283
checkDLLAttributeRedeclaration(Sema & S,NamedDecl * OldDecl,NamedDecl * NewDecl,bool IsSpecialization,bool IsDefinition)6284 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6285 NamedDecl *NewDecl,
6286 bool IsSpecialization,
6287 bool IsDefinition) {
6288 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6289 return;
6290
6291 bool IsTemplate = false;
6292 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6293 OldDecl = OldTD->getTemplatedDecl();
6294 IsTemplate = true;
6295 if (!IsSpecialization)
6296 IsDefinition = false;
6297 }
6298 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6299 NewDecl = NewTD->getTemplatedDecl();
6300 IsTemplate = true;
6301 }
6302
6303 if (!OldDecl || !NewDecl)
6304 return;
6305
6306 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6307 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6308 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6309 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6310
6311 // dllimport and dllexport are inheritable attributes so we have to exclude
6312 // inherited attribute instances.
6313 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6314 (NewExportAttr && !NewExportAttr->isInherited());
6315
6316 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6317 // the only exception being explicit specializations.
6318 // Implicitly generated declarations are also excluded for now because there
6319 // is no other way to switch these to use dllimport or dllexport.
6320 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6321
6322 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6323 // Allow with a warning for free functions and global variables.
6324 bool JustWarn = false;
6325 if (!OldDecl->isCXXClassMember()) {
6326 auto *VD = dyn_cast<VarDecl>(OldDecl);
6327 if (VD && !VD->getDescribedVarTemplate())
6328 JustWarn = true;
6329 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6330 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6331 JustWarn = true;
6332 }
6333
6334 // We cannot change a declaration that's been used because IR has already
6335 // been emitted. Dllimported functions will still work though (modulo
6336 // address equality) as they can use the thunk.
6337 if (OldDecl->isUsed())
6338 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6339 JustWarn = false;
6340
6341 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6342 : diag::err_attribute_dll_redeclaration;
6343 S.Diag(NewDecl->getLocation(), DiagID)
6344 << NewDecl
6345 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6346 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6347 if (!JustWarn) {
6348 NewDecl->setInvalidDecl();
6349 return;
6350 }
6351 }
6352
6353 // A redeclaration is not allowed to drop a dllimport attribute, the only
6354 // exceptions being inline function definitions (except for function
6355 // templates), local extern declarations, qualified friend declarations or
6356 // special MSVC extension: in the last case, the declaration is treated as if
6357 // it were marked dllexport.
6358 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6359 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6360 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6361 // Ignore static data because out-of-line definitions are diagnosed
6362 // separately.
6363 IsStaticDataMember = VD->isStaticDataMember();
6364 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6365 VarDecl::DeclarationOnly;
6366 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6367 IsInline = FD->isInlined();
6368 IsQualifiedFriend = FD->getQualifier() &&
6369 FD->getFriendObjectKind() == Decl::FOK_Declared;
6370 }
6371
6372 if (OldImportAttr && !HasNewAttr &&
6373 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6374 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6375 if (IsMicrosoft && IsDefinition) {
6376 S.Diag(NewDecl->getLocation(),
6377 diag::warn_redeclaration_without_import_attribute)
6378 << NewDecl;
6379 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6380 NewDecl->dropAttr<DLLImportAttr>();
6381 NewDecl->addAttr(
6382 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6383 } else {
6384 S.Diag(NewDecl->getLocation(),
6385 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6386 << NewDecl << OldImportAttr;
6387 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6388 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6389 OldDecl->dropAttr<DLLImportAttr>();
6390 NewDecl->dropAttr<DLLImportAttr>();
6391 }
6392 } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6393 // In MinGW, seeing a function declared inline drops the dllimport
6394 // attribute.
6395 OldDecl->dropAttr<DLLImportAttr>();
6396 NewDecl->dropAttr<DLLImportAttr>();
6397 S.Diag(NewDecl->getLocation(),
6398 diag::warn_dllimport_dropped_from_inline_function)
6399 << NewDecl << OldImportAttr;
6400 }
6401
6402 // A specialization of a class template member function is processed here
6403 // since it's a redeclaration. If the parent class is dllexport, the
6404 // specialization inherits that attribute. This doesn't happen automatically
6405 // since the parent class isn't instantiated until later.
6406 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6407 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6408 !NewImportAttr && !NewExportAttr) {
6409 if (const DLLExportAttr *ParentExportAttr =
6410 MD->getParent()->getAttr<DLLExportAttr>()) {
6411 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6412 NewAttr->setInherited(true);
6413 NewDecl->addAttr(NewAttr);
6414 }
6415 }
6416 }
6417 }
6418
6419 /// Given that we are within the definition of the given function,
6420 /// will that definition behave like C99's 'inline', where the
6421 /// definition is discarded except for optimization purposes?
isFunctionDefinitionDiscarded(Sema & S,FunctionDecl * FD)6422 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6423 // Try to avoid calling GetGVALinkageForFunction.
6424
6425 // All cases of this require the 'inline' keyword.
6426 if (!FD->isInlined()) return false;
6427
6428 // This is only possible in C++ with the gnu_inline attribute.
6429 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6430 return false;
6431
6432 // Okay, go ahead and call the relatively-more-expensive function.
6433 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6434 }
6435
6436 /// Determine whether a variable is extern "C" prior to attaching
6437 /// an initializer. We can't just call isExternC() here, because that
6438 /// will also compute and cache whether the declaration is externally
6439 /// visible, which might change when we attach the initializer.
6440 ///
6441 /// This can only be used if the declaration is known to not be a
6442 /// redeclaration of an internal linkage declaration.
6443 ///
6444 /// For instance:
6445 ///
6446 /// auto x = []{};
6447 ///
6448 /// Attaching the initializer here makes this declaration not externally
6449 /// visible, because its type has internal linkage.
6450 ///
6451 /// FIXME: This is a hack.
6452 template<typename T>
isIncompleteDeclExternC(Sema & S,const T * D)6453 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6454 if (S.getLangOpts().CPlusPlus) {
6455 // In C++, the overloadable attribute negates the effects of extern "C".
6456 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6457 return false;
6458
6459 // So do CUDA's host/device attributes.
6460 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6461 D->template hasAttr<CUDAHostAttr>()))
6462 return false;
6463 }
6464 return D->isExternC();
6465 }
6466
shouldConsiderLinkage(const VarDecl * VD)6467 static bool shouldConsiderLinkage(const VarDecl *VD) {
6468 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6469 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6470 isa<OMPDeclareMapperDecl>(DC))
6471 return VD->hasExternalStorage();
6472 if (DC->isFileContext())
6473 return true;
6474 if (DC->isRecord())
6475 return false;
6476 if (isa<RequiresExprBodyDecl>(DC))
6477 return false;
6478 llvm_unreachable("Unexpected context");
6479 }
6480
shouldConsiderLinkage(const FunctionDecl * FD)6481 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6482 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6483 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6484 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6485 return true;
6486 if (DC->isRecord())
6487 return false;
6488 llvm_unreachable("Unexpected context");
6489 }
6490
hasParsedAttr(Scope * S,const Declarator & PD,ParsedAttr::Kind Kind)6491 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6492 ParsedAttr::Kind Kind) {
6493 // Check decl attributes on the DeclSpec.
6494 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6495 return true;
6496
6497 // Walk the declarator structure, checking decl attributes that were in a type
6498 // position to the decl itself.
6499 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6500 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6501 return true;
6502 }
6503
6504 // Finally, check attributes on the decl itself.
6505 return PD.getAttributes().hasAttribute(Kind);
6506 }
6507
6508 /// Adjust the \c DeclContext for a function or variable that might be a
6509 /// function-local external declaration.
adjustContextForLocalExternDecl(DeclContext * & DC)6510 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6511 if (!DC->isFunctionOrMethod())
6512 return false;
6513
6514 // If this is a local extern function or variable declared within a function
6515 // template, don't add it into the enclosing namespace scope until it is
6516 // instantiated; it might have a dependent type right now.
6517 if (DC->isDependentContext())
6518 return true;
6519
6520 // C++11 [basic.link]p7:
6521 // When a block scope declaration of an entity with linkage is not found to
6522 // refer to some other declaration, then that entity is a member of the
6523 // innermost enclosing namespace.
6524 //
6525 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6526 // semantically-enclosing namespace, not a lexically-enclosing one.
6527 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6528 DC = DC->getParent();
6529 return true;
6530 }
6531
6532 /// Returns true if given declaration has external C language linkage.
isDeclExternC(const Decl * D)6533 static bool isDeclExternC(const Decl *D) {
6534 if (const auto *FD = dyn_cast<FunctionDecl>(D))
6535 return FD->isExternC();
6536 if (const auto *VD = dyn_cast<VarDecl>(D))
6537 return VD->isExternC();
6538
6539 llvm_unreachable("Unknown type of decl!");
6540 }
6541 /// Returns true if there hasn't been any invalid type diagnosed.
diagnoseOpenCLTypes(Scope * S,Sema & Se,Declarator & D,DeclContext * DC,QualType R)6542 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6543 DeclContext *DC, QualType R) {
6544 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6545 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6546 // argument.
6547 if (R->isImageType() || R->isPipeType()) {
6548 Se.Diag(D.getIdentifierLoc(),
6549 diag::err_opencl_type_can_only_be_used_as_function_parameter)
6550 << R;
6551 D.setInvalidType();
6552 return false;
6553 }
6554
6555 // OpenCL v1.2 s6.9.r:
6556 // The event type cannot be used to declare a program scope variable.
6557 // OpenCL v2.0 s6.9.q:
6558 // The clk_event_t and reserve_id_t types cannot be declared in program
6559 // scope.
6560 if (NULL == S->getParent()) {
6561 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6562 Se.Diag(D.getIdentifierLoc(),
6563 diag::err_invalid_type_for_program_scope_var)
6564 << R;
6565 D.setInvalidType();
6566 return false;
6567 }
6568 }
6569
6570 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6571 QualType NR = R;
6572 while (NR->isPointerType()) {
6573 if (NR->isFunctionPointerType()) {
6574 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6575 D.setInvalidType();
6576 return false;
6577 }
6578 NR = NR->getPointeeType();
6579 }
6580
6581 if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6582 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6583 // half array type (unless the cl_khr_fp16 extension is enabled).
6584 if (Se.Context.getBaseElementType(R)->isHalfType()) {
6585 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6586 D.setInvalidType();
6587 return false;
6588 }
6589 }
6590
6591 // OpenCL v1.2 s6.9.r:
6592 // The event type cannot be used with the __local, __constant and __global
6593 // address space qualifiers.
6594 if (R->isEventT()) {
6595 if (R.getAddressSpace() != LangAS::opencl_private) {
6596 Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6597 D.setInvalidType();
6598 return false;
6599 }
6600 }
6601
6602 // C++ for OpenCL does not allow the thread_local storage qualifier.
6603 // OpenCL C does not support thread_local either, and
6604 // also reject all other thread storage class specifiers.
6605 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6606 if (TSC != TSCS_unspecified) {
6607 bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6608 Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6609 diag::err_opencl_unknown_type_specifier)
6610 << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6611 << DeclSpec::getSpecifierName(TSC) << 1;
6612 D.setInvalidType();
6613 return false;
6614 }
6615
6616 if (R->isSamplerT()) {
6617 // OpenCL v1.2 s6.9.b p4:
6618 // The sampler type cannot be used with the __local and __global address
6619 // space qualifiers.
6620 if (R.getAddressSpace() == LangAS::opencl_local ||
6621 R.getAddressSpace() == LangAS::opencl_global) {
6622 Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6623 D.setInvalidType();
6624 }
6625
6626 // OpenCL v1.2 s6.12.14.1:
6627 // A global sampler must be declared with either the constant address
6628 // space qualifier or with the const qualifier.
6629 if (DC->isTranslationUnit() &&
6630 !(R.getAddressSpace() == LangAS::opencl_constant ||
6631 R.isConstQualified())) {
6632 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6633 D.setInvalidType();
6634 }
6635 if (D.isInvalidType())
6636 return false;
6637 }
6638 return true;
6639 }
6640
ActOnVariableDeclarator(Scope * S,Declarator & D,DeclContext * DC,TypeSourceInfo * TInfo,LookupResult & Previous,MultiTemplateParamsArg TemplateParamLists,bool & AddToScope,ArrayRef<BindingDecl * > Bindings)6641 NamedDecl *Sema::ActOnVariableDeclarator(
6642 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6643 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6644 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6645 QualType R = TInfo->getType();
6646 DeclarationName Name = GetNameForDeclarator(D).getName();
6647
6648 IdentifierInfo *II = Name.getAsIdentifierInfo();
6649
6650 if (D.isDecompositionDeclarator()) {
6651 // Take the name of the first declarator as our name for diagnostic
6652 // purposes.
6653 auto &Decomp = D.getDecompositionDeclarator();
6654 if (!Decomp.bindings().empty()) {
6655 II = Decomp.bindings()[0].Name;
6656 Name = II;
6657 }
6658 } else if (!II) {
6659 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6660 return nullptr;
6661 }
6662
6663
6664 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6665 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6666
6667 // dllimport globals without explicit storage class are treated as extern. We
6668 // have to change the storage class this early to get the right DeclContext.
6669 if (SC == SC_None && !DC->isRecord() &&
6670 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6671 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6672 SC = SC_Extern;
6673
6674 DeclContext *OriginalDC = DC;
6675 bool IsLocalExternDecl = SC == SC_Extern &&
6676 adjustContextForLocalExternDecl(DC);
6677
6678 if (SCSpec == DeclSpec::SCS_mutable) {
6679 // mutable can only appear on non-static class members, so it's always
6680 // an error here
6681 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6682 D.setInvalidType();
6683 SC = SC_None;
6684 }
6685
6686 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6687 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6688 D.getDeclSpec().getStorageClassSpecLoc())) {
6689 // In C++11, the 'register' storage class specifier is deprecated.
6690 // Suppress the warning in system macros, it's used in macros in some
6691 // popular C system headers, such as in glibc's htonl() macro.
6692 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6693 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6694 : diag::warn_deprecated_register)
6695 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6696 }
6697
6698 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6699
6700 if (!DC->isRecord() && S->getFnParent() == nullptr) {
6701 // C99 6.9p2: The storage-class specifiers auto and register shall not
6702 // appear in the declaration specifiers in an external declaration.
6703 // Global Register+Asm is a GNU extension we support.
6704 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6705 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6706 D.setInvalidType();
6707 }
6708 }
6709
6710 bool IsMemberSpecialization = false;
6711 bool IsVariableTemplateSpecialization = false;
6712 bool IsPartialSpecialization = false;
6713 bool IsVariableTemplate = false;
6714 VarDecl *NewVD = nullptr;
6715 VarTemplateDecl *NewTemplate = nullptr;
6716 TemplateParameterList *TemplateParams = nullptr;
6717 if (!getLangOpts().CPlusPlus) {
6718 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6719 II, R, TInfo, SC);
6720
6721 if (R->getContainedDeducedType())
6722 ParsingInitForAutoVars.insert(NewVD);
6723
6724 if (D.isInvalidType())
6725 NewVD->setInvalidDecl();
6726
6727 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6728 NewVD->hasLocalStorage())
6729 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6730 NTCUC_AutoVar, NTCUK_Destruct);
6731 } else {
6732 bool Invalid = false;
6733
6734 if (DC->isRecord() && !CurContext->isRecord()) {
6735 // This is an out-of-line definition of a static data member.
6736 switch (SC) {
6737 case SC_None:
6738 break;
6739 case SC_Static:
6740 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6741 diag::err_static_out_of_line)
6742 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6743 break;
6744 case SC_Auto:
6745 case SC_Register:
6746 case SC_Extern:
6747 // [dcl.stc] p2: The auto or register specifiers shall be applied only
6748 // to names of variables declared in a block or to function parameters.
6749 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6750 // of class members
6751
6752 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6753 diag::err_storage_class_for_static_member)
6754 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6755 break;
6756 case SC_PrivateExtern:
6757 llvm_unreachable("C storage class in c++!");
6758 }
6759 }
6760
6761 if (SC == SC_Static && CurContext->isRecord()) {
6762 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6763 if (RD->isLocalClass())
6764 Diag(D.getIdentifierLoc(),
6765 diag::err_static_data_member_not_allowed_in_local_class)
6766 << Name << RD->getDeclName();
6767
6768 // C++98 [class.union]p1: If a union contains a static data member,
6769 // the program is ill-formed. C++11 drops this restriction.
6770 if (RD->isUnion())
6771 Diag(D.getIdentifierLoc(),
6772 getLangOpts().CPlusPlus11
6773 ? diag::warn_cxx98_compat_static_data_member_in_union
6774 : diag::ext_static_data_member_in_union) << Name;
6775 // We conservatively disallow static data members in anonymous structs.
6776 else if (!RD->getDeclName())
6777 Diag(D.getIdentifierLoc(),
6778 diag::err_static_data_member_not_allowed_in_anon_struct)
6779 << Name << RD->isUnion();
6780 }
6781 }
6782
6783 // Match up the template parameter lists with the scope specifier, then
6784 // determine whether we have a template or a template specialization.
6785 TemplateParams = MatchTemplateParametersToScopeSpecifier(
6786 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6787 D.getCXXScopeSpec(),
6788 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6789 ? D.getName().TemplateId
6790 : nullptr,
6791 TemplateParamLists,
6792 /*never a friend*/ false, IsMemberSpecialization, Invalid);
6793
6794 if (TemplateParams) {
6795 if (!TemplateParams->size() &&
6796 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6797 // There is an extraneous 'template<>' for this variable. Complain
6798 // about it, but allow the declaration of the variable.
6799 Diag(TemplateParams->getTemplateLoc(),
6800 diag::err_template_variable_noparams)
6801 << II
6802 << SourceRange(TemplateParams->getTemplateLoc(),
6803 TemplateParams->getRAngleLoc());
6804 TemplateParams = nullptr;
6805 } else {
6806 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6807 // This is an explicit specialization or a partial specialization.
6808 // FIXME: Check that we can declare a specialization here.
6809 IsVariableTemplateSpecialization = true;
6810 IsPartialSpecialization = TemplateParams->size() > 0;
6811 } else { // if (TemplateParams->size() > 0)
6812 // This is a template declaration.
6813 IsVariableTemplate = true;
6814
6815 // Check that we can declare a template here.
6816 if (CheckTemplateDeclScope(S, TemplateParams))
6817 return nullptr;
6818
6819 // Only C++1y supports variable templates (N3651).
6820 Diag(D.getIdentifierLoc(),
6821 getLangOpts().CPlusPlus14
6822 ? diag::warn_cxx11_compat_variable_template
6823 : diag::ext_variable_template);
6824 }
6825 }
6826 } else {
6827 assert((Invalid ||
6828 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6829 "should have a 'template<>' for this decl");
6830 }
6831
6832 if (IsVariableTemplateSpecialization) {
6833 SourceLocation TemplateKWLoc =
6834 TemplateParamLists.size() > 0
6835 ? TemplateParamLists[0]->getTemplateLoc()
6836 : SourceLocation();
6837 DeclResult Res = ActOnVarTemplateSpecialization(
6838 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6839 IsPartialSpecialization);
6840 if (Res.isInvalid())
6841 return nullptr;
6842 NewVD = cast<VarDecl>(Res.get());
6843 AddToScope = false;
6844 } else if (D.isDecompositionDeclarator()) {
6845 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6846 D.getIdentifierLoc(), R, TInfo, SC,
6847 Bindings);
6848 } else
6849 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6850 D.getIdentifierLoc(), II, R, TInfo, SC);
6851
6852 // If this is supposed to be a variable template, create it as such.
6853 if (IsVariableTemplate) {
6854 NewTemplate =
6855 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6856 TemplateParams, NewVD);
6857 NewVD->setDescribedVarTemplate(NewTemplate);
6858 }
6859
6860 // If this decl has an auto type in need of deduction, make a note of the
6861 // Decl so we can diagnose uses of it in its own initializer.
6862 if (R->getContainedDeducedType())
6863 ParsingInitForAutoVars.insert(NewVD);
6864
6865 if (D.isInvalidType() || Invalid) {
6866 NewVD->setInvalidDecl();
6867 if (NewTemplate)
6868 NewTemplate->setInvalidDecl();
6869 }
6870
6871 SetNestedNameSpecifier(*this, NewVD, D);
6872
6873 // If we have any template parameter lists that don't directly belong to
6874 // the variable (matching the scope specifier), store them.
6875 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6876 if (TemplateParamLists.size() > VDTemplateParamLists)
6877 NewVD->setTemplateParameterListsInfo(
6878 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6879 }
6880
6881 if (D.getDeclSpec().isInlineSpecified()) {
6882 if (!getLangOpts().CPlusPlus) {
6883 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6884 << 0;
6885 } else if (CurContext->isFunctionOrMethod()) {
6886 // 'inline' is not allowed on block scope variable declaration.
6887 Diag(D.getDeclSpec().getInlineSpecLoc(),
6888 diag::err_inline_declaration_block_scope) << Name
6889 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6890 } else {
6891 Diag(D.getDeclSpec().getInlineSpecLoc(),
6892 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6893 : diag::ext_inline_variable);
6894 NewVD->setInlineSpecified();
6895 }
6896 }
6897
6898 // Set the lexical context. If the declarator has a C++ scope specifier, the
6899 // lexical context will be different from the semantic context.
6900 NewVD->setLexicalDeclContext(CurContext);
6901 if (NewTemplate)
6902 NewTemplate->setLexicalDeclContext(CurContext);
6903
6904 if (IsLocalExternDecl) {
6905 if (D.isDecompositionDeclarator())
6906 for (auto *B : Bindings)
6907 B->setLocalExternDecl();
6908 else
6909 NewVD->setLocalExternDecl();
6910 }
6911
6912 bool EmitTLSUnsupportedError = false;
6913 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6914 // C++11 [dcl.stc]p4:
6915 // When thread_local is applied to a variable of block scope the
6916 // storage-class-specifier static is implied if it does not appear
6917 // explicitly.
6918 // Core issue: 'static' is not implied if the variable is declared
6919 // 'extern'.
6920 if (NewVD->hasLocalStorage() &&
6921 (SCSpec != DeclSpec::SCS_unspecified ||
6922 TSCS != DeclSpec::TSCS_thread_local ||
6923 !DC->isFunctionOrMethod()))
6924 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6925 diag::err_thread_non_global)
6926 << DeclSpec::getSpecifierName(TSCS);
6927 else if (!Context.getTargetInfo().isTLSSupported()) {
6928 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6929 // Postpone error emission until we've collected attributes required to
6930 // figure out whether it's a host or device variable and whether the
6931 // error should be ignored.
6932 EmitTLSUnsupportedError = true;
6933 // We still need to mark the variable as TLS so it shows up in AST with
6934 // proper storage class for other tools to use even if we're not going
6935 // to emit any code for it.
6936 NewVD->setTSCSpec(TSCS);
6937 } else
6938 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6939 diag::err_thread_unsupported);
6940 } else
6941 NewVD->setTSCSpec(TSCS);
6942 }
6943
6944 switch (D.getDeclSpec().getConstexprSpecifier()) {
6945 case CSK_unspecified:
6946 break;
6947
6948 case CSK_consteval:
6949 Diag(D.getDeclSpec().getConstexprSpecLoc(),
6950 diag::err_constexpr_wrong_decl_kind)
6951 << D.getDeclSpec().getConstexprSpecifier();
6952 LLVM_FALLTHROUGH;
6953
6954 case CSK_constexpr:
6955 NewVD->setConstexpr(true);
6956 // C++1z [dcl.spec.constexpr]p1:
6957 // A static data member declared with the constexpr specifier is
6958 // implicitly an inline variable.
6959 if (NewVD->isStaticDataMember() &&
6960 (getLangOpts().CPlusPlus17 ||
6961 Context.getTargetInfo().getCXXABI().isMicrosoft()))
6962 NewVD->setImplicitlyInline();
6963 break;
6964
6965 case CSK_constinit:
6966 if (!NewVD->hasGlobalStorage())
6967 Diag(D.getDeclSpec().getConstexprSpecLoc(),
6968 diag::err_constinit_local_variable);
6969 else
6970 NewVD->addAttr(ConstInitAttr::Create(
6971 Context, D.getDeclSpec().getConstexprSpecLoc(),
6972 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
6973 break;
6974 }
6975
6976 // C99 6.7.4p3
6977 // An inline definition of a function with external linkage shall
6978 // not contain a definition of a modifiable object with static or
6979 // thread storage duration...
6980 // We only apply this when the function is required to be defined
6981 // elsewhere, i.e. when the function is not 'extern inline'. Note
6982 // that a local variable with thread storage duration still has to
6983 // be marked 'static'. Also note that it's possible to get these
6984 // semantics in C++ using __attribute__((gnu_inline)).
6985 if (SC == SC_Static && S->getFnParent() != nullptr &&
6986 !NewVD->getType().isConstQualified()) {
6987 FunctionDecl *CurFD = getCurFunctionDecl();
6988 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6989 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6990 diag::warn_static_local_in_extern_inline);
6991 MaybeSuggestAddingStaticToDecl(CurFD);
6992 }
6993 }
6994
6995 if (D.getDeclSpec().isModulePrivateSpecified()) {
6996 if (IsVariableTemplateSpecialization)
6997 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6998 << (IsPartialSpecialization ? 1 : 0)
6999 << FixItHint::CreateRemoval(
7000 D.getDeclSpec().getModulePrivateSpecLoc());
7001 else if (IsMemberSpecialization)
7002 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7003 << 2
7004 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7005 else if (NewVD->hasLocalStorage())
7006 Diag(NewVD->getLocation(), diag::err_module_private_local)
7007 << 0 << NewVD->getDeclName()
7008 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7009 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7010 else {
7011 NewVD->setModulePrivate();
7012 if (NewTemplate)
7013 NewTemplate->setModulePrivate();
7014 for (auto *B : Bindings)
7015 B->setModulePrivate();
7016 }
7017 }
7018
7019 if (getLangOpts().OpenCL) {
7020
7021 deduceOpenCLAddressSpace(NewVD);
7022
7023 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7024 }
7025
7026 // Handle attributes prior to checking for duplicates in MergeVarDecl
7027 ProcessDeclAttributes(S, NewVD, D);
7028
7029 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
7030 if (EmitTLSUnsupportedError &&
7031 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7032 (getLangOpts().OpenMPIsDevice &&
7033 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7034 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7035 diag::err_thread_unsupported);
7036 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7037 // storage [duration]."
7038 if (SC == SC_None && S->getFnParent() != nullptr &&
7039 (NewVD->hasAttr<CUDASharedAttr>() ||
7040 NewVD->hasAttr<CUDAConstantAttr>())) {
7041 NewVD->setStorageClass(SC_Static);
7042 }
7043 }
7044
7045 // Ensure that dllimport globals without explicit storage class are treated as
7046 // extern. The storage class is set above using parsed attributes. Now we can
7047 // check the VarDecl itself.
7048 assert(!NewVD->hasAttr<DLLImportAttr>() ||
7049 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7050 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7051
7052 // In auto-retain/release, infer strong retension for variables of
7053 // retainable type.
7054 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7055 NewVD->setInvalidDecl();
7056
7057 // Handle GNU asm-label extension (encoded as an attribute).
7058 if (Expr *E = (Expr*)D.getAsmLabel()) {
7059 // The parser guarantees this is a string.
7060 StringLiteral *SE = cast<StringLiteral>(E);
7061 StringRef Label = SE->getString();
7062 if (S->getFnParent() != nullptr) {
7063 switch (SC) {
7064 case SC_None:
7065 case SC_Auto:
7066 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7067 break;
7068 case SC_Register:
7069 // Local Named register
7070 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7071 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7072 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7073 break;
7074 case SC_Static:
7075 case SC_Extern:
7076 case SC_PrivateExtern:
7077 break;
7078 }
7079 } else if (SC == SC_Register) {
7080 // Global Named register
7081 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7082 const auto &TI = Context.getTargetInfo();
7083 bool HasSizeMismatch;
7084
7085 if (!TI.isValidGCCRegisterName(Label))
7086 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7087 else if (!TI.validateGlobalRegisterVariable(Label,
7088 Context.getTypeSize(R),
7089 HasSizeMismatch))
7090 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7091 else if (HasSizeMismatch)
7092 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7093 }
7094
7095 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7096 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7097 NewVD->setInvalidDecl(true);
7098 }
7099 }
7100
7101 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7102 /*IsLiteralLabel=*/true,
7103 SE->getStrTokenLoc(0)));
7104 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7105 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7106 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7107 if (I != ExtnameUndeclaredIdentifiers.end()) {
7108 if (isDeclExternC(NewVD)) {
7109 NewVD->addAttr(I->second);
7110 ExtnameUndeclaredIdentifiers.erase(I);
7111 } else
7112 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7113 << /*Variable*/1 << NewVD;
7114 }
7115 }
7116
7117 // Find the shadowed declaration before filtering for scope.
7118 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7119 ? getShadowedDeclaration(NewVD, Previous)
7120 : nullptr;
7121
7122 // Don't consider existing declarations that are in a different
7123 // scope and are out-of-semantic-context declarations (if the new
7124 // declaration has linkage).
7125 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7126 D.getCXXScopeSpec().isNotEmpty() ||
7127 IsMemberSpecialization ||
7128 IsVariableTemplateSpecialization);
7129
7130 // Check whether the previous declaration is in the same block scope. This
7131 // affects whether we merge types with it, per C++11 [dcl.array]p3.
7132 if (getLangOpts().CPlusPlus &&
7133 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7134 NewVD->setPreviousDeclInSameBlockScope(
7135 Previous.isSingleResult() && !Previous.isShadowed() &&
7136 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7137
7138 if (!getLangOpts().CPlusPlus) {
7139 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7140 } else {
7141 // If this is an explicit specialization of a static data member, check it.
7142 if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7143 CheckMemberSpecialization(NewVD, Previous))
7144 NewVD->setInvalidDecl();
7145
7146 // Merge the decl with the existing one if appropriate.
7147 if (!Previous.empty()) {
7148 if (Previous.isSingleResult() &&
7149 isa<FieldDecl>(Previous.getFoundDecl()) &&
7150 D.getCXXScopeSpec().isSet()) {
7151 // The user tried to define a non-static data member
7152 // out-of-line (C++ [dcl.meaning]p1).
7153 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7154 << D.getCXXScopeSpec().getRange();
7155 Previous.clear();
7156 NewVD->setInvalidDecl();
7157 }
7158 } else if (D.getCXXScopeSpec().isSet()) {
7159 // No previous declaration in the qualifying scope.
7160 Diag(D.getIdentifierLoc(), diag::err_no_member)
7161 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7162 << D.getCXXScopeSpec().getRange();
7163 NewVD->setInvalidDecl();
7164 }
7165
7166 if (!IsVariableTemplateSpecialization)
7167 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7168
7169 if (NewTemplate) {
7170 VarTemplateDecl *PrevVarTemplate =
7171 NewVD->getPreviousDecl()
7172 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7173 : nullptr;
7174
7175 // Check the template parameter list of this declaration, possibly
7176 // merging in the template parameter list from the previous variable
7177 // template declaration.
7178 if (CheckTemplateParameterList(
7179 TemplateParams,
7180 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7181 : nullptr,
7182 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7183 DC->isDependentContext())
7184 ? TPC_ClassTemplateMember
7185 : TPC_VarTemplate))
7186 NewVD->setInvalidDecl();
7187
7188 // If we are providing an explicit specialization of a static variable
7189 // template, make a note of that.
7190 if (PrevVarTemplate &&
7191 PrevVarTemplate->getInstantiatedFromMemberTemplate())
7192 PrevVarTemplate->setMemberSpecialization();
7193 }
7194 }
7195
7196 // Diagnose shadowed variables iff this isn't a redeclaration.
7197 if (ShadowedDecl && !D.isRedeclaration())
7198 CheckShadow(NewVD, ShadowedDecl, Previous);
7199
7200 ProcessPragmaWeak(S, NewVD);
7201
7202 // If this is the first declaration of an extern C variable, update
7203 // the map of such variables.
7204 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7205 isIncompleteDeclExternC(*this, NewVD))
7206 RegisterLocallyScopedExternCDecl(NewVD, S);
7207
7208 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7209 MangleNumberingContext *MCtx;
7210 Decl *ManglingContextDecl;
7211 std::tie(MCtx, ManglingContextDecl) =
7212 getCurrentMangleNumberContext(NewVD->getDeclContext());
7213 if (MCtx) {
7214 Context.setManglingNumber(
7215 NewVD, MCtx->getManglingNumber(
7216 NewVD, getMSManglingNumber(getLangOpts(), S)));
7217 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7218 }
7219 }
7220
7221 // Special handling of variable named 'main'.
7222 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7223 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7224 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7225
7226 // C++ [basic.start.main]p3
7227 // A program that declares a variable main at global scope is ill-formed.
7228 if (getLangOpts().CPlusPlus)
7229 Diag(D.getBeginLoc(), diag::err_main_global_variable);
7230
7231 // In C, and external-linkage variable named main results in undefined
7232 // behavior.
7233 else if (NewVD->hasExternalFormalLinkage())
7234 Diag(D.getBeginLoc(), diag::warn_main_redefined);
7235 }
7236
7237 if (D.isRedeclaration() && !Previous.empty()) {
7238 NamedDecl *Prev = Previous.getRepresentativeDecl();
7239 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7240 D.isFunctionDefinition());
7241 }
7242
7243 if (NewTemplate) {
7244 if (NewVD->isInvalidDecl())
7245 NewTemplate->setInvalidDecl();
7246 ActOnDocumentableDecl(NewTemplate);
7247 return NewTemplate;
7248 }
7249
7250 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7251 CompleteMemberSpecialization(NewVD, Previous);
7252
7253 return NewVD;
7254 }
7255
7256 /// Enum describing the %select options in diag::warn_decl_shadow.
7257 enum ShadowedDeclKind {
7258 SDK_Local,
7259 SDK_Global,
7260 SDK_StaticMember,
7261 SDK_Field,
7262 SDK_Typedef,
7263 SDK_Using
7264 };
7265
7266 /// Determine what kind of declaration we're shadowing.
computeShadowedDeclKind(const NamedDecl * ShadowedDecl,const DeclContext * OldDC)7267 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7268 const DeclContext *OldDC) {
7269 if (isa<TypeAliasDecl>(ShadowedDecl))
7270 return SDK_Using;
7271 else if (isa<TypedefDecl>(ShadowedDecl))
7272 return SDK_Typedef;
7273 else if (isa<RecordDecl>(OldDC))
7274 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7275
7276 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7277 }
7278
7279 /// Return the location of the capture if the given lambda captures the given
7280 /// variable \p VD, or an invalid source location otherwise.
getCaptureLocation(const LambdaScopeInfo * LSI,const VarDecl * VD)7281 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7282 const VarDecl *VD) {
7283 for (const Capture &Capture : LSI->Captures) {
7284 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7285 return Capture.getLocation();
7286 }
7287 return SourceLocation();
7288 }
7289
shouldWarnIfShadowedDecl(const DiagnosticsEngine & Diags,const LookupResult & R)7290 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7291 const LookupResult &R) {
7292 // Only diagnose if we're shadowing an unambiguous field or variable.
7293 if (R.getResultKind() != LookupResult::Found)
7294 return false;
7295
7296 // Return false if warning is ignored.
7297 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7298 }
7299
7300 /// Return the declaration shadowed by the given variable \p D, or null
7301 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
getShadowedDeclaration(const VarDecl * D,const LookupResult & R)7302 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7303 const LookupResult &R) {
7304 if (!shouldWarnIfShadowedDecl(Diags, R))
7305 return nullptr;
7306
7307 // Don't diagnose declarations at file scope.
7308 if (D->hasGlobalStorage())
7309 return nullptr;
7310
7311 NamedDecl *ShadowedDecl = R.getFoundDecl();
7312 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7313 ? ShadowedDecl
7314 : nullptr;
7315 }
7316
7317 /// Return the declaration shadowed by the given typedef \p D, or null
7318 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
getShadowedDeclaration(const TypedefNameDecl * D,const LookupResult & R)7319 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7320 const LookupResult &R) {
7321 // Don't warn if typedef declaration is part of a class
7322 if (D->getDeclContext()->isRecord())
7323 return nullptr;
7324
7325 if (!shouldWarnIfShadowedDecl(Diags, R))
7326 return nullptr;
7327
7328 NamedDecl *ShadowedDecl = R.getFoundDecl();
7329 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7330 }
7331
7332 /// Diagnose variable or built-in function shadowing. Implements
7333 /// -Wshadow.
7334 ///
7335 /// This method is called whenever a VarDecl is added to a "useful"
7336 /// scope.
7337 ///
7338 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7339 /// \param R the lookup of the name
7340 ///
CheckShadow(NamedDecl * D,NamedDecl * ShadowedDecl,const LookupResult & R)7341 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7342 const LookupResult &R) {
7343 DeclContext *NewDC = D->getDeclContext();
7344
7345 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7346 // Fields are not shadowed by variables in C++ static methods.
7347 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7348 if (MD->isStatic())
7349 return;
7350
7351 // Fields shadowed by constructor parameters are a special case. Usually
7352 // the constructor initializes the field with the parameter.
7353 if (isa<CXXConstructorDecl>(NewDC))
7354 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7355 // Remember that this was shadowed so we can either warn about its
7356 // modification or its existence depending on warning settings.
7357 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7358 return;
7359 }
7360 }
7361
7362 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7363 if (shadowedVar->isExternC()) {
7364 // For shadowing external vars, make sure that we point to the global
7365 // declaration, not a locally scoped extern declaration.
7366 for (auto I : shadowedVar->redecls())
7367 if (I->isFileVarDecl()) {
7368 ShadowedDecl = I;
7369 break;
7370 }
7371 }
7372
7373 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7374
7375 unsigned WarningDiag = diag::warn_decl_shadow;
7376 SourceLocation CaptureLoc;
7377 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7378 isa<CXXMethodDecl>(NewDC)) {
7379 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7380 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7381 if (RD->getLambdaCaptureDefault() == LCD_None) {
7382 // Try to avoid warnings for lambdas with an explicit capture list.
7383 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7384 // Warn only when the lambda captures the shadowed decl explicitly.
7385 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7386 if (CaptureLoc.isInvalid())
7387 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7388 } else {
7389 // Remember that this was shadowed so we can avoid the warning if the
7390 // shadowed decl isn't captured and the warning settings allow it.
7391 cast<LambdaScopeInfo>(getCurFunction())
7392 ->ShadowingDecls.push_back(
7393 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7394 return;
7395 }
7396 }
7397
7398 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7399 // A variable can't shadow a local variable in an enclosing scope, if
7400 // they are separated by a non-capturing declaration context.
7401 for (DeclContext *ParentDC = NewDC;
7402 ParentDC && !ParentDC->Equals(OldDC);
7403 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7404 // Only block literals, captured statements, and lambda expressions
7405 // can capture; other scopes don't.
7406 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7407 !isLambdaCallOperator(ParentDC)) {
7408 return;
7409 }
7410 }
7411 }
7412 }
7413 }
7414
7415 // Only warn about certain kinds of shadowing for class members.
7416 if (NewDC && NewDC->isRecord()) {
7417 // In particular, don't warn about shadowing non-class members.
7418 if (!OldDC->isRecord())
7419 return;
7420
7421 // TODO: should we warn about static data members shadowing
7422 // static data members from base classes?
7423
7424 // TODO: don't diagnose for inaccessible shadowed members.
7425 // This is hard to do perfectly because we might friend the
7426 // shadowing context, but that's just a false negative.
7427 }
7428
7429
7430 DeclarationName Name = R.getLookupName();
7431
7432 // Emit warning and note.
7433 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7434 return;
7435 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7436 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7437 if (!CaptureLoc.isInvalid())
7438 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7439 << Name << /*explicitly*/ 1;
7440 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7441 }
7442
7443 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7444 /// when these variables are captured by the lambda.
DiagnoseShadowingLambdaDecls(const LambdaScopeInfo * LSI)7445 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7446 for (const auto &Shadow : LSI->ShadowingDecls) {
7447 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7448 // Try to avoid the warning when the shadowed decl isn't captured.
7449 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7450 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7451 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7452 ? diag::warn_decl_shadow_uncaptured_local
7453 : diag::warn_decl_shadow)
7454 << Shadow.VD->getDeclName()
7455 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7456 if (!CaptureLoc.isInvalid())
7457 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7458 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7459 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7460 }
7461 }
7462
7463 /// Check -Wshadow without the advantage of a previous lookup.
CheckShadow(Scope * S,VarDecl * D)7464 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7465 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7466 return;
7467
7468 LookupResult R(*this, D->getDeclName(), D->getLocation(),
7469 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7470 LookupName(R, S);
7471 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7472 CheckShadow(D, ShadowedDecl, R);
7473 }
7474
7475 /// Check if 'E', which is an expression that is about to be modified, refers
7476 /// to a constructor parameter that shadows a field.
CheckShadowingDeclModification(Expr * E,SourceLocation Loc)7477 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7478 // Quickly ignore expressions that can't be shadowing ctor parameters.
7479 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7480 return;
7481 E = E->IgnoreParenImpCasts();
7482 auto *DRE = dyn_cast<DeclRefExpr>(E);
7483 if (!DRE)
7484 return;
7485 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7486 auto I = ShadowingDecls.find(D);
7487 if (I == ShadowingDecls.end())
7488 return;
7489 const NamedDecl *ShadowedDecl = I->second;
7490 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7491 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7492 Diag(D->getLocation(), diag::note_var_declared_here) << D;
7493 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7494
7495 // Avoid issuing multiple warnings about the same decl.
7496 ShadowingDecls.erase(I);
7497 }
7498
7499 /// Check for conflict between this global or extern "C" declaration and
7500 /// previous global or extern "C" declarations. This is only used in C++.
7501 template<typename T>
checkGlobalOrExternCConflict(Sema & S,const T * ND,bool IsGlobal,LookupResult & Previous)7502 static bool checkGlobalOrExternCConflict(
7503 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7504 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7505 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7506
7507 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7508 // The common case: this global doesn't conflict with any extern "C"
7509 // declaration.
7510 return false;
7511 }
7512
7513 if (Prev) {
7514 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7515 // Both the old and new declarations have C language linkage. This is a
7516 // redeclaration.
7517 Previous.clear();
7518 Previous.addDecl(Prev);
7519 return true;
7520 }
7521
7522 // This is a global, non-extern "C" declaration, and there is a previous
7523 // non-global extern "C" declaration. Diagnose if this is a variable
7524 // declaration.
7525 if (!isa<VarDecl>(ND))
7526 return false;
7527 } else {
7528 // The declaration is extern "C". Check for any declaration in the
7529 // translation unit which might conflict.
7530 if (IsGlobal) {
7531 // We have already performed the lookup into the translation unit.
7532 IsGlobal = false;
7533 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7534 I != E; ++I) {
7535 if (isa<VarDecl>(*I)) {
7536 Prev = *I;
7537 break;
7538 }
7539 }
7540 } else {
7541 DeclContext::lookup_result R =
7542 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7543 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7544 I != E; ++I) {
7545 if (isa<VarDecl>(*I)) {
7546 Prev = *I;
7547 break;
7548 }
7549 // FIXME: If we have any other entity with this name in global scope,
7550 // the declaration is ill-formed, but that is a defect: it breaks the
7551 // 'stat' hack, for instance. Only variables can have mangled name
7552 // clashes with extern "C" declarations, so only they deserve a
7553 // diagnostic.
7554 }
7555 }
7556
7557 if (!Prev)
7558 return false;
7559 }
7560
7561 // Use the first declaration's location to ensure we point at something which
7562 // is lexically inside an extern "C" linkage-spec.
7563 assert(Prev && "should have found a previous declaration to diagnose");
7564 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7565 Prev = FD->getFirstDecl();
7566 else
7567 Prev = cast<VarDecl>(Prev)->getFirstDecl();
7568
7569 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7570 << IsGlobal << ND;
7571 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7572 << IsGlobal;
7573 return false;
7574 }
7575
7576 /// Apply special rules for handling extern "C" declarations. Returns \c true
7577 /// if we have found that this is a redeclaration of some prior entity.
7578 ///
7579 /// Per C++ [dcl.link]p6:
7580 /// Two declarations [for a function or variable] with C language linkage
7581 /// with the same name that appear in different scopes refer to the same
7582 /// [entity]. An entity with C language linkage shall not be declared with
7583 /// the same name as an entity in global scope.
7584 template<typename T>
checkForConflictWithNonVisibleExternC(Sema & S,const T * ND,LookupResult & Previous)7585 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7586 LookupResult &Previous) {
7587 if (!S.getLangOpts().CPlusPlus) {
7588 // In C, when declaring a global variable, look for a corresponding 'extern'
7589 // variable declared in function scope. We don't need this in C++, because
7590 // we find local extern decls in the surrounding file-scope DeclContext.
7591 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7592 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7593 Previous.clear();
7594 Previous.addDecl(Prev);
7595 return true;
7596 }
7597 }
7598 return false;
7599 }
7600
7601 // A declaration in the translation unit can conflict with an extern "C"
7602 // declaration.
7603 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7604 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7605
7606 // An extern "C" declaration can conflict with a declaration in the
7607 // translation unit or can be a redeclaration of an extern "C" declaration
7608 // in another scope.
7609 if (isIncompleteDeclExternC(S,ND))
7610 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7611
7612 // Neither global nor extern "C": nothing to do.
7613 return false;
7614 }
7615
CheckVariableDeclarationType(VarDecl * NewVD)7616 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7617 // If the decl is already known invalid, don't check it.
7618 if (NewVD->isInvalidDecl())
7619 return;
7620
7621 QualType T = NewVD->getType();
7622
7623 // Defer checking an 'auto' type until its initializer is attached.
7624 if (T->isUndeducedType())
7625 return;
7626
7627 if (NewVD->hasAttrs())
7628 CheckAlignasUnderalignment(NewVD);
7629
7630 if (T->isObjCObjectType()) {
7631 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7632 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7633 T = Context.getObjCObjectPointerType(T);
7634 NewVD->setType(T);
7635 }
7636
7637 // Emit an error if an address space was applied to decl with local storage.
7638 // This includes arrays of objects with address space qualifiers, but not
7639 // automatic variables that point to other address spaces.
7640 // ISO/IEC TR 18037 S5.1.2
7641 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7642 T.getAddressSpace() != LangAS::Default) {
7643 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7644 NewVD->setInvalidDecl();
7645 return;
7646 }
7647
7648 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7649 // scope.
7650 if (getLangOpts().OpenCLVersion == 120 &&
7651 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7652 NewVD->isStaticLocal()) {
7653 Diag(NewVD->getLocation(), diag::err_static_function_scope);
7654 NewVD->setInvalidDecl();
7655 return;
7656 }
7657
7658 if (getLangOpts().OpenCL) {
7659 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7660 if (NewVD->hasAttr<BlocksAttr>()) {
7661 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7662 return;
7663 }
7664
7665 if (T->isBlockPointerType()) {
7666 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7667 // can't use 'extern' storage class.
7668 if (!T.isConstQualified()) {
7669 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7670 << 0 /*const*/;
7671 NewVD->setInvalidDecl();
7672 return;
7673 }
7674 if (NewVD->hasExternalStorage()) {
7675 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7676 NewVD->setInvalidDecl();
7677 return;
7678 }
7679 }
7680 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7681 // __constant address space.
7682 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7683 // variables inside a function can also be declared in the global
7684 // address space.
7685 // C++ for OpenCL inherits rule from OpenCL C v2.0.
7686 // FIXME: Adding local AS in C++ for OpenCL might make sense.
7687 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7688 NewVD->hasExternalStorage()) {
7689 if (!T->isSamplerT() &&
7690 !(T.getAddressSpace() == LangAS::opencl_constant ||
7691 (T.getAddressSpace() == LangAS::opencl_global &&
7692 (getLangOpts().OpenCLVersion == 200 ||
7693 getLangOpts().OpenCLCPlusPlus)))) {
7694 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7695 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7696 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7697 << Scope << "global or constant";
7698 else
7699 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7700 << Scope << "constant";
7701 NewVD->setInvalidDecl();
7702 return;
7703 }
7704 } else {
7705 if (T.getAddressSpace() == LangAS::opencl_global) {
7706 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7707 << 1 /*is any function*/ << "global";
7708 NewVD->setInvalidDecl();
7709 return;
7710 }
7711 if (T.getAddressSpace() == LangAS::opencl_constant ||
7712 T.getAddressSpace() == LangAS::opencl_local) {
7713 FunctionDecl *FD = getCurFunctionDecl();
7714 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7715 // in functions.
7716 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7717 if (T.getAddressSpace() == LangAS::opencl_constant)
7718 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7719 << 0 /*non-kernel only*/ << "constant";
7720 else
7721 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7722 << 0 /*non-kernel only*/ << "local";
7723 NewVD->setInvalidDecl();
7724 return;
7725 }
7726 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7727 // in the outermost scope of a kernel function.
7728 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7729 if (!getCurScope()->isFunctionScope()) {
7730 if (T.getAddressSpace() == LangAS::opencl_constant)
7731 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7732 << "constant";
7733 else
7734 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7735 << "local";
7736 NewVD->setInvalidDecl();
7737 return;
7738 }
7739 }
7740 } else if (T.getAddressSpace() != LangAS::opencl_private &&
7741 // If we are parsing a template we didn't deduce an addr
7742 // space yet.
7743 T.getAddressSpace() != LangAS::Default) {
7744 // Do not allow other address spaces on automatic variable.
7745 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7746 NewVD->setInvalidDecl();
7747 return;
7748 }
7749 }
7750 }
7751
7752 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7753 && !NewVD->hasAttr<BlocksAttr>()) {
7754 if (getLangOpts().getGC() != LangOptions::NonGC)
7755 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7756 else {
7757 assert(!getLangOpts().ObjCAutoRefCount);
7758 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7759 }
7760 }
7761
7762 bool isVM = T->isVariablyModifiedType();
7763 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7764 NewVD->hasAttr<BlocksAttr>())
7765 setFunctionHasBranchProtectedScope();
7766
7767 if ((isVM && NewVD->hasLinkage()) ||
7768 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7769 bool SizeIsNegative;
7770 llvm::APSInt Oversized;
7771 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7772 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7773 QualType FixedT;
7774 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
7775 FixedT = FixedTInfo->getType();
7776 else if (FixedTInfo) {
7777 // Type and type-as-written are canonically different. We need to fix up
7778 // both types separately.
7779 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7780 Oversized);
7781 }
7782 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7783 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7784 // FIXME: This won't give the correct result for
7785 // int a[10][n];
7786 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7787
7788 if (NewVD->isFileVarDecl())
7789 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7790 << SizeRange;
7791 else if (NewVD->isStaticLocal())
7792 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7793 << SizeRange;
7794 else
7795 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7796 << SizeRange;
7797 NewVD->setInvalidDecl();
7798 return;
7799 }
7800
7801 if (!FixedTInfo) {
7802 if (NewVD->isFileVarDecl())
7803 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7804 else
7805 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7806 NewVD->setInvalidDecl();
7807 return;
7808 }
7809
7810 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7811 NewVD->setType(FixedT);
7812 NewVD->setTypeSourceInfo(FixedTInfo);
7813 }
7814
7815 if (T->isVoidType()) {
7816 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7817 // of objects and functions.
7818 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7819 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7820 << T;
7821 NewVD->setInvalidDecl();
7822 return;
7823 }
7824 }
7825
7826 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7827 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7828 NewVD->setInvalidDecl();
7829 return;
7830 }
7831
7832 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7833 Diag(NewVD->getLocation(), diag::err_block_on_vm);
7834 NewVD->setInvalidDecl();
7835 return;
7836 }
7837
7838 if (NewVD->isConstexpr() && !T->isDependentType() &&
7839 RequireLiteralType(NewVD->getLocation(), T,
7840 diag::err_constexpr_var_non_literal)) {
7841 NewVD->setInvalidDecl();
7842 return;
7843 }
7844 }
7845
7846 /// Perform semantic checking on a newly-created variable
7847 /// declaration.
7848 ///
7849 /// This routine performs all of the type-checking required for a
7850 /// variable declaration once it has been built. It is used both to
7851 /// check variables after they have been parsed and their declarators
7852 /// have been translated into a declaration, and to check variables
7853 /// that have been instantiated from a template.
7854 ///
7855 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7856 ///
7857 /// Returns true if the variable declaration is a redeclaration.
CheckVariableDeclaration(VarDecl * NewVD,LookupResult & Previous)7858 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7859 CheckVariableDeclarationType(NewVD);
7860
7861 // If the decl is already known invalid, don't check it.
7862 if (NewVD->isInvalidDecl())
7863 return false;
7864
7865 // If we did not find anything by this name, look for a non-visible
7866 // extern "C" declaration with the same name.
7867 if (Previous.empty() &&
7868 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7869 Previous.setShadowed();
7870
7871 if (!Previous.empty()) {
7872 MergeVarDecl(NewVD, Previous);
7873 return true;
7874 }
7875 return false;
7876 }
7877
7878 namespace {
7879 struct FindOverriddenMethod {
7880 Sema *S;
7881 CXXMethodDecl *Method;
7882
7883 /// Member lookup function that determines whether a given C++
7884 /// method overrides a method in a base class, to be used with
7885 /// CXXRecordDecl::lookupInBases().
operator ()__anon45468b3d0811::FindOverriddenMethod7886 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7887 RecordDecl *BaseRecord =
7888 Specifier->getType()->castAs<RecordType>()->getDecl();
7889
7890 DeclarationName Name = Method->getDeclName();
7891
7892 // FIXME: Do we care about other names here too?
7893 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7894 // We really want to find the base class destructor here.
7895 QualType T = S->Context.getTypeDeclType(BaseRecord);
7896 CanQualType CT = S->Context.getCanonicalType(T);
7897
7898 Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7899 }
7900
7901 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7902 Path.Decls = Path.Decls.slice(1)) {
7903 NamedDecl *D = Path.Decls.front();
7904 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7905 if (MD->isVirtual() &&
7906 !S->IsOverload(
7907 Method, MD, /*UseMemberUsingDeclRules=*/false,
7908 /*ConsiderCudaAttrs=*/true,
7909 // C++2a [class.virtual]p2 does not consider requires clauses
7910 // when overriding.
7911 /*ConsiderRequiresClauses=*/false))
7912 return true;
7913 }
7914 }
7915
7916 return false;
7917 }
7918 };
7919
7920 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7921 } // end anonymous namespace
7922
7923 /// Report an error regarding overriding, along with any relevant
7924 /// overridden methods.
7925 ///
7926 /// \param DiagID the primary error to report.
7927 /// \param MD the overriding method.
7928 /// \param OEK which overrides to include as notes.
ReportOverrides(Sema & S,unsigned DiagID,const CXXMethodDecl * MD,OverrideErrorKind OEK=OEK_All)7929 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7930 OverrideErrorKind OEK = OEK_All) {
7931 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7932 for (const CXXMethodDecl *O : MD->overridden_methods()) {
7933 // This check (& the OEK parameter) could be replaced by a predicate, but
7934 // without lambdas that would be overkill. This is still nicer than writing
7935 // out the diag loop 3 times.
7936 if ((OEK == OEK_All) ||
7937 (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7938 (OEK == OEK_Deleted && O->isDeleted()))
7939 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7940 }
7941 }
7942
7943 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7944 /// and if so, check that it's a valid override and remember it.
AddOverriddenMethods(CXXRecordDecl * DC,CXXMethodDecl * MD)7945 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7946 // Look for methods in base classes that this method might override.
7947 CXXBasePaths Paths;
7948 FindOverriddenMethod FOM;
7949 FOM.Method = MD;
7950 FOM.S = this;
7951 bool hasDeletedOverridenMethods = false;
7952 bool hasNonDeletedOverridenMethods = false;
7953 bool AddedAny = false;
7954 if (DC->lookupInBases(FOM, Paths)) {
7955 for (auto *I : Paths.found_decls()) {
7956 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7957 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7958 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7959 !CheckOverridingFunctionAttributes(MD, OldMD) &&
7960 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7961 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7962 hasDeletedOverridenMethods |= OldMD->isDeleted();
7963 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7964 AddedAny = true;
7965 }
7966 }
7967 }
7968 }
7969
7970 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7971 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7972 }
7973 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7974 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7975 }
7976
7977 return AddedAny;
7978 }
7979
7980 namespace {
7981 // Struct for holding all of the extra arguments needed by
7982 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7983 struct ActOnFDArgs {
7984 Scope *S;
7985 Declarator &D;
7986 MultiTemplateParamsArg TemplateParamLists;
7987 bool AddToScope;
7988 };
7989 } // end anonymous namespace
7990
7991 namespace {
7992
7993 // Callback to only accept typo corrections that have a non-zero edit distance.
7994 // Also only accept corrections that have the same parent decl.
7995 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
7996 public:
DifferentNameValidatorCCC(ASTContext & Context,FunctionDecl * TypoFD,CXXRecordDecl * Parent)7997 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7998 CXXRecordDecl *Parent)
7999 : Context(Context), OriginalFD(TypoFD),
8000 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8001
ValidateCandidate(const TypoCorrection & candidate)8002 bool ValidateCandidate(const TypoCorrection &candidate) override {
8003 if (candidate.getEditDistance() == 0)
8004 return false;
8005
8006 SmallVector<unsigned, 1> MismatchedParams;
8007 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8008 CDeclEnd = candidate.end();
8009 CDecl != CDeclEnd; ++CDecl) {
8010 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8011
8012 if (FD && !FD->hasBody() &&
8013 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8014 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8015 CXXRecordDecl *Parent = MD->getParent();
8016 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8017 return true;
8018 } else if (!ExpectedParent) {
8019 return true;
8020 }
8021 }
8022 }
8023
8024 return false;
8025 }
8026
clone()8027 std::unique_ptr<CorrectionCandidateCallback> clone() override {
8028 return std::make_unique<DifferentNameValidatorCCC>(*this);
8029 }
8030
8031 private:
8032 ASTContext &Context;
8033 FunctionDecl *OriginalFD;
8034 CXXRecordDecl *ExpectedParent;
8035 };
8036
8037 } // end anonymous namespace
8038
MarkTypoCorrectedFunctionDefinition(const NamedDecl * F)8039 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8040 TypoCorrectedFunctionDefinitions.insert(F);
8041 }
8042
8043 /// Generate diagnostics for an invalid function redeclaration.
8044 ///
8045 /// This routine handles generating the diagnostic messages for an invalid
8046 /// function redeclaration, including finding possible similar declarations
8047 /// or performing typo correction if there are no previous declarations with
8048 /// the same name.
8049 ///
8050 /// Returns a NamedDecl iff typo correction was performed and substituting in
8051 /// the new declaration name does not cause new errors.
DiagnoseInvalidRedeclaration(Sema & SemaRef,LookupResult & Previous,FunctionDecl * NewFD,ActOnFDArgs & ExtraArgs,bool IsLocalFriend,Scope * S)8052 static NamedDecl *DiagnoseInvalidRedeclaration(
8053 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8054 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8055 DeclarationName Name = NewFD->getDeclName();
8056 DeclContext *NewDC = NewFD->getDeclContext();
8057 SmallVector<unsigned, 1> MismatchedParams;
8058 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8059 TypoCorrection Correction;
8060 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8061 unsigned DiagMsg =
8062 IsLocalFriend ? diag::err_no_matching_local_friend :
8063 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8064 diag::err_member_decl_does_not_match;
8065 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8066 IsLocalFriend ? Sema::LookupLocalFriendName
8067 : Sema::LookupOrdinaryName,
8068 Sema::ForVisibleRedeclaration);
8069
8070 NewFD->setInvalidDecl();
8071 if (IsLocalFriend)
8072 SemaRef.LookupName(Prev, S);
8073 else
8074 SemaRef.LookupQualifiedName(Prev, NewDC);
8075 assert(!Prev.isAmbiguous() &&
8076 "Cannot have an ambiguity in previous-declaration lookup");
8077 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8078 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8079 MD ? MD->getParent() : nullptr);
8080 if (!Prev.empty()) {
8081 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8082 Func != FuncEnd; ++Func) {
8083 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8084 if (FD &&
8085 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8086 // Add 1 to the index so that 0 can mean the mismatch didn't
8087 // involve a parameter
8088 unsigned ParamNum =
8089 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8090 NearMatches.push_back(std::make_pair(FD, ParamNum));
8091 }
8092 }
8093 // If the qualified name lookup yielded nothing, try typo correction
8094 } else if ((Correction = SemaRef.CorrectTypo(
8095 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8096 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8097 IsLocalFriend ? nullptr : NewDC))) {
8098 // Set up everything for the call to ActOnFunctionDeclarator
8099 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8100 ExtraArgs.D.getIdentifierLoc());
8101 Previous.clear();
8102 Previous.setLookupName(Correction.getCorrection());
8103 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8104 CDeclEnd = Correction.end();
8105 CDecl != CDeclEnd; ++CDecl) {
8106 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8107 if (FD && !FD->hasBody() &&
8108 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8109 Previous.addDecl(FD);
8110 }
8111 }
8112 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8113
8114 NamedDecl *Result;
8115 // Retry building the function declaration with the new previous
8116 // declarations, and with errors suppressed.
8117 {
8118 // Trap errors.
8119 Sema::SFINAETrap Trap(SemaRef);
8120
8121 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8122 // pieces need to verify the typo-corrected C++ declaration and hopefully
8123 // eliminate the need for the parameter pack ExtraArgs.
8124 Result = SemaRef.ActOnFunctionDeclarator(
8125 ExtraArgs.S, ExtraArgs.D,
8126 Correction.getCorrectionDecl()->getDeclContext(),
8127 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8128 ExtraArgs.AddToScope);
8129
8130 if (Trap.hasErrorOccurred())
8131 Result = nullptr;
8132 }
8133
8134 if (Result) {
8135 // Determine which correction we picked.
8136 Decl *Canonical = Result->getCanonicalDecl();
8137 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8138 I != E; ++I)
8139 if ((*I)->getCanonicalDecl() == Canonical)
8140 Correction.setCorrectionDecl(*I);
8141
8142 // Let Sema know about the correction.
8143 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8144 SemaRef.diagnoseTypo(
8145 Correction,
8146 SemaRef.PDiag(IsLocalFriend
8147 ? diag::err_no_matching_local_friend_suggest
8148 : diag::err_member_decl_does_not_match_suggest)
8149 << Name << NewDC << IsDefinition);
8150 return Result;
8151 }
8152
8153 // Pretend the typo correction never occurred
8154 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8155 ExtraArgs.D.getIdentifierLoc());
8156 ExtraArgs.D.setRedeclaration(wasRedeclaration);
8157 Previous.clear();
8158 Previous.setLookupName(Name);
8159 }
8160
8161 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8162 << Name << NewDC << IsDefinition << NewFD->getLocation();
8163
8164 bool NewFDisConst = false;
8165 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8166 NewFDisConst = NewMD->isConst();
8167
8168 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8169 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8170 NearMatch != NearMatchEnd; ++NearMatch) {
8171 FunctionDecl *FD = NearMatch->first;
8172 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8173 bool FDisConst = MD && MD->isConst();
8174 bool IsMember = MD || !IsLocalFriend;
8175
8176 // FIXME: These notes are poorly worded for the local friend case.
8177 if (unsigned Idx = NearMatch->second) {
8178 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8179 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8180 if (Loc.isInvalid()) Loc = FD->getLocation();
8181 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8182 : diag::note_local_decl_close_param_match)
8183 << Idx << FDParam->getType()
8184 << NewFD->getParamDecl(Idx - 1)->getType();
8185 } else if (FDisConst != NewFDisConst) {
8186 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8187 << NewFDisConst << FD->getSourceRange().getEnd();
8188 } else
8189 SemaRef.Diag(FD->getLocation(),
8190 IsMember ? diag::note_member_def_close_match
8191 : diag::note_local_decl_close_match);
8192 }
8193 return nullptr;
8194 }
8195
getFunctionStorageClass(Sema & SemaRef,Declarator & D)8196 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8197 switch (D.getDeclSpec().getStorageClassSpec()) {
8198 default: llvm_unreachable("Unknown storage class!");
8199 case DeclSpec::SCS_auto:
8200 case DeclSpec::SCS_register:
8201 case DeclSpec::SCS_mutable:
8202 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8203 diag::err_typecheck_sclass_func);
8204 D.getMutableDeclSpec().ClearStorageClassSpecs();
8205 D.setInvalidType();
8206 break;
8207 case DeclSpec::SCS_unspecified: break;
8208 case DeclSpec::SCS_extern:
8209 if (D.getDeclSpec().isExternInLinkageSpec())
8210 return SC_None;
8211 return SC_Extern;
8212 case DeclSpec::SCS_static: {
8213 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8214 // C99 6.7.1p5:
8215 // The declaration of an identifier for a function that has
8216 // block scope shall have no explicit storage-class specifier
8217 // other than extern
8218 // See also (C++ [dcl.stc]p4).
8219 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8220 diag::err_static_block_func);
8221 break;
8222 } else
8223 return SC_Static;
8224 }
8225 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8226 }
8227
8228 // No explicit storage class has already been returned
8229 return SC_None;
8230 }
8231
CreateNewFunctionDecl(Sema & SemaRef,Declarator & D,DeclContext * DC,QualType & R,TypeSourceInfo * TInfo,StorageClass SC,bool & IsVirtualOkay)8232 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8233 DeclContext *DC, QualType &R,
8234 TypeSourceInfo *TInfo,
8235 StorageClass SC,
8236 bool &IsVirtualOkay) {
8237 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8238 DeclarationName Name = NameInfo.getName();
8239
8240 FunctionDecl *NewFD = nullptr;
8241 bool isInline = D.getDeclSpec().isInlineSpecified();
8242
8243 if (!SemaRef.getLangOpts().CPlusPlus) {
8244 // Determine whether the function was written with a
8245 // prototype. This true when:
8246 // - there is a prototype in the declarator, or
8247 // - the type R of the function is some kind of typedef or other non-
8248 // attributed reference to a type name (which eventually refers to a
8249 // function type).
8250 bool HasPrototype =
8251 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8252 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8253
8254 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8255 R, TInfo, SC, isInline, HasPrototype,
8256 CSK_unspecified,
8257 /*TrailingRequiresClause=*/nullptr);
8258 if (D.isInvalidType())
8259 NewFD->setInvalidDecl();
8260
8261 return NewFD;
8262 }
8263
8264 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8265
8266 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8267 if (ConstexprKind == CSK_constinit) {
8268 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8269 diag::err_constexpr_wrong_decl_kind)
8270 << ConstexprKind;
8271 ConstexprKind = CSK_unspecified;
8272 D.getMutableDeclSpec().ClearConstexprSpec();
8273 }
8274 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8275
8276 // Check that the return type is not an abstract class type.
8277 // For record types, this is done by the AbstractClassUsageDiagnoser once
8278 // the class has been completely parsed.
8279 if (!DC->isRecord() &&
8280 SemaRef.RequireNonAbstractType(
8281 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8282 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8283 D.setInvalidType();
8284
8285 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8286 // This is a C++ constructor declaration.
8287 assert(DC->isRecord() &&
8288 "Constructors can only be declared in a member context");
8289
8290 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8291 return CXXConstructorDecl::Create(
8292 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8293 TInfo, ExplicitSpecifier, isInline,
8294 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8295 TrailingRequiresClause);
8296
8297 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8298 // This is a C++ destructor declaration.
8299 if (DC->isRecord()) {
8300 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8301 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8302 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8303 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8304 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8305 TrailingRequiresClause);
8306
8307 // If the destructor needs an implicit exception specification, set it
8308 // now. FIXME: It'd be nice to be able to create the right type to start
8309 // with, but the type needs to reference the destructor declaration.
8310 if (SemaRef.getLangOpts().CPlusPlus11)
8311 SemaRef.AdjustDestructorExceptionSpec(NewDD);
8312
8313 IsVirtualOkay = true;
8314 return NewDD;
8315
8316 } else {
8317 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8318 D.setInvalidType();
8319
8320 // Create a FunctionDecl to satisfy the function definition parsing
8321 // code path.
8322 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8323 D.getIdentifierLoc(), Name, R, TInfo, SC,
8324 isInline,
8325 /*hasPrototype=*/true, ConstexprKind,
8326 TrailingRequiresClause);
8327 }
8328
8329 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8330 if (!DC->isRecord()) {
8331 SemaRef.Diag(D.getIdentifierLoc(),
8332 diag::err_conv_function_not_member);
8333 return nullptr;
8334 }
8335
8336 SemaRef.CheckConversionDeclarator(D, R, SC);
8337 if (D.isInvalidType())
8338 return nullptr;
8339
8340 IsVirtualOkay = true;
8341 return CXXConversionDecl::Create(
8342 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8343 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8344 TrailingRequiresClause);
8345
8346 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8347 if (TrailingRequiresClause)
8348 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8349 diag::err_trailing_requires_clause_on_deduction_guide)
8350 << TrailingRequiresClause->getSourceRange();
8351 SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8352
8353 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8354 ExplicitSpecifier, NameInfo, R, TInfo,
8355 D.getEndLoc());
8356 } else if (DC->isRecord()) {
8357 // If the name of the function is the same as the name of the record,
8358 // then this must be an invalid constructor that has a return type.
8359 // (The parser checks for a return type and makes the declarator a
8360 // constructor if it has no return type).
8361 if (Name.getAsIdentifierInfo() &&
8362 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8363 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8364 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8365 << SourceRange(D.getIdentifierLoc());
8366 return nullptr;
8367 }
8368
8369 // This is a C++ method declaration.
8370 CXXMethodDecl *Ret = CXXMethodDecl::Create(
8371 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8372 TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8373 TrailingRequiresClause);
8374 IsVirtualOkay = !Ret->isStatic();
8375 return Ret;
8376 } else {
8377 bool isFriend =
8378 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8379 if (!isFriend && SemaRef.CurContext->isRecord())
8380 return nullptr;
8381
8382 // Determine whether the function was written with a
8383 // prototype. This true when:
8384 // - we're in C++ (where every function has a prototype),
8385 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8386 R, TInfo, SC, isInline, true /*HasPrototype*/,
8387 ConstexprKind, TrailingRequiresClause);
8388 }
8389 }
8390
8391 enum OpenCLParamType {
8392 ValidKernelParam,
8393 PtrPtrKernelParam,
8394 PtrKernelParam,
8395 InvalidAddrSpacePtrKernelParam,
8396 InvalidKernelParam,
8397 RecordKernelParam
8398 };
8399
isOpenCLSizeDependentType(ASTContext & C,QualType Ty)8400 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8401 // Size dependent types are just typedefs to normal integer types
8402 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8403 // integers other than by their names.
8404 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8405
8406 // Remove typedefs one by one until we reach a typedef
8407 // for a size dependent type.
8408 QualType DesugaredTy = Ty;
8409 do {
8410 ArrayRef<StringRef> Names(SizeTypeNames);
8411 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8412 if (Names.end() != Match)
8413 return true;
8414
8415 Ty = DesugaredTy;
8416 DesugaredTy = Ty.getSingleStepDesugaredType(C);
8417 } while (DesugaredTy != Ty);
8418
8419 return false;
8420 }
8421
getOpenCLKernelParameterType(Sema & S,QualType PT)8422 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8423 if (PT->isPointerType()) {
8424 QualType PointeeType = PT->getPointeeType();
8425 if (PointeeType->isPointerType())
8426 return PtrPtrKernelParam;
8427 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8428 PointeeType.getAddressSpace() == LangAS::opencl_private ||
8429 PointeeType.getAddressSpace() == LangAS::Default)
8430 return InvalidAddrSpacePtrKernelParam;
8431 return PtrKernelParam;
8432 }
8433
8434 // OpenCL v1.2 s6.9.k:
8435 // Arguments to kernel functions in a program cannot be declared with the
8436 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8437 // uintptr_t or a struct and/or union that contain fields declared to be one
8438 // of these built-in scalar types.
8439 if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8440 return InvalidKernelParam;
8441
8442 if (PT->isImageType())
8443 return PtrKernelParam;
8444
8445 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8446 return InvalidKernelParam;
8447
8448 // OpenCL extension spec v1.2 s9.5:
8449 // This extension adds support for half scalar and vector types as built-in
8450 // types that can be used for arithmetic operations, conversions etc.
8451 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8452 return InvalidKernelParam;
8453
8454 if (PT->isRecordType())
8455 return RecordKernelParam;
8456
8457 // Look into an array argument to check if it has a forbidden type.
8458 if (PT->isArrayType()) {
8459 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8460 // Call ourself to check an underlying type of an array. Since the
8461 // getPointeeOrArrayElementType returns an innermost type which is not an
8462 // array, this recursive call only happens once.
8463 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8464 }
8465
8466 return ValidKernelParam;
8467 }
8468
checkIsValidOpenCLKernelParameter(Sema & S,Declarator & D,ParmVarDecl * Param,llvm::SmallPtrSetImpl<const Type * > & ValidTypes)8469 static void checkIsValidOpenCLKernelParameter(
8470 Sema &S,
8471 Declarator &D,
8472 ParmVarDecl *Param,
8473 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8474 QualType PT = Param->getType();
8475
8476 // Cache the valid types we encounter to avoid rechecking structs that are
8477 // used again
8478 if (ValidTypes.count(PT.getTypePtr()))
8479 return;
8480
8481 switch (getOpenCLKernelParameterType(S, PT)) {
8482 case PtrPtrKernelParam:
8483 // OpenCL v1.2 s6.9.a:
8484 // A kernel function argument cannot be declared as a
8485 // pointer to a pointer type.
8486 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8487 D.setInvalidType();
8488 return;
8489
8490 case InvalidAddrSpacePtrKernelParam:
8491 // OpenCL v1.0 s6.5:
8492 // __kernel function arguments declared to be a pointer of a type can point
8493 // to one of the following address spaces only : __global, __local or
8494 // __constant.
8495 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8496 D.setInvalidType();
8497 return;
8498
8499 // OpenCL v1.2 s6.9.k:
8500 // Arguments to kernel functions in a program cannot be declared with the
8501 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8502 // uintptr_t or a struct and/or union that contain fields declared to be
8503 // one of these built-in scalar types.
8504
8505 case InvalidKernelParam:
8506 // OpenCL v1.2 s6.8 n:
8507 // A kernel function argument cannot be declared
8508 // of event_t type.
8509 // Do not diagnose half type since it is diagnosed as invalid argument
8510 // type for any function elsewhere.
8511 if (!PT->isHalfType()) {
8512 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8513
8514 // Explain what typedefs are involved.
8515 const TypedefType *Typedef = nullptr;
8516 while ((Typedef = PT->getAs<TypedefType>())) {
8517 SourceLocation Loc = Typedef->getDecl()->getLocation();
8518 // SourceLocation may be invalid for a built-in type.
8519 if (Loc.isValid())
8520 S.Diag(Loc, diag::note_entity_declared_at) << PT;
8521 PT = Typedef->desugar();
8522 }
8523 }
8524
8525 D.setInvalidType();
8526 return;
8527
8528 case PtrKernelParam:
8529 case ValidKernelParam:
8530 ValidTypes.insert(PT.getTypePtr());
8531 return;
8532
8533 case RecordKernelParam:
8534 break;
8535 }
8536
8537 // Track nested structs we will inspect
8538 SmallVector<const Decl *, 4> VisitStack;
8539
8540 // Track where we are in the nested structs. Items will migrate from
8541 // VisitStack to HistoryStack as we do the DFS for bad field.
8542 SmallVector<const FieldDecl *, 4> HistoryStack;
8543 HistoryStack.push_back(nullptr);
8544
8545 // At this point we already handled everything except of a RecordType or
8546 // an ArrayType of a RecordType.
8547 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8548 const RecordType *RecTy =
8549 PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8550 const RecordDecl *OrigRecDecl = RecTy->getDecl();
8551
8552 VisitStack.push_back(RecTy->getDecl());
8553 assert(VisitStack.back() && "First decl null?");
8554
8555 do {
8556 const Decl *Next = VisitStack.pop_back_val();
8557 if (!Next) {
8558 assert(!HistoryStack.empty());
8559 // Found a marker, we have gone up a level
8560 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8561 ValidTypes.insert(Hist->getType().getTypePtr());
8562
8563 continue;
8564 }
8565
8566 // Adds everything except the original parameter declaration (which is not a
8567 // field itself) to the history stack.
8568 const RecordDecl *RD;
8569 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8570 HistoryStack.push_back(Field);
8571
8572 QualType FieldTy = Field->getType();
8573 // Other field types (known to be valid or invalid) are handled while we
8574 // walk around RecordDecl::fields().
8575 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8576 "Unexpected type.");
8577 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8578
8579 RD = FieldRecTy->castAs<RecordType>()->getDecl();
8580 } else {
8581 RD = cast<RecordDecl>(Next);
8582 }
8583
8584 // Add a null marker so we know when we've gone back up a level
8585 VisitStack.push_back(nullptr);
8586
8587 for (const auto *FD : RD->fields()) {
8588 QualType QT = FD->getType();
8589
8590 if (ValidTypes.count(QT.getTypePtr()))
8591 continue;
8592
8593 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8594 if (ParamType == ValidKernelParam)
8595 continue;
8596
8597 if (ParamType == RecordKernelParam) {
8598 VisitStack.push_back(FD);
8599 continue;
8600 }
8601
8602 // OpenCL v1.2 s6.9.p:
8603 // Arguments to kernel functions that are declared to be a struct or union
8604 // do not allow OpenCL objects to be passed as elements of the struct or
8605 // union.
8606 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8607 ParamType == InvalidAddrSpacePtrKernelParam) {
8608 S.Diag(Param->getLocation(),
8609 diag::err_record_with_pointers_kernel_param)
8610 << PT->isUnionType()
8611 << PT;
8612 } else {
8613 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8614 }
8615
8616 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8617 << OrigRecDecl->getDeclName();
8618
8619 // We have an error, now let's go back up through history and show where
8620 // the offending field came from
8621 for (ArrayRef<const FieldDecl *>::const_iterator
8622 I = HistoryStack.begin() + 1,
8623 E = HistoryStack.end();
8624 I != E; ++I) {
8625 const FieldDecl *OuterField = *I;
8626 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8627 << OuterField->getType();
8628 }
8629
8630 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8631 << QT->isPointerType()
8632 << QT;
8633 D.setInvalidType();
8634 return;
8635 }
8636 } while (!VisitStack.empty());
8637 }
8638
8639 /// Find the DeclContext in which a tag is implicitly declared if we see an
8640 /// elaborated type specifier in the specified context, and lookup finds
8641 /// nothing.
getTagInjectionContext(DeclContext * DC)8642 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8643 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8644 DC = DC->getParent();
8645 return DC;
8646 }
8647
8648 /// Find the Scope in which a tag is implicitly declared if we see an
8649 /// elaborated type specifier in the specified context, and lookup finds
8650 /// nothing.
getTagInjectionScope(Scope * S,const LangOptions & LangOpts)8651 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8652 while (S->isClassScope() ||
8653 (LangOpts.CPlusPlus &&
8654 S->isFunctionPrototypeScope()) ||
8655 ((S->getFlags() & Scope::DeclScope) == 0) ||
8656 (S->getEntity() && S->getEntity()->isTransparentContext()))
8657 S = S->getParent();
8658 return S;
8659 }
8660
8661 NamedDecl*
ActOnFunctionDeclarator(Scope * S,Declarator & D,DeclContext * DC,TypeSourceInfo * TInfo,LookupResult & Previous,MultiTemplateParamsArg TemplateParamListsRef,bool & AddToScope)8662 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8663 TypeSourceInfo *TInfo, LookupResult &Previous,
8664 MultiTemplateParamsArg TemplateParamListsRef,
8665 bool &AddToScope) {
8666 QualType R = TInfo->getType();
8667
8668 assert(R->isFunctionType());
8669 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
8670 for (TemplateParameterList *TPL : TemplateParamListsRef)
8671 TemplateParamLists.push_back(TPL);
8672 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
8673 if (!TemplateParamLists.empty() &&
8674 Invented->getDepth() == TemplateParamLists.back()->getDepth())
8675 TemplateParamLists.back() = Invented;
8676 else
8677 TemplateParamLists.push_back(Invented);
8678 }
8679
8680 // TODO: consider using NameInfo for diagnostic.
8681 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8682 DeclarationName Name = NameInfo.getName();
8683 StorageClass SC = getFunctionStorageClass(*this, D);
8684
8685 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8686 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8687 diag::err_invalid_thread)
8688 << DeclSpec::getSpecifierName(TSCS);
8689
8690 if (D.isFirstDeclarationOfMember())
8691 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8692 D.getIdentifierLoc());
8693
8694 bool isFriend = false;
8695 FunctionTemplateDecl *FunctionTemplate = nullptr;
8696 bool isMemberSpecialization = false;
8697 bool isFunctionTemplateSpecialization = false;
8698
8699 bool isDependentClassScopeExplicitSpecialization = false;
8700 bool HasExplicitTemplateArgs = false;
8701 TemplateArgumentListInfo TemplateArgs;
8702
8703 bool isVirtualOkay = false;
8704
8705 DeclContext *OriginalDC = DC;
8706 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8707
8708 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8709 isVirtualOkay);
8710 if (!NewFD) return nullptr;
8711
8712 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8713 NewFD->setTopLevelDeclInObjCContainer();
8714
8715 // Set the lexical context. If this is a function-scope declaration, or has a
8716 // C++ scope specifier, or is the object of a friend declaration, the lexical
8717 // context will be different from the semantic context.
8718 NewFD->setLexicalDeclContext(CurContext);
8719
8720 if (IsLocalExternDecl)
8721 NewFD->setLocalExternDecl();
8722
8723 if (getLangOpts().CPlusPlus) {
8724 bool isInline = D.getDeclSpec().isInlineSpecified();
8725 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8726 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8727 isFriend = D.getDeclSpec().isFriendSpecified();
8728 if (isFriend && !isInline && D.isFunctionDefinition()) {
8729 // C++ [class.friend]p5
8730 // A function can be defined in a friend declaration of a
8731 // class . . . . Such a function is implicitly inline.
8732 NewFD->setImplicitlyInline();
8733 }
8734
8735 // If this is a method defined in an __interface, and is not a constructor
8736 // or an overloaded operator, then set the pure flag (isVirtual will already
8737 // return true).
8738 if (const CXXRecordDecl *Parent =
8739 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8740 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8741 NewFD->setPure(true);
8742
8743 // C++ [class.union]p2
8744 // A union can have member functions, but not virtual functions.
8745 if (isVirtual && Parent->isUnion())
8746 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8747 }
8748
8749 SetNestedNameSpecifier(*this, NewFD, D);
8750 isMemberSpecialization = false;
8751 isFunctionTemplateSpecialization = false;
8752 if (D.isInvalidType())
8753 NewFD->setInvalidDecl();
8754
8755 // Match up the template parameter lists with the scope specifier, then
8756 // determine whether we have a template or a template specialization.
8757 bool Invalid = false;
8758 TemplateParameterList *TemplateParams =
8759 MatchTemplateParametersToScopeSpecifier(
8760 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8761 D.getCXXScopeSpec(),
8762 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8763 ? D.getName().TemplateId
8764 : nullptr,
8765 TemplateParamLists, isFriend, isMemberSpecialization,
8766 Invalid);
8767 if (TemplateParams) {
8768 if (TemplateParams->size() > 0) {
8769 // This is a function template
8770
8771 // Check that we can declare a template here.
8772 if (CheckTemplateDeclScope(S, TemplateParams))
8773 NewFD->setInvalidDecl();
8774
8775 // A destructor cannot be a template.
8776 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8777 Diag(NewFD->getLocation(), diag::err_destructor_template);
8778 NewFD->setInvalidDecl();
8779 }
8780
8781 // If we're adding a template to a dependent context, we may need to
8782 // rebuilding some of the types used within the template parameter list,
8783 // now that we know what the current instantiation is.
8784 if (DC->isDependentContext()) {
8785 ContextRAII SavedContext(*this, DC);
8786 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8787 Invalid = true;
8788 }
8789
8790 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8791 NewFD->getLocation(),
8792 Name, TemplateParams,
8793 NewFD);
8794 FunctionTemplate->setLexicalDeclContext(CurContext);
8795 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8796
8797 // For source fidelity, store the other template param lists.
8798 if (TemplateParamLists.size() > 1) {
8799 NewFD->setTemplateParameterListsInfo(Context,
8800 ArrayRef<TemplateParameterList *>(TemplateParamLists)
8801 .drop_back(1));
8802 }
8803 } else {
8804 // This is a function template specialization.
8805 isFunctionTemplateSpecialization = true;
8806 // For source fidelity, store all the template param lists.
8807 if (TemplateParamLists.size() > 0)
8808 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8809
8810 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8811 if (isFriend) {
8812 // We want to remove the "template<>", found here.
8813 SourceRange RemoveRange = TemplateParams->getSourceRange();
8814
8815 // If we remove the template<> and the name is not a
8816 // template-id, we're actually silently creating a problem:
8817 // the friend declaration will refer to an untemplated decl,
8818 // and clearly the user wants a template specialization. So
8819 // we need to insert '<>' after the name.
8820 SourceLocation InsertLoc;
8821 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8822 InsertLoc = D.getName().getSourceRange().getEnd();
8823 InsertLoc = getLocForEndOfToken(InsertLoc);
8824 }
8825
8826 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8827 << Name << RemoveRange
8828 << FixItHint::CreateRemoval(RemoveRange)
8829 << FixItHint::CreateInsertion(InsertLoc, "<>");
8830 }
8831 }
8832 } else {
8833 // All template param lists were matched against the scope specifier:
8834 // this is NOT (an explicit specialization of) a template.
8835 if (TemplateParamLists.size() > 0)
8836 // For source fidelity, store all the template param lists.
8837 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8838 }
8839
8840 if (Invalid) {
8841 NewFD->setInvalidDecl();
8842 if (FunctionTemplate)
8843 FunctionTemplate->setInvalidDecl();
8844 }
8845
8846 // C++ [dcl.fct.spec]p5:
8847 // The virtual specifier shall only be used in declarations of
8848 // nonstatic class member functions that appear within a
8849 // member-specification of a class declaration; see 10.3.
8850 //
8851 if (isVirtual && !NewFD->isInvalidDecl()) {
8852 if (!isVirtualOkay) {
8853 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8854 diag::err_virtual_non_function);
8855 } else if (!CurContext->isRecord()) {
8856 // 'virtual' was specified outside of the class.
8857 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8858 diag::err_virtual_out_of_class)
8859 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8860 } else if (NewFD->getDescribedFunctionTemplate()) {
8861 // C++ [temp.mem]p3:
8862 // A member function template shall not be virtual.
8863 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8864 diag::err_virtual_member_function_template)
8865 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8866 } else {
8867 // Okay: Add virtual to the method.
8868 NewFD->setVirtualAsWritten(true);
8869 }
8870
8871 if (getLangOpts().CPlusPlus14 &&
8872 NewFD->getReturnType()->isUndeducedType())
8873 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8874 }
8875
8876 if (getLangOpts().CPlusPlus14 &&
8877 (NewFD->isDependentContext() ||
8878 (isFriend && CurContext->isDependentContext())) &&
8879 NewFD->getReturnType()->isUndeducedType()) {
8880 // If the function template is referenced directly (for instance, as a
8881 // member of the current instantiation), pretend it has a dependent type.
8882 // This is not really justified by the standard, but is the only sane
8883 // thing to do.
8884 // FIXME: For a friend function, we have not marked the function as being
8885 // a friend yet, so 'isDependentContext' on the FD doesn't work.
8886 const FunctionProtoType *FPT =
8887 NewFD->getType()->castAs<FunctionProtoType>();
8888 QualType Result =
8889 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8890 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8891 FPT->getExtProtoInfo()));
8892 }
8893
8894 // C++ [dcl.fct.spec]p3:
8895 // The inline specifier shall not appear on a block scope function
8896 // declaration.
8897 if (isInline && !NewFD->isInvalidDecl()) {
8898 if (CurContext->isFunctionOrMethod()) {
8899 // 'inline' is not allowed on block scope function declaration.
8900 Diag(D.getDeclSpec().getInlineSpecLoc(),
8901 diag::err_inline_declaration_block_scope) << Name
8902 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8903 }
8904 }
8905
8906 // C++ [dcl.fct.spec]p6:
8907 // The explicit specifier shall be used only in the declaration of a
8908 // constructor or conversion function within its class definition;
8909 // see 12.3.1 and 12.3.2.
8910 if (hasExplicit && !NewFD->isInvalidDecl() &&
8911 !isa<CXXDeductionGuideDecl>(NewFD)) {
8912 if (!CurContext->isRecord()) {
8913 // 'explicit' was specified outside of the class.
8914 Diag(D.getDeclSpec().getExplicitSpecLoc(),
8915 diag::err_explicit_out_of_class)
8916 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8917 } else if (!isa<CXXConstructorDecl>(NewFD) &&
8918 !isa<CXXConversionDecl>(NewFD)) {
8919 // 'explicit' was specified on a function that wasn't a constructor
8920 // or conversion function.
8921 Diag(D.getDeclSpec().getExplicitSpecLoc(),
8922 diag::err_explicit_non_ctor_or_conv_function)
8923 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8924 }
8925 }
8926
8927 if (ConstexprSpecKind ConstexprKind =
8928 D.getDeclSpec().getConstexprSpecifier()) {
8929 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8930 // are implicitly inline.
8931 NewFD->setImplicitlyInline();
8932
8933 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8934 // be either constructors or to return a literal type. Therefore,
8935 // destructors cannot be declared constexpr.
8936 if (isa<CXXDestructorDecl>(NewFD) && !getLangOpts().CPlusPlus2a) {
8937 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
8938 << ConstexprKind;
8939 }
8940 }
8941
8942 // If __module_private__ was specified, mark the function accordingly.
8943 if (D.getDeclSpec().isModulePrivateSpecified()) {
8944 if (isFunctionTemplateSpecialization) {
8945 SourceLocation ModulePrivateLoc
8946 = D.getDeclSpec().getModulePrivateSpecLoc();
8947 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8948 << 0
8949 << FixItHint::CreateRemoval(ModulePrivateLoc);
8950 } else {
8951 NewFD->setModulePrivate();
8952 if (FunctionTemplate)
8953 FunctionTemplate->setModulePrivate();
8954 }
8955 }
8956
8957 if (isFriend) {
8958 if (FunctionTemplate) {
8959 FunctionTemplate->setObjectOfFriendDecl();
8960 FunctionTemplate->setAccess(AS_public);
8961 }
8962 NewFD->setObjectOfFriendDecl();
8963 NewFD->setAccess(AS_public);
8964 }
8965
8966 // If a function is defined as defaulted or deleted, mark it as such now.
8967 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8968 // definition kind to FDK_Definition.
8969 switch (D.getFunctionDefinitionKind()) {
8970 case FDK_Declaration:
8971 case FDK_Definition:
8972 break;
8973
8974 case FDK_Defaulted:
8975 NewFD->setDefaulted();
8976 break;
8977
8978 case FDK_Deleted:
8979 NewFD->setDeletedAsWritten();
8980 break;
8981 }
8982
8983 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8984 D.isFunctionDefinition()) {
8985 // C++ [class.mfct]p2:
8986 // A member function may be defined (8.4) in its class definition, in
8987 // which case it is an inline member function (7.1.2)
8988 NewFD->setImplicitlyInline();
8989 }
8990
8991 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8992 !CurContext->isRecord()) {
8993 // C++ [class.static]p1:
8994 // A data or function member of a class may be declared static
8995 // in a class definition, in which case it is a static member of
8996 // the class.
8997
8998 // Complain about the 'static' specifier if it's on an out-of-line
8999 // member function definition.
9000
9001 // MSVC permits the use of a 'static' storage specifier on an out-of-line
9002 // member function template declaration and class member template
9003 // declaration (MSVC versions before 2015), warn about this.
9004 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9005 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9006 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9007 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9008 ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9009 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9010 }
9011
9012 // C++11 [except.spec]p15:
9013 // A deallocation function with no exception-specification is treated
9014 // as if it were specified with noexcept(true).
9015 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9016 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9017 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9018 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9019 NewFD->setType(Context.getFunctionType(
9020 FPT->getReturnType(), FPT->getParamTypes(),
9021 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9022 }
9023
9024 // Filter out previous declarations that don't match the scope.
9025 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9026 D.getCXXScopeSpec().isNotEmpty() ||
9027 isMemberSpecialization ||
9028 isFunctionTemplateSpecialization);
9029
9030 // Handle GNU asm-label extension (encoded as an attribute).
9031 if (Expr *E = (Expr*) D.getAsmLabel()) {
9032 // The parser guarantees this is a string.
9033 StringLiteral *SE = cast<StringLiteral>(E);
9034 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9035 /*IsLiteralLabel=*/true,
9036 SE->getStrTokenLoc(0)));
9037 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9038 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9039 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9040 if (I != ExtnameUndeclaredIdentifiers.end()) {
9041 if (isDeclExternC(NewFD)) {
9042 NewFD->addAttr(I->second);
9043 ExtnameUndeclaredIdentifiers.erase(I);
9044 } else
9045 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9046 << /*Variable*/0 << NewFD;
9047 }
9048 }
9049
9050 // Copy the parameter declarations from the declarator D to the function
9051 // declaration NewFD, if they are available. First scavenge them into Params.
9052 SmallVector<ParmVarDecl*, 16> Params;
9053 unsigned FTIIdx;
9054 if (D.isFunctionDeclarator(FTIIdx)) {
9055 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9056
9057 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9058 // function that takes no arguments, not a function that takes a
9059 // single void argument.
9060 // We let through "const void" here because Sema::GetTypeForDeclarator
9061 // already checks for that case.
9062 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9063 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9064 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9065 assert(Param->getDeclContext() != NewFD && "Was set before ?");
9066 Param->setDeclContext(NewFD);
9067 Params.push_back(Param);
9068
9069 if (Param->isInvalidDecl())
9070 NewFD->setInvalidDecl();
9071 }
9072 }
9073
9074 if (!getLangOpts().CPlusPlus) {
9075 // In C, find all the tag declarations from the prototype and move them
9076 // into the function DeclContext. Remove them from the surrounding tag
9077 // injection context of the function, which is typically but not always
9078 // the TU.
9079 DeclContext *PrototypeTagContext =
9080 getTagInjectionContext(NewFD->getLexicalDeclContext());
9081 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9082 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9083
9084 // We don't want to reparent enumerators. Look at their parent enum
9085 // instead.
9086 if (!TD) {
9087 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9088 TD = cast<EnumDecl>(ECD->getDeclContext());
9089 }
9090 if (!TD)
9091 continue;
9092 DeclContext *TagDC = TD->getLexicalDeclContext();
9093 if (!TagDC->containsDecl(TD))
9094 continue;
9095 TagDC->removeDecl(TD);
9096 TD->setDeclContext(NewFD);
9097 NewFD->addDecl(TD);
9098
9099 // Preserve the lexical DeclContext if it is not the surrounding tag
9100 // injection context of the FD. In this example, the semantic context of
9101 // E will be f and the lexical context will be S, while both the
9102 // semantic and lexical contexts of S will be f:
9103 // void f(struct S { enum E { a } f; } s);
9104 if (TagDC != PrototypeTagContext)
9105 TD->setLexicalDeclContext(TagDC);
9106 }
9107 }
9108 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9109 // When we're declaring a function with a typedef, typeof, etc as in the
9110 // following example, we'll need to synthesize (unnamed)
9111 // parameters for use in the declaration.
9112 //
9113 // @code
9114 // typedef void fn(int);
9115 // fn f;
9116 // @endcode
9117
9118 // Synthesize a parameter for each argument type.
9119 for (const auto &AI : FT->param_types()) {
9120 ParmVarDecl *Param =
9121 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9122 Param->setScopeInfo(0, Params.size());
9123 Params.push_back(Param);
9124 }
9125 } else {
9126 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9127 "Should not need args for typedef of non-prototype fn");
9128 }
9129
9130 // Finally, we know we have the right number of parameters, install them.
9131 NewFD->setParams(Params);
9132
9133 if (D.getDeclSpec().isNoreturnSpecified())
9134 NewFD->addAttr(C11NoReturnAttr::Create(Context,
9135 D.getDeclSpec().getNoreturnSpecLoc(),
9136 AttributeCommonInfo::AS_Keyword));
9137
9138 // Functions returning a variably modified type violate C99 6.7.5.2p2
9139 // because all functions have linkage.
9140 if (!NewFD->isInvalidDecl() &&
9141 NewFD->getReturnType()->isVariablyModifiedType()) {
9142 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9143 NewFD->setInvalidDecl();
9144 }
9145
9146 // Apply an implicit SectionAttr if '#pragma clang section text' is active
9147 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9148 !NewFD->hasAttr<SectionAttr>())
9149 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9150 Context, PragmaClangTextSection.SectionName,
9151 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9152
9153 // Apply an implicit SectionAttr if #pragma code_seg is active.
9154 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9155 !NewFD->hasAttr<SectionAttr>()) {
9156 NewFD->addAttr(SectionAttr::CreateImplicit(
9157 Context, CodeSegStack.CurrentValue->getString(),
9158 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9159 SectionAttr::Declspec_allocate));
9160 if (UnifySection(CodeSegStack.CurrentValue->getString(),
9161 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9162 ASTContext::PSF_Read,
9163 NewFD))
9164 NewFD->dropAttr<SectionAttr>();
9165 }
9166
9167 // Apply an implicit CodeSegAttr from class declspec or
9168 // apply an implicit SectionAttr from #pragma code_seg if active.
9169 if (!NewFD->hasAttr<CodeSegAttr>()) {
9170 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9171 D.isFunctionDefinition())) {
9172 NewFD->addAttr(SAttr);
9173 }
9174 }
9175
9176 // Handle attributes.
9177 ProcessDeclAttributes(S, NewFD, D);
9178
9179 if (getLangOpts().OpenCL) {
9180 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9181 // type declaration will generate a compilation error.
9182 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9183 if (AddressSpace != LangAS::Default) {
9184 Diag(NewFD->getLocation(),
9185 diag::err_opencl_return_value_with_address_space);
9186 NewFD->setInvalidDecl();
9187 }
9188 }
9189
9190 if (!getLangOpts().CPlusPlus) {
9191 // Perform semantic checking on the function declaration.
9192 if (!NewFD->isInvalidDecl() && NewFD->isMain())
9193 CheckMain(NewFD, D.getDeclSpec());
9194
9195 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9196 CheckMSVCRTEntryPoint(NewFD);
9197
9198 if (!NewFD->isInvalidDecl())
9199 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9200 isMemberSpecialization));
9201 else if (!Previous.empty())
9202 // Recover gracefully from an invalid redeclaration.
9203 D.setRedeclaration(true);
9204 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9205 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9206 "previous declaration set still overloaded");
9207
9208 // Diagnose no-prototype function declarations with calling conventions that
9209 // don't support variadic calls. Only do this in C and do it after merging
9210 // possibly prototyped redeclarations.
9211 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9212 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9213 CallingConv CC = FT->getExtInfo().getCC();
9214 if (!supportsVariadicCall(CC)) {
9215 // Windows system headers sometimes accidentally use stdcall without
9216 // (void) parameters, so we relax this to a warning.
9217 int DiagID =
9218 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9219 Diag(NewFD->getLocation(), DiagID)
9220 << FunctionType::getNameForCallConv(CC);
9221 }
9222 }
9223
9224 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9225 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9226 checkNonTrivialCUnion(NewFD->getReturnType(),
9227 NewFD->getReturnTypeSourceRange().getBegin(),
9228 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9229 } else {
9230 // C++11 [replacement.functions]p3:
9231 // The program's definitions shall not be specified as inline.
9232 //
9233 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9234 //
9235 // Suppress the diagnostic if the function is __attribute__((used)), since
9236 // that forces an external definition to be emitted.
9237 if (D.getDeclSpec().isInlineSpecified() &&
9238 NewFD->isReplaceableGlobalAllocationFunction() &&
9239 !NewFD->hasAttr<UsedAttr>())
9240 Diag(D.getDeclSpec().getInlineSpecLoc(),
9241 diag::ext_operator_new_delete_declared_inline)
9242 << NewFD->getDeclName();
9243
9244 // If the declarator is a template-id, translate the parser's template
9245 // argument list into our AST format.
9246 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9247 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9248 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9249 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9250 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9251 TemplateId->NumArgs);
9252 translateTemplateArguments(TemplateArgsPtr,
9253 TemplateArgs);
9254
9255 HasExplicitTemplateArgs = true;
9256
9257 if (NewFD->isInvalidDecl()) {
9258 HasExplicitTemplateArgs = false;
9259 } else if (FunctionTemplate) {
9260 // Function template with explicit template arguments.
9261 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9262 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9263
9264 HasExplicitTemplateArgs = false;
9265 } else {
9266 assert((isFunctionTemplateSpecialization ||
9267 D.getDeclSpec().isFriendSpecified()) &&
9268 "should have a 'template<>' for this decl");
9269 // "friend void foo<>(int);" is an implicit specialization decl.
9270 isFunctionTemplateSpecialization = true;
9271 }
9272 } else if (isFriend && isFunctionTemplateSpecialization) {
9273 // This combination is only possible in a recovery case; the user
9274 // wrote something like:
9275 // template <> friend void foo(int);
9276 // which we're recovering from as if the user had written:
9277 // friend void foo<>(int);
9278 // Go ahead and fake up a template id.
9279 HasExplicitTemplateArgs = true;
9280 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9281 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9282 }
9283
9284 // We do not add HD attributes to specializations here because
9285 // they may have different constexpr-ness compared to their
9286 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9287 // may end up with different effective targets. Instead, a
9288 // specialization inherits its target attributes from its template
9289 // in the CheckFunctionTemplateSpecialization() call below.
9290 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9291 maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9292
9293 // If it's a friend (and only if it's a friend), it's possible
9294 // that either the specialized function type or the specialized
9295 // template is dependent, and therefore matching will fail. In
9296 // this case, don't check the specialization yet.
9297 bool InstantiationDependent = false;
9298 if (isFunctionTemplateSpecialization && isFriend &&
9299 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9300 TemplateSpecializationType::anyDependentTemplateArguments(
9301 TemplateArgs,
9302 InstantiationDependent))) {
9303 assert(HasExplicitTemplateArgs &&
9304 "friend function specialization without template args");
9305 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9306 Previous))
9307 NewFD->setInvalidDecl();
9308 } else if (isFunctionTemplateSpecialization) {
9309 if (CurContext->isDependentContext() && CurContext->isRecord()
9310 && !isFriend) {
9311 isDependentClassScopeExplicitSpecialization = true;
9312 } else if (!NewFD->isInvalidDecl() &&
9313 CheckFunctionTemplateSpecialization(
9314 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9315 Previous))
9316 NewFD->setInvalidDecl();
9317
9318 // C++ [dcl.stc]p1:
9319 // A storage-class-specifier shall not be specified in an explicit
9320 // specialization (14.7.3)
9321 FunctionTemplateSpecializationInfo *Info =
9322 NewFD->getTemplateSpecializationInfo();
9323 if (Info && SC != SC_None) {
9324 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9325 Diag(NewFD->getLocation(),
9326 diag::err_explicit_specialization_inconsistent_storage_class)
9327 << SC
9328 << FixItHint::CreateRemoval(
9329 D.getDeclSpec().getStorageClassSpecLoc());
9330
9331 else
9332 Diag(NewFD->getLocation(),
9333 diag::ext_explicit_specialization_storage_class)
9334 << FixItHint::CreateRemoval(
9335 D.getDeclSpec().getStorageClassSpecLoc());
9336 }
9337 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9338 if (CheckMemberSpecialization(NewFD, Previous))
9339 NewFD->setInvalidDecl();
9340 }
9341
9342 // Perform semantic checking on the function declaration.
9343 if (!isDependentClassScopeExplicitSpecialization) {
9344 if (!NewFD->isInvalidDecl() && NewFD->isMain())
9345 CheckMain(NewFD, D.getDeclSpec());
9346
9347 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9348 CheckMSVCRTEntryPoint(NewFD);
9349
9350 if (!NewFD->isInvalidDecl())
9351 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9352 isMemberSpecialization));
9353 else if (!Previous.empty())
9354 // Recover gracefully from an invalid redeclaration.
9355 D.setRedeclaration(true);
9356 }
9357
9358 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9359 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9360 "previous declaration set still overloaded");
9361
9362 NamedDecl *PrincipalDecl = (FunctionTemplate
9363 ? cast<NamedDecl>(FunctionTemplate)
9364 : NewFD);
9365
9366 if (isFriend && NewFD->getPreviousDecl()) {
9367 AccessSpecifier Access = AS_public;
9368 if (!NewFD->isInvalidDecl())
9369 Access = NewFD->getPreviousDecl()->getAccess();
9370
9371 NewFD->setAccess(Access);
9372 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9373 }
9374
9375 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9376 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9377 PrincipalDecl->setNonMemberOperator();
9378
9379 // If we have a function template, check the template parameter
9380 // list. This will check and merge default template arguments.
9381 if (FunctionTemplate) {
9382 FunctionTemplateDecl *PrevTemplate =
9383 FunctionTemplate->getPreviousDecl();
9384 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9385 PrevTemplate ? PrevTemplate->getTemplateParameters()
9386 : nullptr,
9387 D.getDeclSpec().isFriendSpecified()
9388 ? (D.isFunctionDefinition()
9389 ? TPC_FriendFunctionTemplateDefinition
9390 : TPC_FriendFunctionTemplate)
9391 : (D.getCXXScopeSpec().isSet() &&
9392 DC && DC->isRecord() &&
9393 DC->isDependentContext())
9394 ? TPC_ClassTemplateMember
9395 : TPC_FunctionTemplate);
9396 }
9397
9398 if (NewFD->isInvalidDecl()) {
9399 // Ignore all the rest of this.
9400 } else if (!D.isRedeclaration()) {
9401 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9402 AddToScope };
9403 // Fake up an access specifier if it's supposed to be a class member.
9404 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9405 NewFD->setAccess(AS_public);
9406
9407 // Qualified decls generally require a previous declaration.
9408 if (D.getCXXScopeSpec().isSet()) {
9409 // ...with the major exception of templated-scope or
9410 // dependent-scope friend declarations.
9411
9412 // TODO: we currently also suppress this check in dependent
9413 // contexts because (1) the parameter depth will be off when
9414 // matching friend templates and (2) we might actually be
9415 // selecting a friend based on a dependent factor. But there
9416 // are situations where these conditions don't apply and we
9417 // can actually do this check immediately.
9418 //
9419 // Unless the scope is dependent, it's always an error if qualified
9420 // redeclaration lookup found nothing at all. Diagnose that now;
9421 // nothing will diagnose that error later.
9422 if (isFriend &&
9423 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9424 (!Previous.empty() && CurContext->isDependentContext()))) {
9425 // ignore these
9426 } else {
9427 // The user tried to provide an out-of-line definition for a
9428 // function that is a member of a class or namespace, but there
9429 // was no such member function declared (C++ [class.mfct]p2,
9430 // C++ [namespace.memdef]p2). For example:
9431 //
9432 // class X {
9433 // void f() const;
9434 // };
9435 //
9436 // void X::f() { } // ill-formed
9437 //
9438 // Complain about this problem, and attempt to suggest close
9439 // matches (e.g., those that differ only in cv-qualifiers and
9440 // whether the parameter types are references).
9441
9442 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9443 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9444 AddToScope = ExtraArgs.AddToScope;
9445 return Result;
9446 }
9447 }
9448
9449 // Unqualified local friend declarations are required to resolve
9450 // to something.
9451 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9452 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9453 *this, Previous, NewFD, ExtraArgs, true, S)) {
9454 AddToScope = ExtraArgs.AddToScope;
9455 return Result;
9456 }
9457 }
9458 } else if (!D.isFunctionDefinition() &&
9459 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9460 !isFriend && !isFunctionTemplateSpecialization &&
9461 !isMemberSpecialization) {
9462 // An out-of-line member function declaration must also be a
9463 // definition (C++ [class.mfct]p2).
9464 // Note that this is not the case for explicit specializations of
9465 // function templates or member functions of class templates, per
9466 // C++ [temp.expl.spec]p2. We also allow these declarations as an
9467 // extension for compatibility with old SWIG code which likes to
9468 // generate them.
9469 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9470 << D.getCXXScopeSpec().getRange();
9471 }
9472 }
9473
9474 ProcessPragmaWeak(S, NewFD);
9475 checkAttributesAfterMerging(*this, *NewFD);
9476
9477 AddKnownFunctionAttributes(NewFD);
9478
9479 if (NewFD->hasAttr<OverloadableAttr>() &&
9480 !NewFD->getType()->getAs<FunctionProtoType>()) {
9481 Diag(NewFD->getLocation(),
9482 diag::err_attribute_overloadable_no_prototype)
9483 << NewFD;
9484
9485 // Turn this into a variadic function with no parameters.
9486 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9487 FunctionProtoType::ExtProtoInfo EPI(
9488 Context.getDefaultCallingConvention(true, false));
9489 EPI.Variadic = true;
9490 EPI.ExtInfo = FT->getExtInfo();
9491
9492 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9493 NewFD->setType(R);
9494 }
9495
9496 // If there's a #pragma GCC visibility in scope, and this isn't a class
9497 // member, set the visibility of this function.
9498 if (!DC->isRecord() && NewFD->isExternallyVisible())
9499 AddPushedVisibilityAttribute(NewFD);
9500
9501 // If there's a #pragma clang arc_cf_code_audited in scope, consider
9502 // marking the function.
9503 AddCFAuditedAttribute(NewFD);
9504
9505 // If this is a function definition, check if we have to apply optnone due to
9506 // a pragma.
9507 if(D.isFunctionDefinition())
9508 AddRangeBasedOptnone(NewFD);
9509
9510 // If this is the first declaration of an extern C variable, update
9511 // the map of such variables.
9512 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9513 isIncompleteDeclExternC(*this, NewFD))
9514 RegisterLocallyScopedExternCDecl(NewFD, S);
9515
9516 // Set this FunctionDecl's range up to the right paren.
9517 NewFD->setRangeEnd(D.getSourceRange().getEnd());
9518
9519 if (D.isRedeclaration() && !Previous.empty()) {
9520 NamedDecl *Prev = Previous.getRepresentativeDecl();
9521 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9522 isMemberSpecialization ||
9523 isFunctionTemplateSpecialization,
9524 D.isFunctionDefinition());
9525 }
9526
9527 if (getLangOpts().CUDA) {
9528 IdentifierInfo *II = NewFD->getIdentifier();
9529 if (II && II->isStr(getCudaConfigureFuncName()) &&
9530 !NewFD->isInvalidDecl() &&
9531 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9532 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9533 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9534 << getCudaConfigureFuncName();
9535 Context.setcudaConfigureCallDecl(NewFD);
9536 }
9537
9538 // Variadic functions, other than a *declaration* of printf, are not allowed
9539 // in device-side CUDA code, unless someone passed
9540 // -fcuda-allow-variadic-functions.
9541 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9542 (NewFD->hasAttr<CUDADeviceAttr>() ||
9543 NewFD->hasAttr<CUDAGlobalAttr>()) &&
9544 !(II && II->isStr("printf") && NewFD->isExternC() &&
9545 !D.isFunctionDefinition())) {
9546 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9547 }
9548 }
9549
9550 MarkUnusedFileScopedDecl(NewFD);
9551
9552
9553
9554 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9555 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9556 if ((getLangOpts().OpenCLVersion >= 120)
9557 && (SC == SC_Static)) {
9558 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9559 D.setInvalidType();
9560 }
9561
9562 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9563 if (!NewFD->getReturnType()->isVoidType()) {
9564 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9565 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9566 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9567 : FixItHint());
9568 D.setInvalidType();
9569 }
9570
9571 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9572 for (auto Param : NewFD->parameters())
9573 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9574
9575 if (getLangOpts().OpenCLCPlusPlus) {
9576 if (DC->isRecord()) {
9577 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9578 D.setInvalidType();
9579 }
9580 if (FunctionTemplate) {
9581 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9582 D.setInvalidType();
9583 }
9584 }
9585 }
9586
9587 if (getLangOpts().CPlusPlus) {
9588 if (FunctionTemplate) {
9589 if (NewFD->isInvalidDecl())
9590 FunctionTemplate->setInvalidDecl();
9591 return FunctionTemplate;
9592 }
9593
9594 if (isMemberSpecialization && !NewFD->isInvalidDecl())
9595 CompleteMemberSpecialization(NewFD, Previous);
9596 }
9597
9598 for (const ParmVarDecl *Param : NewFD->parameters()) {
9599 QualType PT = Param->getType();
9600
9601 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9602 // types.
9603 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9604 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9605 QualType ElemTy = PipeTy->getElementType();
9606 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9607 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9608 D.setInvalidType();
9609 }
9610 }
9611 }
9612 }
9613
9614 // Here we have an function template explicit specialization at class scope.
9615 // The actual specialization will be postponed to template instatiation
9616 // time via the ClassScopeFunctionSpecializationDecl node.
9617 if (isDependentClassScopeExplicitSpecialization) {
9618 ClassScopeFunctionSpecializationDecl *NewSpec =
9619 ClassScopeFunctionSpecializationDecl::Create(
9620 Context, CurContext, NewFD->getLocation(),
9621 cast<CXXMethodDecl>(NewFD),
9622 HasExplicitTemplateArgs, TemplateArgs);
9623 CurContext->addDecl(NewSpec);
9624 AddToScope = false;
9625 }
9626
9627 // Diagnose availability attributes. Availability cannot be used on functions
9628 // that are run during load/unload.
9629 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9630 if (NewFD->hasAttr<ConstructorAttr>()) {
9631 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9632 << 1;
9633 NewFD->dropAttr<AvailabilityAttr>();
9634 }
9635 if (NewFD->hasAttr<DestructorAttr>()) {
9636 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9637 << 2;
9638 NewFD->dropAttr<AvailabilityAttr>();
9639 }
9640 }
9641
9642 // Diagnose no_builtin attribute on function declaration that are not a
9643 // definition.
9644 // FIXME: We should really be doing this in
9645 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9646 // the FunctionDecl and at this point of the code
9647 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9648 // because Sema::ActOnStartOfFunctionDef has not been called yet.
9649 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9650 switch (D.getFunctionDefinitionKind()) {
9651 case FDK_Defaulted:
9652 case FDK_Deleted:
9653 Diag(NBA->getLocation(),
9654 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9655 << NBA->getSpelling();
9656 break;
9657 case FDK_Declaration:
9658 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9659 << NBA->getSpelling();
9660 break;
9661 case FDK_Definition:
9662 break;
9663 }
9664
9665 return NewFD;
9666 }
9667
9668 /// Return a CodeSegAttr from a containing class. The Microsoft docs say
9669 /// when __declspec(code_seg) "is applied to a class, all member functions of
9670 /// the class and nested classes -- this includes compiler-generated special
9671 /// member functions -- are put in the specified segment."
9672 /// The actual behavior is a little more complicated. The Microsoft compiler
9673 /// won't check outer classes if there is an active value from #pragma code_seg.
9674 /// The CodeSeg is always applied from the direct parent but only from outer
9675 /// classes when the #pragma code_seg stack is empty. See:
9676 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9677 /// available since MS has removed the page.
getImplicitCodeSegAttrFromClass(Sema & S,const FunctionDecl * FD)9678 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9679 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9680 if (!Method)
9681 return nullptr;
9682 const CXXRecordDecl *Parent = Method->getParent();
9683 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9684 Attr *NewAttr = SAttr->clone(S.getASTContext());
9685 NewAttr->setImplicit(true);
9686 return NewAttr;
9687 }
9688
9689 // The Microsoft compiler won't check outer classes for the CodeSeg
9690 // when the #pragma code_seg stack is active.
9691 if (S.CodeSegStack.CurrentValue)
9692 return nullptr;
9693
9694 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9695 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9696 Attr *NewAttr = SAttr->clone(S.getASTContext());
9697 NewAttr->setImplicit(true);
9698 return NewAttr;
9699 }
9700 }
9701 return nullptr;
9702 }
9703
9704 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9705 /// containing class. Otherwise it will return implicit SectionAttr if the
9706 /// function is a definition and there is an active value on CodeSegStack
9707 /// (from the current #pragma code-seg value).
9708 ///
9709 /// \param FD Function being declared.
9710 /// \param IsDefinition Whether it is a definition or just a declarartion.
9711 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9712 /// nullptr if no attribute should be added.
getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl * FD,bool IsDefinition)9713 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9714 bool IsDefinition) {
9715 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9716 return A;
9717 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9718 CodeSegStack.CurrentValue)
9719 return SectionAttr::CreateImplicit(
9720 getASTContext(), CodeSegStack.CurrentValue->getString(),
9721 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9722 SectionAttr::Declspec_allocate);
9723 return nullptr;
9724 }
9725
9726 /// Determines if we can perform a correct type check for \p D as a
9727 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9728 /// best-effort check.
9729 ///
9730 /// \param NewD The new declaration.
9731 /// \param OldD The old declaration.
9732 /// \param NewT The portion of the type of the new declaration to check.
9733 /// \param OldT The portion of the type of the old declaration to check.
canFullyTypeCheckRedeclaration(ValueDecl * NewD,ValueDecl * OldD,QualType NewT,QualType OldT)9734 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9735 QualType NewT, QualType OldT) {
9736 if (!NewD->getLexicalDeclContext()->isDependentContext())
9737 return true;
9738
9739 // For dependently-typed local extern declarations and friends, we can't
9740 // perform a correct type check in general until instantiation:
9741 //
9742 // int f();
9743 // template<typename T> void g() { T f(); }
9744 //
9745 // (valid if g() is only instantiated with T = int).
9746 if (NewT->isDependentType() &&
9747 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9748 return false;
9749
9750 // Similarly, if the previous declaration was a dependent local extern
9751 // declaration, we don't really know its type yet.
9752 if (OldT->isDependentType() && OldD->isLocalExternDecl())
9753 return false;
9754
9755 return true;
9756 }
9757
9758 /// Checks if the new declaration declared in dependent context must be
9759 /// put in the same redeclaration chain as the specified declaration.
9760 ///
9761 /// \param D Declaration that is checked.
9762 /// \param PrevDecl Previous declaration found with proper lookup method for the
9763 /// same declaration name.
9764 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9765 /// belongs to.
9766 ///
shouldLinkDependentDeclWithPrevious(Decl * D,Decl * PrevDecl)9767 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9768 if (!D->getLexicalDeclContext()->isDependentContext())
9769 return true;
9770
9771 // Don't chain dependent friend function definitions until instantiation, to
9772 // permit cases like
9773 //
9774 // void func();
9775 // template<typename T> class C1 { friend void func() {} };
9776 // template<typename T> class C2 { friend void func() {} };
9777 //
9778 // ... which is valid if only one of C1 and C2 is ever instantiated.
9779 //
9780 // FIXME: This need only apply to function definitions. For now, we proxy
9781 // this by checking for a file-scope function. We do not want this to apply
9782 // to friend declarations nominating member functions, because that gets in
9783 // the way of access checks.
9784 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9785 return false;
9786
9787 auto *VD = dyn_cast<ValueDecl>(D);
9788 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9789 return !VD || !PrevVD ||
9790 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9791 PrevVD->getType());
9792 }
9793
9794 /// Check the target attribute of the function for MultiVersion
9795 /// validity.
9796 ///
9797 /// Returns true if there was an error, false otherwise.
CheckMultiVersionValue(Sema & S,const FunctionDecl * FD)9798 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9799 const auto *TA = FD->getAttr<TargetAttr>();
9800 assert(TA && "MultiVersion Candidate requires a target attribute");
9801 ParsedTargetAttr ParseInfo = TA->parse();
9802 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9803 enum ErrType { Feature = 0, Architecture = 1 };
9804
9805 if (!ParseInfo.Architecture.empty() &&
9806 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9807 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9808 << Architecture << ParseInfo.Architecture;
9809 return true;
9810 }
9811
9812 for (const auto &Feat : ParseInfo.Features) {
9813 auto BareFeat = StringRef{Feat}.substr(1);
9814 if (Feat[0] == '-') {
9815 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9816 << Feature << ("no-" + BareFeat).str();
9817 return true;
9818 }
9819
9820 if (!TargetInfo.validateCpuSupports(BareFeat) ||
9821 !TargetInfo.isValidFeatureName(BareFeat)) {
9822 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9823 << Feature << BareFeat;
9824 return true;
9825 }
9826 }
9827 return false;
9828 }
9829
HasNonMultiVersionAttributes(const FunctionDecl * FD,MultiVersionKind MVType)9830 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9831 MultiVersionKind MVType) {
9832 for (const Attr *A : FD->attrs()) {
9833 switch (A->getKind()) {
9834 case attr::CPUDispatch:
9835 case attr::CPUSpecific:
9836 if (MVType != MultiVersionKind::CPUDispatch &&
9837 MVType != MultiVersionKind::CPUSpecific)
9838 return true;
9839 break;
9840 case attr::Target:
9841 if (MVType != MultiVersionKind::Target)
9842 return true;
9843 break;
9844 default:
9845 return true;
9846 }
9847 }
9848 return false;
9849 }
9850
areMultiversionVariantFunctionsCompatible(const FunctionDecl * OldFD,const FunctionDecl * NewFD,const PartialDiagnostic & NoProtoDiagID,const PartialDiagnosticAt & NoteCausedDiagIDAt,const PartialDiagnosticAt & NoSupportDiagIDAt,const PartialDiagnosticAt & DiffDiagIDAt,bool TemplatesSupported,bool ConstexprSupported,bool CLinkageMayDiffer)9851 bool Sema::areMultiversionVariantFunctionsCompatible(
9852 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
9853 const PartialDiagnostic &NoProtoDiagID,
9854 const PartialDiagnosticAt &NoteCausedDiagIDAt,
9855 const PartialDiagnosticAt &NoSupportDiagIDAt,
9856 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
9857 bool ConstexprSupported, bool CLinkageMayDiffer) {
9858 enum DoesntSupport {
9859 FuncTemplates = 0,
9860 VirtFuncs = 1,
9861 DeducedReturn = 2,
9862 Constructors = 3,
9863 Destructors = 4,
9864 DeletedFuncs = 5,
9865 DefaultedFuncs = 6,
9866 ConstexprFuncs = 7,
9867 ConstevalFuncs = 8,
9868 };
9869 enum Different {
9870 CallingConv = 0,
9871 ReturnType = 1,
9872 ConstexprSpec = 2,
9873 InlineSpec = 3,
9874 StorageClass = 4,
9875 Linkage = 5,
9876 };
9877
9878 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
9879 !OldFD->getType()->getAs<FunctionProtoType>()) {
9880 Diag(OldFD->getLocation(), NoProtoDiagID);
9881 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
9882 return true;
9883 }
9884
9885 if (NoProtoDiagID.getDiagID() != 0 &&
9886 !NewFD->getType()->getAs<FunctionProtoType>())
9887 return Diag(NewFD->getLocation(), NoProtoDiagID);
9888
9889 if (!TemplatesSupported &&
9890 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9891 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9892 << FuncTemplates;
9893
9894 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9895 if (NewCXXFD->isVirtual())
9896 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9897 << VirtFuncs;
9898
9899 if (isa<CXXConstructorDecl>(NewCXXFD))
9900 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9901 << Constructors;
9902
9903 if (isa<CXXDestructorDecl>(NewCXXFD))
9904 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9905 << Destructors;
9906 }
9907
9908 if (NewFD->isDeleted())
9909 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9910 << DeletedFuncs;
9911
9912 if (NewFD->isDefaulted())
9913 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9914 << DefaultedFuncs;
9915
9916 if (!ConstexprSupported && NewFD->isConstexpr())
9917 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9918 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
9919
9920 QualType NewQType = Context.getCanonicalType(NewFD->getType());
9921 const auto *NewType = cast<FunctionType>(NewQType);
9922 QualType NewReturnType = NewType->getReturnType();
9923
9924 if (NewReturnType->isUndeducedType())
9925 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9926 << DeducedReturn;
9927
9928 // Ensure the return type is identical.
9929 if (OldFD) {
9930 QualType OldQType = Context.getCanonicalType(OldFD->getType());
9931 const auto *OldType = cast<FunctionType>(OldQType);
9932 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9933 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9934
9935 if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9936 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
9937
9938 QualType OldReturnType = OldType->getReturnType();
9939
9940 if (OldReturnType != NewReturnType)
9941 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
9942
9943 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
9944 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
9945
9946 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9947 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
9948
9949 if (OldFD->getStorageClass() != NewFD->getStorageClass())
9950 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
9951
9952 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
9953 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
9954
9955 if (CheckEquivalentExceptionSpec(
9956 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9957 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9958 return true;
9959 }
9960 return false;
9961 }
9962
CheckMultiVersionAdditionalRules(Sema & S,const FunctionDecl * OldFD,const FunctionDecl * NewFD,bool CausesMV,MultiVersionKind MVType)9963 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9964 const FunctionDecl *NewFD,
9965 bool CausesMV,
9966 MultiVersionKind MVType) {
9967 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9968 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9969 if (OldFD)
9970 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9971 return true;
9972 }
9973
9974 bool IsCPUSpecificCPUDispatchMVType =
9975 MVType == MultiVersionKind::CPUDispatch ||
9976 MVType == MultiVersionKind::CPUSpecific;
9977
9978 // For now, disallow all other attributes. These should be opt-in, but
9979 // an analysis of all of them is a future FIXME.
9980 if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9981 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9982 << IsCPUSpecificCPUDispatchMVType;
9983 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9984 return true;
9985 }
9986
9987 if (HasNonMultiVersionAttributes(NewFD, MVType))
9988 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9989 << IsCPUSpecificCPUDispatchMVType;
9990
9991 // Only allow transition to MultiVersion if it hasn't been used.
9992 if (OldFD && CausesMV && OldFD->isUsed(false))
9993 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9994
9995 return S.areMultiversionVariantFunctionsCompatible(
9996 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
9997 PartialDiagnosticAt(NewFD->getLocation(),
9998 S.PDiag(diag::note_multiversioning_caused_here)),
9999 PartialDiagnosticAt(NewFD->getLocation(),
10000 S.PDiag(diag::err_multiversion_doesnt_support)
10001 << IsCPUSpecificCPUDispatchMVType),
10002 PartialDiagnosticAt(NewFD->getLocation(),
10003 S.PDiag(diag::err_multiversion_diff)),
10004 /*TemplatesSupported=*/false,
10005 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10006 /*CLinkageMayDiffer=*/false);
10007 }
10008
10009 /// Check the validity of a multiversion function declaration that is the
10010 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10011 ///
10012 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10013 ///
10014 /// Returns true if there was an error, false otherwise.
CheckMultiVersionFirstFunction(Sema & S,FunctionDecl * FD,MultiVersionKind MVType,const TargetAttr * TA)10015 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10016 MultiVersionKind MVType,
10017 const TargetAttr *TA) {
10018 assert(MVType != MultiVersionKind::None &&
10019 "Function lacks multiversion attribute");
10020
10021 // Target only causes MV if it is default, otherwise this is a normal
10022 // function.
10023 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10024 return false;
10025
10026 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10027 FD->setInvalidDecl();
10028 return true;
10029 }
10030
10031 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10032 FD->setInvalidDecl();
10033 return true;
10034 }
10035
10036 FD->setIsMultiVersion();
10037 return false;
10038 }
10039
PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl * FD)10040 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10041 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10042 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10043 return true;
10044 }
10045
10046 return false;
10047 }
10048
CheckTargetCausesMultiVersioning(Sema & S,FunctionDecl * OldFD,FunctionDecl * NewFD,const TargetAttr * NewTA,bool & Redeclaration,NamedDecl * & OldDecl,bool & MergeTypeWithPrevious,LookupResult & Previous)10049 static bool CheckTargetCausesMultiVersioning(
10050 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10051 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10052 LookupResult &Previous) {
10053 const auto *OldTA = OldFD->getAttr<TargetAttr>();
10054 ParsedTargetAttr NewParsed = NewTA->parse();
10055 // Sort order doesn't matter, it just needs to be consistent.
10056 llvm::sort(NewParsed.Features);
10057
10058 // If the old decl is NOT MultiVersioned yet, and we don't cause that
10059 // to change, this is a simple redeclaration.
10060 if (!NewTA->isDefaultVersion() &&
10061 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10062 return false;
10063
10064 // Otherwise, this decl causes MultiVersioning.
10065 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10066 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10067 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10068 NewFD->setInvalidDecl();
10069 return true;
10070 }
10071
10072 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10073 MultiVersionKind::Target)) {
10074 NewFD->setInvalidDecl();
10075 return true;
10076 }
10077
10078 if (CheckMultiVersionValue(S, NewFD)) {
10079 NewFD->setInvalidDecl();
10080 return true;
10081 }
10082
10083 // If this is 'default', permit the forward declaration.
10084 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10085 Redeclaration = true;
10086 OldDecl = OldFD;
10087 OldFD->setIsMultiVersion();
10088 NewFD->setIsMultiVersion();
10089 return false;
10090 }
10091
10092 if (CheckMultiVersionValue(S, OldFD)) {
10093 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10094 NewFD->setInvalidDecl();
10095 return true;
10096 }
10097
10098 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10099
10100 if (OldParsed == NewParsed) {
10101 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10102 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10103 NewFD->setInvalidDecl();
10104 return true;
10105 }
10106
10107 for (const auto *FD : OldFD->redecls()) {
10108 const auto *CurTA = FD->getAttr<TargetAttr>();
10109 // We allow forward declarations before ANY multiversioning attributes, but
10110 // nothing after the fact.
10111 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10112 (!CurTA || CurTA->isInherited())) {
10113 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10114 << 0;
10115 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10116 NewFD->setInvalidDecl();
10117 return true;
10118 }
10119 }
10120
10121 OldFD->setIsMultiVersion();
10122 NewFD->setIsMultiVersion();
10123 Redeclaration = false;
10124 MergeTypeWithPrevious = false;
10125 OldDecl = nullptr;
10126 Previous.clear();
10127 return false;
10128 }
10129
10130 /// Check the validity of a new function declaration being added to an existing
10131 /// 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)10132 static bool CheckMultiVersionAdditionalDecl(
10133 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10134 MultiVersionKind NewMVType, const TargetAttr *NewTA,
10135 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10136 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10137 LookupResult &Previous) {
10138
10139 MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10140 // Disallow mixing of multiversioning types.
10141 if ((OldMVType == MultiVersionKind::Target &&
10142 NewMVType != MultiVersionKind::Target) ||
10143 (NewMVType == MultiVersionKind::Target &&
10144 OldMVType != MultiVersionKind::Target)) {
10145 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10146 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10147 NewFD->setInvalidDecl();
10148 return true;
10149 }
10150
10151 ParsedTargetAttr NewParsed;
10152 if (NewTA) {
10153 NewParsed = NewTA->parse();
10154 llvm::sort(NewParsed.Features);
10155 }
10156
10157 bool UseMemberUsingDeclRules =
10158 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10159
10160 // Next, check ALL non-overloads to see if this is a redeclaration of a
10161 // previous member of the MultiVersion set.
10162 for (NamedDecl *ND : Previous) {
10163 FunctionDecl *CurFD = ND->getAsFunction();
10164 if (!CurFD)
10165 continue;
10166 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10167 continue;
10168
10169 if (NewMVType == MultiVersionKind::Target) {
10170 const auto *CurTA = CurFD->getAttr<TargetAttr>();
10171 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10172 NewFD->setIsMultiVersion();
10173 Redeclaration = true;
10174 OldDecl = ND;
10175 return false;
10176 }
10177
10178 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10179 if (CurParsed == NewParsed) {
10180 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10181 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10182 NewFD->setInvalidDecl();
10183 return true;
10184 }
10185 } else {
10186 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10187 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10188 // Handle CPUDispatch/CPUSpecific versions.
10189 // Only 1 CPUDispatch function is allowed, this will make it go through
10190 // the redeclaration errors.
10191 if (NewMVType == MultiVersionKind::CPUDispatch &&
10192 CurFD->hasAttr<CPUDispatchAttr>()) {
10193 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10194 std::equal(
10195 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10196 NewCPUDisp->cpus_begin(),
10197 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10198 return Cur->getName() == New->getName();
10199 })) {
10200 NewFD->setIsMultiVersion();
10201 Redeclaration = true;
10202 OldDecl = ND;
10203 return false;
10204 }
10205
10206 // If the declarations don't match, this is an error condition.
10207 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10208 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10209 NewFD->setInvalidDecl();
10210 return true;
10211 }
10212 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10213
10214 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10215 std::equal(
10216 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10217 NewCPUSpec->cpus_begin(),
10218 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10219 return Cur->getName() == New->getName();
10220 })) {
10221 NewFD->setIsMultiVersion();
10222 Redeclaration = true;
10223 OldDecl = ND;
10224 return false;
10225 }
10226
10227 // Only 1 version of CPUSpecific is allowed for each CPU.
10228 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10229 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10230 if (CurII == NewII) {
10231 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10232 << NewII;
10233 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10234 NewFD->setInvalidDecl();
10235 return true;
10236 }
10237 }
10238 }
10239 }
10240 // If the two decls aren't the same MVType, there is no possible error
10241 // condition.
10242 }
10243 }
10244
10245 // Else, this is simply a non-redecl case. Checking the 'value' is only
10246 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10247 // handled in the attribute adding step.
10248 if (NewMVType == MultiVersionKind::Target &&
10249 CheckMultiVersionValue(S, NewFD)) {
10250 NewFD->setInvalidDecl();
10251 return true;
10252 }
10253
10254 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10255 !OldFD->isMultiVersion(), NewMVType)) {
10256 NewFD->setInvalidDecl();
10257 return true;
10258 }
10259
10260 // Permit forward declarations in the case where these two are compatible.
10261 if (!OldFD->isMultiVersion()) {
10262 OldFD->setIsMultiVersion();
10263 NewFD->setIsMultiVersion();
10264 Redeclaration = true;
10265 OldDecl = OldFD;
10266 return false;
10267 }
10268
10269 NewFD->setIsMultiVersion();
10270 Redeclaration = false;
10271 MergeTypeWithPrevious = false;
10272 OldDecl = nullptr;
10273 Previous.clear();
10274 return false;
10275 }
10276
10277
10278 /// Check the validity of a mulitversion function declaration.
10279 /// Also sets the multiversion'ness' of the function itself.
10280 ///
10281 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10282 ///
10283 /// Returns true if there was an error, false otherwise.
CheckMultiVersionFunction(Sema & S,FunctionDecl * NewFD,bool & Redeclaration,NamedDecl * & OldDecl,bool & MergeTypeWithPrevious,LookupResult & Previous)10284 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10285 bool &Redeclaration, NamedDecl *&OldDecl,
10286 bool &MergeTypeWithPrevious,
10287 LookupResult &Previous) {
10288 const auto *NewTA = NewFD->getAttr<TargetAttr>();
10289 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10290 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10291
10292 // Mixing Multiversioning types is prohibited.
10293 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10294 (NewCPUDisp && NewCPUSpec)) {
10295 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10296 NewFD->setInvalidDecl();
10297 return true;
10298 }
10299
10300 MultiVersionKind MVType = NewFD->getMultiVersionKind();
10301
10302 // Main isn't allowed to become a multiversion function, however it IS
10303 // permitted to have 'main' be marked with the 'target' optimization hint.
10304 if (NewFD->isMain()) {
10305 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10306 MVType == MultiVersionKind::CPUDispatch ||
10307 MVType == MultiVersionKind::CPUSpecific) {
10308 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10309 NewFD->setInvalidDecl();
10310 return true;
10311 }
10312 return false;
10313 }
10314
10315 if (!OldDecl || !OldDecl->getAsFunction() ||
10316 OldDecl->getDeclContext()->getRedeclContext() !=
10317 NewFD->getDeclContext()->getRedeclContext()) {
10318 // If there's no previous declaration, AND this isn't attempting to cause
10319 // multiversioning, this isn't an error condition.
10320 if (MVType == MultiVersionKind::None)
10321 return false;
10322 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10323 }
10324
10325 FunctionDecl *OldFD = OldDecl->getAsFunction();
10326
10327 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10328 return false;
10329
10330 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10331 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10332 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10333 NewFD->setInvalidDecl();
10334 return true;
10335 }
10336
10337 // Handle the target potentially causes multiversioning case.
10338 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10339 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10340 Redeclaration, OldDecl,
10341 MergeTypeWithPrevious, Previous);
10342
10343 // At this point, we have a multiversion function decl (in OldFD) AND an
10344 // appropriate attribute in the current function decl. Resolve that these are
10345 // still compatible with previous declarations.
10346 return CheckMultiVersionAdditionalDecl(
10347 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10348 OldDecl, MergeTypeWithPrevious, Previous);
10349 }
10350
10351 /// Perform semantic checking of a new function declaration.
10352 ///
10353 /// Performs semantic analysis of the new function declaration
10354 /// NewFD. This routine performs all semantic checking that does not
10355 /// require the actual declarator involved in the declaration, and is
10356 /// used both for the declaration of functions as they are parsed
10357 /// (called via ActOnDeclarator) and for the declaration of functions
10358 /// that have been instantiated via C++ template instantiation (called
10359 /// via InstantiateDecl).
10360 ///
10361 /// \param IsMemberSpecialization whether this new function declaration is
10362 /// a member specialization (that replaces any definition provided by the
10363 /// previous declaration).
10364 ///
10365 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10366 ///
10367 /// \returns true if the function declaration is a redeclaration.
CheckFunctionDeclaration(Scope * S,FunctionDecl * NewFD,LookupResult & Previous,bool IsMemberSpecialization)10368 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10369 LookupResult &Previous,
10370 bool IsMemberSpecialization) {
10371 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10372 "Variably modified return types are not handled here");
10373
10374 // Determine whether the type of this function should be merged with
10375 // a previous visible declaration. This never happens for functions in C++,
10376 // and always happens in C if the previous declaration was visible.
10377 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10378 !Previous.isShadowed();
10379
10380 bool Redeclaration = false;
10381 NamedDecl *OldDecl = nullptr;
10382 bool MayNeedOverloadableChecks = false;
10383
10384 // Merge or overload the declaration with an existing declaration of
10385 // the same name, if appropriate.
10386 if (!Previous.empty()) {
10387 // Determine whether NewFD is an overload of PrevDecl or
10388 // a declaration that requires merging. If it's an overload,
10389 // there's no more work to do here; we'll just add the new
10390 // function to the scope.
10391 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10392 NamedDecl *Candidate = Previous.getRepresentativeDecl();
10393 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10394 Redeclaration = true;
10395 OldDecl = Candidate;
10396 }
10397 } else {
10398 MayNeedOverloadableChecks = true;
10399 switch (CheckOverload(S, NewFD, Previous, OldDecl,
10400 /*NewIsUsingDecl*/ false)) {
10401 case Ovl_Match:
10402 Redeclaration = true;
10403 break;
10404
10405 case Ovl_NonFunction:
10406 Redeclaration = true;
10407 break;
10408
10409 case Ovl_Overload:
10410 Redeclaration = false;
10411 break;
10412 }
10413 }
10414 }
10415
10416 // Check for a previous extern "C" declaration with this name.
10417 if (!Redeclaration &&
10418 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10419 if (!Previous.empty()) {
10420 // This is an extern "C" declaration with the same name as a previous
10421 // declaration, and thus redeclares that entity...
10422 Redeclaration = true;
10423 OldDecl = Previous.getFoundDecl();
10424 MergeTypeWithPrevious = false;
10425
10426 // ... except in the presence of __attribute__((overloadable)).
10427 if (OldDecl->hasAttr<OverloadableAttr>() ||
10428 NewFD->hasAttr<OverloadableAttr>()) {
10429 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10430 MayNeedOverloadableChecks = true;
10431 Redeclaration = false;
10432 OldDecl = nullptr;
10433 }
10434 }
10435 }
10436 }
10437
10438 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10439 MergeTypeWithPrevious, Previous))
10440 return Redeclaration;
10441
10442 // C++11 [dcl.constexpr]p8:
10443 // A constexpr specifier for a non-static member function that is not
10444 // a constructor declares that member function to be const.
10445 //
10446 // This needs to be delayed until we know whether this is an out-of-line
10447 // definition of a static member function.
10448 //
10449 // This rule is not present in C++1y, so we produce a backwards
10450 // compatibility warning whenever it happens in C++11.
10451 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10452 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10453 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10454 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10455 CXXMethodDecl *OldMD = nullptr;
10456 if (OldDecl)
10457 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10458 if (!OldMD || !OldMD->isStatic()) {
10459 const FunctionProtoType *FPT =
10460 MD->getType()->castAs<FunctionProtoType>();
10461 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10462 EPI.TypeQuals.addConst();
10463 MD->setType(Context.getFunctionType(FPT->getReturnType(),
10464 FPT->getParamTypes(), EPI));
10465
10466 // Warn that we did this, if we're not performing template instantiation.
10467 // In that case, we'll have warned already when the template was defined.
10468 if (!inTemplateInstantiation()) {
10469 SourceLocation AddConstLoc;
10470 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10471 .IgnoreParens().getAs<FunctionTypeLoc>())
10472 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10473
10474 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10475 << FixItHint::CreateInsertion(AddConstLoc, " const");
10476 }
10477 }
10478 }
10479
10480 if (Redeclaration) {
10481 // NewFD and OldDecl represent declarations that need to be
10482 // merged.
10483 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10484 NewFD->setInvalidDecl();
10485 return Redeclaration;
10486 }
10487
10488 Previous.clear();
10489 Previous.addDecl(OldDecl);
10490
10491 if (FunctionTemplateDecl *OldTemplateDecl =
10492 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10493 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10494 FunctionTemplateDecl *NewTemplateDecl
10495 = NewFD->getDescribedFunctionTemplate();
10496 assert(NewTemplateDecl && "Template/non-template mismatch");
10497
10498 // The call to MergeFunctionDecl above may have created some state in
10499 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10500 // can add it as a redeclaration.
10501 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10502
10503 NewFD->setPreviousDeclaration(OldFD);
10504 adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10505 if (NewFD->isCXXClassMember()) {
10506 NewFD->setAccess(OldTemplateDecl->getAccess());
10507 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10508 }
10509
10510 // If this is an explicit specialization of a member that is a function
10511 // template, mark it as a member specialization.
10512 if (IsMemberSpecialization &&
10513 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10514 NewTemplateDecl->setMemberSpecialization();
10515 assert(OldTemplateDecl->isMemberSpecialization());
10516 // Explicit specializations of a member template do not inherit deleted
10517 // status from the parent member template that they are specializing.
10518 if (OldFD->isDeleted()) {
10519 // FIXME: This assert will not hold in the presence of modules.
10520 assert(OldFD->getCanonicalDecl() == OldFD);
10521 // FIXME: We need an update record for this AST mutation.
10522 OldFD->setDeletedAsWritten(false);
10523 }
10524 }
10525
10526 } else {
10527 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10528 auto *OldFD = cast<FunctionDecl>(OldDecl);
10529 // This needs to happen first so that 'inline' propagates.
10530 NewFD->setPreviousDeclaration(OldFD);
10531 adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10532 if (NewFD->isCXXClassMember())
10533 NewFD->setAccess(OldFD->getAccess());
10534 }
10535 }
10536 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10537 !NewFD->getAttr<OverloadableAttr>()) {
10538 assert((Previous.empty() ||
10539 llvm::any_of(Previous,
10540 [](const NamedDecl *ND) {
10541 return ND->hasAttr<OverloadableAttr>();
10542 })) &&
10543 "Non-redecls shouldn't happen without overloadable present");
10544
10545 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10546 const auto *FD = dyn_cast<FunctionDecl>(ND);
10547 return FD && !FD->hasAttr<OverloadableAttr>();
10548 });
10549
10550 if (OtherUnmarkedIter != Previous.end()) {
10551 Diag(NewFD->getLocation(),
10552 diag::err_attribute_overloadable_multiple_unmarked_overloads);
10553 Diag((*OtherUnmarkedIter)->getLocation(),
10554 diag::note_attribute_overloadable_prev_overload)
10555 << false;
10556
10557 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10558 }
10559 }
10560
10561 // Semantic checking for this function declaration (in isolation).
10562
10563 if (getLangOpts().CPlusPlus) {
10564 // C++-specific checks.
10565 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10566 CheckConstructor(Constructor);
10567 } else if (CXXDestructorDecl *Destructor =
10568 dyn_cast<CXXDestructorDecl>(NewFD)) {
10569 CXXRecordDecl *Record = Destructor->getParent();
10570 QualType ClassType = Context.getTypeDeclType(Record);
10571
10572 // FIXME: Shouldn't we be able to perform this check even when the class
10573 // type is dependent? Both gcc and edg can handle that.
10574 if (!ClassType->isDependentType()) {
10575 DeclarationName Name
10576 = Context.DeclarationNames.getCXXDestructorName(
10577 Context.getCanonicalType(ClassType));
10578 if (NewFD->getDeclName() != Name) {
10579 Diag(NewFD->getLocation(), diag::err_destructor_name);
10580 NewFD->setInvalidDecl();
10581 return Redeclaration;
10582 }
10583 }
10584 } else if (CXXConversionDecl *Conversion
10585 = dyn_cast<CXXConversionDecl>(NewFD)) {
10586 ActOnConversionDeclarator(Conversion);
10587 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10588 if (auto *TD = Guide->getDescribedFunctionTemplate())
10589 CheckDeductionGuideTemplate(TD);
10590
10591 // A deduction guide is not on the list of entities that can be
10592 // explicitly specialized.
10593 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10594 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10595 << /*explicit specialization*/ 1;
10596 }
10597
10598 // Find any virtual functions that this function overrides.
10599 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10600 if (!Method->isFunctionTemplateSpecialization() &&
10601 !Method->getDescribedFunctionTemplate() &&
10602 Method->isCanonicalDecl()) {
10603 if (AddOverriddenMethods(Method->getParent(), Method)) {
10604 // If the function was marked as "static", we have a problem.
10605 if (NewFD->getStorageClass() == SC_Static) {
10606 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10607 }
10608 }
10609 }
10610 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10611 // C++2a [class.virtual]p6
10612 // A virtual method shall not have a requires-clause.
10613 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10614 diag::err_constrained_virtual_method);
10615
10616 if (Method->isStatic())
10617 checkThisInStaticMemberFunctionType(Method);
10618 }
10619
10620 // Extra checking for C++ overloaded operators (C++ [over.oper]).
10621 if (NewFD->isOverloadedOperator() &&
10622 CheckOverloadedOperatorDeclaration(NewFD)) {
10623 NewFD->setInvalidDecl();
10624 return Redeclaration;
10625 }
10626
10627 // Extra checking for C++0x literal operators (C++0x [over.literal]).
10628 if (NewFD->getLiteralIdentifier() &&
10629 CheckLiteralOperatorDeclaration(NewFD)) {
10630 NewFD->setInvalidDecl();
10631 return Redeclaration;
10632 }
10633
10634 // In C++, check default arguments now that we have merged decls. Unless
10635 // the lexical context is the class, because in this case this is done
10636 // during delayed parsing anyway.
10637 if (!CurContext->isRecord())
10638 CheckCXXDefaultArguments(NewFD);
10639
10640 // If this function declares a builtin function, check the type of this
10641 // declaration against the expected type for the builtin.
10642 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10643 ASTContext::GetBuiltinTypeError Error;
10644 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10645 QualType T = Context.GetBuiltinType(BuiltinID, Error);
10646 // If the type of the builtin differs only in its exception
10647 // specification, that's OK.
10648 // FIXME: If the types do differ in this way, it would be better to
10649 // retain the 'noexcept' form of the type.
10650 if (!T.isNull() &&
10651 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10652 NewFD->getType()))
10653 // The type of this function differs from the type of the builtin,
10654 // so forget about the builtin entirely.
10655 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10656 }
10657
10658 // If this function is declared as being extern "C", then check to see if
10659 // the function returns a UDT (class, struct, or union type) that is not C
10660 // compatible, and if it does, warn the user.
10661 // But, issue any diagnostic on the first declaration only.
10662 if (Previous.empty() && NewFD->isExternC()) {
10663 QualType R = NewFD->getReturnType();
10664 if (R->isIncompleteType() && !R->isVoidType())
10665 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10666 << NewFD << R;
10667 else if (!R.isPODType(Context) && !R->isVoidType() &&
10668 !R->isObjCObjectPointerType())
10669 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10670 }
10671
10672 // C++1z [dcl.fct]p6:
10673 // [...] whether the function has a non-throwing exception-specification
10674 // [is] part of the function type
10675 //
10676 // This results in an ABI break between C++14 and C++17 for functions whose
10677 // declared type includes an exception-specification in a parameter or
10678 // return type. (Exception specifications on the function itself are OK in
10679 // most cases, and exception specifications are not permitted in most other
10680 // contexts where they could make it into a mangling.)
10681 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10682 auto HasNoexcept = [&](QualType T) -> bool {
10683 // Strip off declarator chunks that could be between us and a function
10684 // type. We don't need to look far, exception specifications are very
10685 // restricted prior to C++17.
10686 if (auto *RT = T->getAs<ReferenceType>())
10687 T = RT->getPointeeType();
10688 else if (T->isAnyPointerType())
10689 T = T->getPointeeType();
10690 else if (auto *MPT = T->getAs<MemberPointerType>())
10691 T = MPT->getPointeeType();
10692 if (auto *FPT = T->getAs<FunctionProtoType>())
10693 if (FPT->isNothrow())
10694 return true;
10695 return false;
10696 };
10697
10698 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10699 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10700 for (QualType T : FPT->param_types())
10701 AnyNoexcept |= HasNoexcept(T);
10702 if (AnyNoexcept)
10703 Diag(NewFD->getLocation(),
10704 diag::warn_cxx17_compat_exception_spec_in_signature)
10705 << NewFD;
10706 }
10707
10708 if (!Redeclaration && LangOpts.CUDA)
10709 checkCUDATargetOverload(NewFD, Previous);
10710 }
10711 return Redeclaration;
10712 }
10713
CheckMain(FunctionDecl * FD,const DeclSpec & DS)10714 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10715 // C++11 [basic.start.main]p3:
10716 // A program that [...] declares main to be inline, static or
10717 // constexpr is ill-formed.
10718 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
10719 // appear in a declaration of main.
10720 // static main is not an error under C99, but we should warn about it.
10721 // We accept _Noreturn main as an extension.
10722 if (FD->getStorageClass() == SC_Static)
10723 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10724 ? diag::err_static_main : diag::warn_static_main)
10725 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10726 if (FD->isInlineSpecified())
10727 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10728 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10729 if (DS.isNoreturnSpecified()) {
10730 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10731 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10732 Diag(NoreturnLoc, diag::ext_noreturn_main);
10733 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10734 << FixItHint::CreateRemoval(NoreturnRange);
10735 }
10736 if (FD->isConstexpr()) {
10737 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10738 << FD->isConsteval()
10739 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10740 FD->setConstexprKind(CSK_unspecified);
10741 }
10742
10743 if (getLangOpts().OpenCL) {
10744 Diag(FD->getLocation(), diag::err_opencl_no_main)
10745 << FD->hasAttr<OpenCLKernelAttr>();
10746 FD->setInvalidDecl();
10747 return;
10748 }
10749
10750 QualType T = FD->getType();
10751 assert(T->isFunctionType() && "function decl is not of function type");
10752 const FunctionType* FT = T->castAs<FunctionType>();
10753
10754 // Set default calling convention for main()
10755 if (FT->getCallConv() != CC_C) {
10756 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10757 FD->setType(QualType(FT, 0));
10758 T = Context.getCanonicalType(FD->getType());
10759 }
10760
10761 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10762 // In C with GNU extensions we allow main() to have non-integer return
10763 // type, but we should warn about the extension, and we disable the
10764 // implicit-return-zero rule.
10765
10766 // GCC in C mode accepts qualified 'int'.
10767 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10768 FD->setHasImplicitReturnZero(true);
10769 else {
10770 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10771 SourceRange RTRange = FD->getReturnTypeSourceRange();
10772 if (RTRange.isValid())
10773 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10774 << FixItHint::CreateReplacement(RTRange, "int");
10775 }
10776 } else {
10777 // In C and C++, main magically returns 0 if you fall off the end;
10778 // set the flag which tells us that.
10779 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10780
10781 // All the standards say that main() should return 'int'.
10782 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10783 FD->setHasImplicitReturnZero(true);
10784 else {
10785 // Otherwise, this is just a flat-out error.
10786 SourceRange RTRange = FD->getReturnTypeSourceRange();
10787 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10788 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10789 : FixItHint());
10790 FD->setInvalidDecl(true);
10791 }
10792 }
10793
10794 // Treat protoless main() as nullary.
10795 if (isa<FunctionNoProtoType>(FT)) return;
10796
10797 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10798 unsigned nparams = FTP->getNumParams();
10799 assert(FD->getNumParams() == nparams);
10800
10801 bool HasExtraParameters = (nparams > 3);
10802
10803 if (FTP->isVariadic()) {
10804 Diag(FD->getLocation(), diag::ext_variadic_main);
10805 // FIXME: if we had information about the location of the ellipsis, we
10806 // could add a FixIt hint to remove it as a parameter.
10807 }
10808
10809 // Darwin passes an undocumented fourth argument of type char**. If
10810 // other platforms start sprouting these, the logic below will start
10811 // getting shifty.
10812 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10813 HasExtraParameters = false;
10814
10815 if (HasExtraParameters) {
10816 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10817 FD->setInvalidDecl(true);
10818 nparams = 3;
10819 }
10820
10821 // FIXME: a lot of the following diagnostics would be improved
10822 // if we had some location information about types.
10823
10824 QualType CharPP =
10825 Context.getPointerType(Context.getPointerType(Context.CharTy));
10826 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10827
10828 for (unsigned i = 0; i < nparams; ++i) {
10829 QualType AT = FTP->getParamType(i);
10830
10831 bool mismatch = true;
10832
10833 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10834 mismatch = false;
10835 else if (Expected[i] == CharPP) {
10836 // As an extension, the following forms are okay:
10837 // char const **
10838 // char const * const *
10839 // char * const *
10840
10841 QualifierCollector qs;
10842 const PointerType* PT;
10843 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10844 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10845 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10846 Context.CharTy)) {
10847 qs.removeConst();
10848 mismatch = !qs.empty();
10849 }
10850 }
10851
10852 if (mismatch) {
10853 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10854 // TODO: suggest replacing given type with expected type
10855 FD->setInvalidDecl(true);
10856 }
10857 }
10858
10859 if (nparams == 1 && !FD->isInvalidDecl()) {
10860 Diag(FD->getLocation(), diag::warn_main_one_arg);
10861 }
10862
10863 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10864 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10865 FD->setInvalidDecl();
10866 }
10867 }
10868
CheckMSVCRTEntryPoint(FunctionDecl * FD)10869 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10870 QualType T = FD->getType();
10871 assert(T->isFunctionType() && "function decl is not of function type");
10872 const FunctionType *FT = T->castAs<FunctionType>();
10873
10874 // Set an implicit return of 'zero' if the function can return some integral,
10875 // enumeration, pointer or nullptr type.
10876 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10877 FT->getReturnType()->isAnyPointerType() ||
10878 FT->getReturnType()->isNullPtrType())
10879 // DllMain is exempt because a return value of zero means it failed.
10880 if (FD->getName() != "DllMain")
10881 FD->setHasImplicitReturnZero(true);
10882
10883 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10884 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10885 FD->setInvalidDecl();
10886 }
10887 }
10888
CheckForConstantInitializer(Expr * Init,QualType DclT)10889 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10890 // FIXME: Need strict checking. In C89, we need to check for
10891 // any assignment, increment, decrement, function-calls, or
10892 // commas outside of a sizeof. In C99, it's the same list,
10893 // except that the aforementioned are allowed in unevaluated
10894 // expressions. Everything else falls under the
10895 // "may accept other forms of constant expressions" exception.
10896 // (We never end up here for C++, so the constant expression
10897 // rules there don't matter.)
10898 const Expr *Culprit;
10899 if (Init->isConstantInitializer(Context, false, &Culprit))
10900 return false;
10901 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10902 << Culprit->getSourceRange();
10903 return true;
10904 }
10905
10906 namespace {
10907 // Visits an initialization expression to see if OrigDecl is evaluated in
10908 // its own initialization and throws a warning if it does.
10909 class SelfReferenceChecker
10910 : public EvaluatedExprVisitor<SelfReferenceChecker> {
10911 Sema &S;
10912 Decl *OrigDecl;
10913 bool isRecordType;
10914 bool isPODType;
10915 bool isReferenceType;
10916
10917 bool isInitList;
10918 llvm::SmallVector<unsigned, 4> InitFieldIndex;
10919
10920 public:
10921 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10922
SelfReferenceChecker(Sema & S,Decl * OrigDecl)10923 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10924 S(S), OrigDecl(OrigDecl) {
10925 isPODType = false;
10926 isRecordType = false;
10927 isReferenceType = false;
10928 isInitList = false;
10929 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10930 isPODType = VD->getType().isPODType(S.Context);
10931 isRecordType = VD->getType()->isRecordType();
10932 isReferenceType = VD->getType()->isReferenceType();
10933 }
10934 }
10935
10936 // For most expressions, just call the visitor. For initializer lists,
10937 // track the index of the field being initialized since fields are
10938 // initialized in order allowing use of previously initialized fields.
CheckExpr(Expr * E)10939 void CheckExpr(Expr *E) {
10940 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10941 if (!InitList) {
10942 Visit(E);
10943 return;
10944 }
10945
10946 // Track and increment the index here.
10947 isInitList = true;
10948 InitFieldIndex.push_back(0);
10949 for (auto Child : InitList->children()) {
10950 CheckExpr(cast<Expr>(Child));
10951 ++InitFieldIndex.back();
10952 }
10953 InitFieldIndex.pop_back();
10954 }
10955
10956 // Returns true if MemberExpr is checked and no further checking is needed.
10957 // Returns false if additional checking is required.
CheckInitListMemberExpr(MemberExpr * E,bool CheckReference)10958 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10959 llvm::SmallVector<FieldDecl*, 4> Fields;
10960 Expr *Base = E;
10961 bool ReferenceField = false;
10962
10963 // Get the field members used.
10964 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10965 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10966 if (!FD)
10967 return false;
10968 Fields.push_back(FD);
10969 if (FD->getType()->isReferenceType())
10970 ReferenceField = true;
10971 Base = ME->getBase()->IgnoreParenImpCasts();
10972 }
10973
10974 // Keep checking only if the base Decl is the same.
10975 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10976 if (!DRE || DRE->getDecl() != OrigDecl)
10977 return false;
10978
10979 // A reference field can be bound to an unininitialized field.
10980 if (CheckReference && !ReferenceField)
10981 return true;
10982
10983 // Convert FieldDecls to their index number.
10984 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10985 for (const FieldDecl *I : llvm::reverse(Fields))
10986 UsedFieldIndex.push_back(I->getFieldIndex());
10987
10988 // See if a warning is needed by checking the first difference in index
10989 // numbers. If field being used has index less than the field being
10990 // initialized, then the use is safe.
10991 for (auto UsedIter = UsedFieldIndex.begin(),
10992 UsedEnd = UsedFieldIndex.end(),
10993 OrigIter = InitFieldIndex.begin(),
10994 OrigEnd = InitFieldIndex.end();
10995 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10996 if (*UsedIter < *OrigIter)
10997 return true;
10998 if (*UsedIter > *OrigIter)
10999 break;
11000 }
11001
11002 // TODO: Add a different warning which will print the field names.
11003 HandleDeclRefExpr(DRE);
11004 return true;
11005 }
11006
11007 // For most expressions, the cast is directly above the DeclRefExpr.
11008 // For conditional operators, the cast can be outside the conditional
11009 // operator if both expressions are DeclRefExpr's.
HandleValue(Expr * E)11010 void HandleValue(Expr *E) {
11011 E = E->IgnoreParens();
11012 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11013 HandleDeclRefExpr(DRE);
11014 return;
11015 }
11016
11017 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11018 Visit(CO->getCond());
11019 HandleValue(CO->getTrueExpr());
11020 HandleValue(CO->getFalseExpr());
11021 return;
11022 }
11023
11024 if (BinaryConditionalOperator *BCO =
11025 dyn_cast<BinaryConditionalOperator>(E)) {
11026 Visit(BCO->getCond());
11027 HandleValue(BCO->getFalseExpr());
11028 return;
11029 }
11030
11031 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11032 HandleValue(OVE->getSourceExpr());
11033 return;
11034 }
11035
11036 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11037 if (BO->getOpcode() == BO_Comma) {
11038 Visit(BO->getLHS());
11039 HandleValue(BO->getRHS());
11040 return;
11041 }
11042 }
11043
11044 if (isa<MemberExpr>(E)) {
11045 if (isInitList) {
11046 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11047 false /*CheckReference*/))
11048 return;
11049 }
11050
11051 Expr *Base = E->IgnoreParenImpCasts();
11052 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11053 // Check for static member variables and don't warn on them.
11054 if (!isa<FieldDecl>(ME->getMemberDecl()))
11055 return;
11056 Base = ME->getBase()->IgnoreParenImpCasts();
11057 }
11058 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11059 HandleDeclRefExpr(DRE);
11060 return;
11061 }
11062
11063 Visit(E);
11064 }
11065
11066 // Reference types not handled in HandleValue are handled here since all
11067 // uses of references are bad, not just r-value uses.
VisitDeclRefExpr(DeclRefExpr * E)11068 void VisitDeclRefExpr(DeclRefExpr *E) {
11069 if (isReferenceType)
11070 HandleDeclRefExpr(E);
11071 }
11072
VisitImplicitCastExpr(ImplicitCastExpr * E)11073 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11074 if (E->getCastKind() == CK_LValueToRValue) {
11075 HandleValue(E->getSubExpr());
11076 return;
11077 }
11078
11079 Inherited::VisitImplicitCastExpr(E);
11080 }
11081
VisitMemberExpr(MemberExpr * E)11082 void VisitMemberExpr(MemberExpr *E) {
11083 if (isInitList) {
11084 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11085 return;
11086 }
11087
11088 // Don't warn on arrays since they can be treated as pointers.
11089 if (E->getType()->canDecayToPointerType()) return;
11090
11091 // Warn when a non-static method call is followed by non-static member
11092 // field accesses, which is followed by a DeclRefExpr.
11093 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11094 bool Warn = (MD && !MD->isStatic());
11095 Expr *Base = E->getBase()->IgnoreParenImpCasts();
11096 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11097 if (!isa<FieldDecl>(ME->getMemberDecl()))
11098 Warn = false;
11099 Base = ME->getBase()->IgnoreParenImpCasts();
11100 }
11101
11102 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11103 if (Warn)
11104 HandleDeclRefExpr(DRE);
11105 return;
11106 }
11107
11108 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11109 // Visit that expression.
11110 Visit(Base);
11111 }
11112
VisitCXXOperatorCallExpr(CXXOperatorCallExpr * E)11113 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11114 Expr *Callee = E->getCallee();
11115
11116 if (isa<UnresolvedLookupExpr>(Callee))
11117 return Inherited::VisitCXXOperatorCallExpr(E);
11118
11119 Visit(Callee);
11120 for (auto Arg: E->arguments())
11121 HandleValue(Arg->IgnoreParenImpCasts());
11122 }
11123
VisitUnaryOperator(UnaryOperator * E)11124 void VisitUnaryOperator(UnaryOperator *E) {
11125 // For POD record types, addresses of its own members are well-defined.
11126 if (E->getOpcode() == UO_AddrOf && isRecordType &&
11127 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11128 if (!isPODType)
11129 HandleValue(E->getSubExpr());
11130 return;
11131 }
11132
11133 if (E->isIncrementDecrementOp()) {
11134 HandleValue(E->getSubExpr());
11135 return;
11136 }
11137
11138 Inherited::VisitUnaryOperator(E);
11139 }
11140
VisitObjCMessageExpr(ObjCMessageExpr * E)11141 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11142
VisitCXXConstructExpr(CXXConstructExpr * E)11143 void VisitCXXConstructExpr(CXXConstructExpr *E) {
11144 if (E->getConstructor()->isCopyConstructor()) {
11145 Expr *ArgExpr = E->getArg(0);
11146 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11147 if (ILE->getNumInits() == 1)
11148 ArgExpr = ILE->getInit(0);
11149 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11150 if (ICE->getCastKind() == CK_NoOp)
11151 ArgExpr = ICE->getSubExpr();
11152 HandleValue(ArgExpr);
11153 return;
11154 }
11155 Inherited::VisitCXXConstructExpr(E);
11156 }
11157
VisitCallExpr(CallExpr * E)11158 void VisitCallExpr(CallExpr *E) {
11159 // Treat std::move as a use.
11160 if (E->isCallToStdMove()) {
11161 HandleValue(E->getArg(0));
11162 return;
11163 }
11164
11165 Inherited::VisitCallExpr(E);
11166 }
11167
VisitBinaryOperator(BinaryOperator * E)11168 void VisitBinaryOperator(BinaryOperator *E) {
11169 if (E->isCompoundAssignmentOp()) {
11170 HandleValue(E->getLHS());
11171 Visit(E->getRHS());
11172 return;
11173 }
11174
11175 Inherited::VisitBinaryOperator(E);
11176 }
11177
11178 // A custom visitor for BinaryConditionalOperator is needed because the
11179 // regular visitor would check the condition and true expression separately
11180 // but both point to the same place giving duplicate diagnostics.
VisitBinaryConditionalOperator(BinaryConditionalOperator * E)11181 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11182 Visit(E->getCond());
11183 Visit(E->getFalseExpr());
11184 }
11185
HandleDeclRefExpr(DeclRefExpr * DRE)11186 void HandleDeclRefExpr(DeclRefExpr *DRE) {
11187 Decl* ReferenceDecl = DRE->getDecl();
11188 if (OrigDecl != ReferenceDecl) return;
11189 unsigned diag;
11190 if (isReferenceType) {
11191 diag = diag::warn_uninit_self_reference_in_reference_init;
11192 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11193 diag = diag::warn_static_self_reference_in_init;
11194 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11195 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11196 DRE->getDecl()->getType()->isRecordType()) {
11197 diag = diag::warn_uninit_self_reference_in_init;
11198 } else {
11199 // Local variables will be handled by the CFG analysis.
11200 return;
11201 }
11202
11203 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11204 S.PDiag(diag)
11205 << DRE->getDecl() << OrigDecl->getLocation()
11206 << DRE->getSourceRange());
11207 }
11208 };
11209
11210 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
CheckSelfReference(Sema & S,Decl * OrigDecl,Expr * E,bool DirectInit)11211 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11212 bool DirectInit) {
11213 // Parameters arguments are occassionially constructed with itself,
11214 // for instance, in recursive functions. Skip them.
11215 if (isa<ParmVarDecl>(OrigDecl))
11216 return;
11217
11218 E = E->IgnoreParens();
11219
11220 // Skip checking T a = a where T is not a record or reference type.
11221 // Doing so is a way to silence uninitialized warnings.
11222 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11223 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11224 if (ICE->getCastKind() == CK_LValueToRValue)
11225 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11226 if (DRE->getDecl() == OrigDecl)
11227 return;
11228
11229 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11230 }
11231 } // end anonymous namespace
11232
11233 namespace {
11234 // Simple wrapper to add the name of a variable or (if no variable is
11235 // available) a DeclarationName into a diagnostic.
11236 struct VarDeclOrName {
11237 VarDecl *VDecl;
11238 DeclarationName Name;
11239
11240 friend const Sema::SemaDiagnosticBuilder &
operator <<(const Sema::SemaDiagnosticBuilder & Diag,VarDeclOrName VN)11241 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11242 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11243 }
11244 };
11245 } // end anonymous namespace
11246
deduceVarTypeFromInitializer(VarDecl * VDecl,DeclarationName Name,QualType Type,TypeSourceInfo * TSI,SourceRange Range,bool DirectInit,Expr * Init)11247 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11248 DeclarationName Name, QualType Type,
11249 TypeSourceInfo *TSI,
11250 SourceRange Range, bool DirectInit,
11251 Expr *Init) {
11252 bool IsInitCapture = !VDecl;
11253 assert((!VDecl || !VDecl->isInitCapture()) &&
11254 "init captures are expected to be deduced prior to initialization");
11255
11256 VarDeclOrName VN{VDecl, Name};
11257
11258 DeducedType *Deduced = Type->getContainedDeducedType();
11259 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11260
11261 // C++11 [dcl.spec.auto]p3
11262 if (!Init) {
11263 assert(VDecl && "no init for init capture deduction?");
11264
11265 // Except for class argument deduction, and then for an initializing
11266 // declaration only, i.e. no static at class scope or extern.
11267 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11268 VDecl->hasExternalStorage() ||
11269 VDecl->isStaticDataMember()) {
11270 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11271 << VDecl->getDeclName() << Type;
11272 return QualType();
11273 }
11274 }
11275
11276 ArrayRef<Expr*> DeduceInits;
11277 if (Init)
11278 DeduceInits = Init;
11279
11280 if (DirectInit) {
11281 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11282 DeduceInits = PL->exprs();
11283 }
11284
11285 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11286 assert(VDecl && "non-auto type for init capture deduction?");
11287 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11288 InitializationKind Kind = InitializationKind::CreateForInit(
11289 VDecl->getLocation(), DirectInit, Init);
11290 // FIXME: Initialization should not be taking a mutable list of inits.
11291 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11292 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11293 InitsCopy);
11294 }
11295
11296 if (DirectInit) {
11297 if (auto *IL = dyn_cast<InitListExpr>(Init))
11298 DeduceInits = IL->inits();
11299 }
11300
11301 // Deduction only works if we have exactly one source expression.
11302 if (DeduceInits.empty()) {
11303 // It isn't possible to write this directly, but it is possible to
11304 // end up in this situation with "auto x(some_pack...);"
11305 Diag(Init->getBeginLoc(), IsInitCapture
11306 ? diag::err_init_capture_no_expression
11307 : diag::err_auto_var_init_no_expression)
11308 << VN << Type << Range;
11309 return QualType();
11310 }
11311
11312 if (DeduceInits.size() > 1) {
11313 Diag(DeduceInits[1]->getBeginLoc(),
11314 IsInitCapture ? diag::err_init_capture_multiple_expressions
11315 : diag::err_auto_var_init_multiple_expressions)
11316 << VN << Type << Range;
11317 return QualType();
11318 }
11319
11320 Expr *DeduceInit = DeduceInits[0];
11321 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11322 Diag(Init->getBeginLoc(), IsInitCapture
11323 ? diag::err_init_capture_paren_braces
11324 : diag::err_auto_var_init_paren_braces)
11325 << isa<InitListExpr>(Init) << VN << Type << Range;
11326 return QualType();
11327 }
11328
11329 // Expressions default to 'id' when we're in a debugger.
11330 bool DefaultedAnyToId = false;
11331 if (getLangOpts().DebuggerCastResultToId &&
11332 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11333 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11334 if (Result.isInvalid()) {
11335 return QualType();
11336 }
11337 Init = Result.get();
11338 DefaultedAnyToId = true;
11339 }
11340
11341 // C++ [dcl.decomp]p1:
11342 // If the assignment-expression [...] has array type A and no ref-qualifier
11343 // is present, e has type cv A
11344 if (VDecl && isa<DecompositionDecl>(VDecl) &&
11345 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11346 DeduceInit->getType()->isConstantArrayType())
11347 return Context.getQualifiedType(DeduceInit->getType(),
11348 Type.getQualifiers());
11349
11350 QualType DeducedType;
11351 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11352 if (!IsInitCapture)
11353 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11354 else if (isa<InitListExpr>(Init))
11355 Diag(Range.getBegin(),
11356 diag::err_init_capture_deduction_failure_from_init_list)
11357 << VN
11358 << (DeduceInit->getType().isNull() ? TSI->getType()
11359 : DeduceInit->getType())
11360 << DeduceInit->getSourceRange();
11361 else
11362 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11363 << VN << TSI->getType()
11364 << (DeduceInit->getType().isNull() ? TSI->getType()
11365 : DeduceInit->getType())
11366 << DeduceInit->getSourceRange();
11367 }
11368
11369 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11370 // 'id' instead of a specific object type prevents most of our usual
11371 // checks.
11372 // We only want to warn outside of template instantiations, though:
11373 // inside a template, the 'id' could have come from a parameter.
11374 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11375 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11376 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11377 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11378 }
11379
11380 return DeducedType;
11381 }
11382
DeduceVariableDeclarationType(VarDecl * VDecl,bool DirectInit,Expr * Init)11383 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11384 Expr *Init) {
11385 QualType DeducedType = deduceVarTypeFromInitializer(
11386 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11387 VDecl->getSourceRange(), DirectInit, Init);
11388 if (DeducedType.isNull()) {
11389 VDecl->setInvalidDecl();
11390 return true;
11391 }
11392
11393 VDecl->setType(DeducedType);
11394 assert(VDecl->isLinkageValid());
11395
11396 // In ARC, infer lifetime.
11397 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11398 VDecl->setInvalidDecl();
11399
11400 if (getLangOpts().OpenCL)
11401 deduceOpenCLAddressSpace(VDecl);
11402
11403 // If this is a redeclaration, check that the type we just deduced matches
11404 // the previously declared type.
11405 if (VarDecl *Old = VDecl->getPreviousDecl()) {
11406 // We never need to merge the type, because we cannot form an incomplete
11407 // array of auto, nor deduce such a type.
11408 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11409 }
11410
11411 // Check the deduced type is valid for a variable declaration.
11412 CheckVariableDeclarationType(VDecl);
11413 return VDecl->isInvalidDecl();
11414 }
11415
checkNonTrivialCUnionInInitializer(const Expr * Init,SourceLocation Loc)11416 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11417 SourceLocation Loc) {
11418 if (auto *CE = dyn_cast<ConstantExpr>(Init))
11419 Init = CE->getSubExpr();
11420
11421 QualType InitType = Init->getType();
11422 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11423 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11424 "shouldn't be called if type doesn't have a non-trivial C struct");
11425 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11426 for (auto I : ILE->inits()) {
11427 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11428 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11429 continue;
11430 SourceLocation SL = I->getExprLoc();
11431 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11432 }
11433 return;
11434 }
11435
11436 if (isa<ImplicitValueInitExpr>(Init)) {
11437 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11438 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11439 NTCUK_Init);
11440 } else {
11441 // Assume all other explicit initializers involving copying some existing
11442 // object.
11443 // TODO: ignore any explicit initializers where we can guarantee
11444 // copy-elision.
11445 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11446 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11447 }
11448 }
11449
11450 namespace {
11451
shouldIgnoreForRecordTriviality(const FieldDecl * FD)11452 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11453 // Ignore unavailable fields. A field can be marked as unavailable explicitly
11454 // in the source code or implicitly by the compiler if it is in a union
11455 // defined in a system header and has non-trivial ObjC ownership
11456 // qualifications. We don't want those fields to participate in determining
11457 // whether the containing union is non-trivial.
11458 return FD->hasAttr<UnavailableAttr>();
11459 }
11460
11461 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11462 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11463 void> {
11464 using Super =
11465 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11466 void>;
11467
DiagNonTrivalCUnionDefaultInitializeVisitor__anon45468b3d1211::DiagNonTrivalCUnionDefaultInitializeVisitor11468 DiagNonTrivalCUnionDefaultInitializeVisitor(
11469 QualType OrigTy, SourceLocation OrigLoc,
11470 Sema::NonTrivialCUnionContext UseContext, Sema &S)
11471 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11472
visitWithKind__anon45468b3d1211::DiagNonTrivalCUnionDefaultInitializeVisitor11473 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11474 const FieldDecl *FD, bool InNonTrivialUnion) {
11475 if (const auto *AT = S.Context.getAsArrayType(QT))
11476 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11477 InNonTrivialUnion);
11478 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11479 }
11480
visitARCStrong__anon45468b3d1211::DiagNonTrivalCUnionDefaultInitializeVisitor11481 void visitARCStrong(QualType QT, const FieldDecl *FD,
11482 bool InNonTrivialUnion) {
11483 if (InNonTrivialUnion)
11484 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11485 << 1 << 0 << QT << FD->getName();
11486 }
11487
visitARCWeak__anon45468b3d1211::DiagNonTrivalCUnionDefaultInitializeVisitor11488 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11489 if (InNonTrivialUnion)
11490 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11491 << 1 << 0 << QT << FD->getName();
11492 }
11493
visitStruct__anon45468b3d1211::DiagNonTrivalCUnionDefaultInitializeVisitor11494 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11495 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11496 if (RD->isUnion()) {
11497 if (OrigLoc.isValid()) {
11498 bool IsUnion = false;
11499 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11500 IsUnion = OrigRD->isUnion();
11501 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11502 << 0 << OrigTy << IsUnion << UseContext;
11503 // Reset OrigLoc so that this diagnostic is emitted only once.
11504 OrigLoc = SourceLocation();
11505 }
11506 InNonTrivialUnion = true;
11507 }
11508
11509 if (InNonTrivialUnion)
11510 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11511 << 0 << 0 << QT.getUnqualifiedType() << "";
11512
11513 for (const FieldDecl *FD : RD->fields())
11514 if (!shouldIgnoreForRecordTriviality(FD))
11515 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11516 }
11517
visitTrivial__anon45468b3d1211::DiagNonTrivalCUnionDefaultInitializeVisitor11518 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11519
11520 // The non-trivial C union type or the struct/union type that contains a
11521 // non-trivial C union.
11522 QualType OrigTy;
11523 SourceLocation OrigLoc;
11524 Sema::NonTrivialCUnionContext UseContext;
11525 Sema &S;
11526 };
11527
11528 struct DiagNonTrivalCUnionDestructedTypeVisitor
11529 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11530 using Super =
11531 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11532
DiagNonTrivalCUnionDestructedTypeVisitor__anon45468b3d1211::DiagNonTrivalCUnionDestructedTypeVisitor11533 DiagNonTrivalCUnionDestructedTypeVisitor(
11534 QualType OrigTy, SourceLocation OrigLoc,
11535 Sema::NonTrivialCUnionContext UseContext, Sema &S)
11536 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11537
visitWithKind__anon45468b3d1211::DiagNonTrivalCUnionDestructedTypeVisitor11538 void visitWithKind(QualType::DestructionKind DK, QualType QT,
11539 const FieldDecl *FD, bool InNonTrivialUnion) {
11540 if (const auto *AT = S.Context.getAsArrayType(QT))
11541 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11542 InNonTrivialUnion);
11543 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11544 }
11545
visitARCStrong__anon45468b3d1211::DiagNonTrivalCUnionDestructedTypeVisitor11546 void visitARCStrong(QualType QT, const FieldDecl *FD,
11547 bool InNonTrivialUnion) {
11548 if (InNonTrivialUnion)
11549 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11550 << 1 << 1 << QT << FD->getName();
11551 }
11552
visitARCWeak__anon45468b3d1211::DiagNonTrivalCUnionDestructedTypeVisitor11553 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11554 if (InNonTrivialUnion)
11555 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11556 << 1 << 1 << QT << FD->getName();
11557 }
11558
visitStruct__anon45468b3d1211::DiagNonTrivalCUnionDestructedTypeVisitor11559 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11560 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11561 if (RD->isUnion()) {
11562 if (OrigLoc.isValid()) {
11563 bool IsUnion = false;
11564 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11565 IsUnion = OrigRD->isUnion();
11566 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11567 << 1 << OrigTy << IsUnion << UseContext;
11568 // Reset OrigLoc so that this diagnostic is emitted only once.
11569 OrigLoc = SourceLocation();
11570 }
11571 InNonTrivialUnion = true;
11572 }
11573
11574 if (InNonTrivialUnion)
11575 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11576 << 0 << 1 << QT.getUnqualifiedType() << "";
11577
11578 for (const FieldDecl *FD : RD->fields())
11579 if (!shouldIgnoreForRecordTriviality(FD))
11580 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11581 }
11582
visitTrivial__anon45468b3d1211::DiagNonTrivalCUnionDestructedTypeVisitor11583 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
visitCXXDestructor__anon45468b3d1211::DiagNonTrivalCUnionDestructedTypeVisitor11584 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11585 bool InNonTrivialUnion) {}
11586
11587 // The non-trivial C union type or the struct/union type that contains a
11588 // non-trivial C union.
11589 QualType OrigTy;
11590 SourceLocation OrigLoc;
11591 Sema::NonTrivialCUnionContext UseContext;
11592 Sema &S;
11593 };
11594
11595 struct DiagNonTrivalCUnionCopyVisitor
11596 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11597 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11598
DiagNonTrivalCUnionCopyVisitor__anon45468b3d1211::DiagNonTrivalCUnionCopyVisitor11599 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11600 Sema::NonTrivialCUnionContext UseContext,
11601 Sema &S)
11602 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11603
visitWithKind__anon45468b3d1211::DiagNonTrivalCUnionCopyVisitor11604 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11605 const FieldDecl *FD, bool InNonTrivialUnion) {
11606 if (const auto *AT = S.Context.getAsArrayType(QT))
11607 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11608 InNonTrivialUnion);
11609 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11610 }
11611
visitARCStrong__anon45468b3d1211::DiagNonTrivalCUnionCopyVisitor11612 void visitARCStrong(QualType QT, const FieldDecl *FD,
11613 bool InNonTrivialUnion) {
11614 if (InNonTrivialUnion)
11615 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11616 << 1 << 2 << QT << FD->getName();
11617 }
11618
visitARCWeak__anon45468b3d1211::DiagNonTrivalCUnionCopyVisitor11619 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11620 if (InNonTrivialUnion)
11621 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11622 << 1 << 2 << QT << FD->getName();
11623 }
11624
visitStruct__anon45468b3d1211::DiagNonTrivalCUnionCopyVisitor11625 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11626 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11627 if (RD->isUnion()) {
11628 if (OrigLoc.isValid()) {
11629 bool IsUnion = false;
11630 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11631 IsUnion = OrigRD->isUnion();
11632 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11633 << 2 << OrigTy << IsUnion << UseContext;
11634 // Reset OrigLoc so that this diagnostic is emitted only once.
11635 OrigLoc = SourceLocation();
11636 }
11637 InNonTrivialUnion = true;
11638 }
11639
11640 if (InNonTrivialUnion)
11641 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11642 << 0 << 2 << QT.getUnqualifiedType() << "";
11643
11644 for (const FieldDecl *FD : RD->fields())
11645 if (!shouldIgnoreForRecordTriviality(FD))
11646 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11647 }
11648
preVisit__anon45468b3d1211::DiagNonTrivalCUnionCopyVisitor11649 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11650 const FieldDecl *FD, bool InNonTrivialUnion) {}
visitTrivial__anon45468b3d1211::DiagNonTrivalCUnionCopyVisitor11651 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
visitVolatileTrivial__anon45468b3d1211::DiagNonTrivalCUnionCopyVisitor11652 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11653 bool InNonTrivialUnion) {}
11654
11655 // The non-trivial C union type or the struct/union type that contains a
11656 // non-trivial C union.
11657 QualType OrigTy;
11658 SourceLocation OrigLoc;
11659 Sema::NonTrivialCUnionContext UseContext;
11660 Sema &S;
11661 };
11662
11663 } // namespace
11664
checkNonTrivialCUnion(QualType QT,SourceLocation Loc,NonTrivialCUnionContext UseContext,unsigned NonTrivialKind)11665 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11666 NonTrivialCUnionContext UseContext,
11667 unsigned NonTrivialKind) {
11668 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11669 QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11670 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11671 "shouldn't be called if type doesn't have a non-trivial C union");
11672
11673 if ((NonTrivialKind & NTCUK_Init) &&
11674 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11675 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11676 .visit(QT, nullptr, false);
11677 if ((NonTrivialKind & NTCUK_Destruct) &&
11678 QT.hasNonTrivialToPrimitiveDestructCUnion())
11679 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11680 .visit(QT, nullptr, false);
11681 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11682 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11683 .visit(QT, nullptr, false);
11684 }
11685
11686 /// AddInitializerToDecl - Adds the initializer Init to the
11687 /// declaration dcl. If DirectInit is true, this is C++ direct
11688 /// initialization rather than copy initialization.
AddInitializerToDecl(Decl * RealDecl,Expr * Init,bool DirectInit)11689 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11690 // If there is no declaration, there was an error parsing it. Just ignore
11691 // the initializer.
11692 if (!RealDecl || RealDecl->isInvalidDecl()) {
11693 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11694 return;
11695 }
11696
11697 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11698 // Pure-specifiers are handled in ActOnPureSpecifier.
11699 Diag(Method->getLocation(), diag::err_member_function_initialization)
11700 << Method->getDeclName() << Init->getSourceRange();
11701 Method->setInvalidDecl();
11702 return;
11703 }
11704
11705 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11706 if (!VDecl) {
11707 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11708 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11709 RealDecl->setInvalidDecl();
11710 return;
11711 }
11712
11713 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11714 if (VDecl->getType()->isUndeducedType()) {
11715 // Attempt typo correction early so that the type of the init expression can
11716 // be deduced based on the chosen correction if the original init contains a
11717 // TypoExpr.
11718 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11719 if (!Res.isUsable()) {
11720 RealDecl->setInvalidDecl();
11721 return;
11722 }
11723 Init = Res.get();
11724
11725 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11726 return;
11727 }
11728
11729 // dllimport cannot be used on variable definitions.
11730 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11731 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11732 VDecl->setInvalidDecl();
11733 return;
11734 }
11735
11736 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11737 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11738 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11739 VDecl->setInvalidDecl();
11740 return;
11741 }
11742
11743 if (!VDecl->getType()->isDependentType()) {
11744 // A definition must end up with a complete type, which means it must be
11745 // complete with the restriction that an array type might be completed by
11746 // the initializer; note that later code assumes this restriction.
11747 QualType BaseDeclType = VDecl->getType();
11748 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11749 BaseDeclType = Array->getElementType();
11750 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11751 diag::err_typecheck_decl_incomplete_type)) {
11752 RealDecl->setInvalidDecl();
11753 return;
11754 }
11755
11756 // The variable can not have an abstract class type.
11757 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11758 diag::err_abstract_type_in_decl,
11759 AbstractVariableType))
11760 VDecl->setInvalidDecl();
11761 }
11762
11763 // If adding the initializer will turn this declaration into a definition,
11764 // and we already have a definition for this variable, diagnose or otherwise
11765 // handle the situation.
11766 VarDecl *Def;
11767 if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11768 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11769 !VDecl->isThisDeclarationADemotedDefinition() &&
11770 checkVarDeclRedefinition(Def, VDecl))
11771 return;
11772
11773 if (getLangOpts().CPlusPlus) {
11774 // C++ [class.static.data]p4
11775 // If a static data member is of const integral or const
11776 // enumeration type, its declaration in the class definition can
11777 // specify a constant-initializer which shall be an integral
11778 // constant expression (5.19). In that case, the member can appear
11779 // in integral constant expressions. The member shall still be
11780 // defined in a namespace scope if it is used in the program and the
11781 // namespace scope definition shall not contain an initializer.
11782 //
11783 // We already performed a redefinition check above, but for static
11784 // data members we also need to check whether there was an in-class
11785 // declaration with an initializer.
11786 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11787 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11788 << VDecl->getDeclName();
11789 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11790 diag::note_previous_initializer)
11791 << 0;
11792 return;
11793 }
11794
11795 if (VDecl->hasLocalStorage())
11796 setFunctionHasBranchProtectedScope();
11797
11798 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11799 VDecl->setInvalidDecl();
11800 return;
11801 }
11802 }
11803
11804 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11805 // a kernel function cannot be initialized."
11806 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11807 Diag(VDecl->getLocation(), diag::err_local_cant_init);
11808 VDecl->setInvalidDecl();
11809 return;
11810 }
11811
11812 // Get the decls type and save a reference for later, since
11813 // CheckInitializerTypes may change it.
11814 QualType DclT = VDecl->getType(), SavT = DclT;
11815
11816 // Expressions default to 'id' when we're in a debugger
11817 // and we are assigning it to a variable of Objective-C pointer type.
11818 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11819 Init->getType() == Context.UnknownAnyTy) {
11820 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11821 if (Result.isInvalid()) {
11822 VDecl->setInvalidDecl();
11823 return;
11824 }
11825 Init = Result.get();
11826 }
11827
11828 // Perform the initialization.
11829 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11830 if (!VDecl->isInvalidDecl()) {
11831 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11832 InitializationKind Kind = InitializationKind::CreateForInit(
11833 VDecl->getLocation(), DirectInit, Init);
11834
11835 MultiExprArg Args = Init;
11836 if (CXXDirectInit)
11837 Args = MultiExprArg(CXXDirectInit->getExprs(),
11838 CXXDirectInit->getNumExprs());
11839
11840 // Try to correct any TypoExprs in the initialization arguments.
11841 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11842 ExprResult Res = CorrectDelayedTyposInExpr(
11843 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11844 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11845 return Init.Failed() ? ExprError() : E;
11846 });
11847 if (Res.isInvalid()) {
11848 VDecl->setInvalidDecl();
11849 } else if (Res.get() != Args[Idx]) {
11850 Args[Idx] = Res.get();
11851 }
11852 }
11853 if (VDecl->isInvalidDecl())
11854 return;
11855
11856 InitializationSequence InitSeq(*this, Entity, Kind, Args,
11857 /*TopLevelOfInitList=*/false,
11858 /*TreatUnavailableAsInvalid=*/false);
11859 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11860 if (Result.isInvalid()) {
11861 VDecl->setInvalidDecl();
11862 return;
11863 }
11864
11865 Init = Result.getAs<Expr>();
11866 }
11867
11868 // Check for self-references within variable initializers.
11869 // Variables declared within a function/method body (except for references)
11870 // are handled by a dataflow analysis.
11871 // This is undefined behavior in C++, but valid in C.
11872 if (getLangOpts().CPlusPlus) {
11873 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11874 VDecl->getType()->isReferenceType()) {
11875 CheckSelfReference(*this, RealDecl, Init, DirectInit);
11876 }
11877 }
11878
11879 // If the type changed, it means we had an incomplete type that was
11880 // completed by the initializer. For example:
11881 // int ary[] = { 1, 3, 5 };
11882 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11883 if (!VDecl->isInvalidDecl() && (DclT != SavT))
11884 VDecl->setType(DclT);
11885
11886 if (!VDecl->isInvalidDecl()) {
11887 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11888
11889 if (VDecl->hasAttr<BlocksAttr>())
11890 checkRetainCycles(VDecl, Init);
11891
11892 // It is safe to assign a weak reference into a strong variable.
11893 // Although this code can still have problems:
11894 // id x = self.weakProp;
11895 // id y = self.weakProp;
11896 // we do not warn to warn spuriously when 'x' and 'y' are on separate
11897 // paths through the function. This should be revisited if
11898 // -Wrepeated-use-of-weak is made flow-sensitive.
11899 if (FunctionScopeInfo *FSI = getCurFunction())
11900 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11901 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11902 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11903 Init->getBeginLoc()))
11904 FSI->markSafeWeakUse(Init);
11905 }
11906
11907 // The initialization is usually a full-expression.
11908 //
11909 // FIXME: If this is a braced initialization of an aggregate, it is not
11910 // an expression, and each individual field initializer is a separate
11911 // full-expression. For instance, in:
11912 //
11913 // struct Temp { ~Temp(); };
11914 // struct S { S(Temp); };
11915 // struct T { S a, b; } t = { Temp(), Temp() }
11916 //
11917 // we should destroy the first Temp before constructing the second.
11918 ExprResult Result =
11919 ActOnFinishFullExpr(Init, VDecl->getLocation(),
11920 /*DiscardedValue*/ false, VDecl->isConstexpr());
11921 if (Result.isInvalid()) {
11922 VDecl->setInvalidDecl();
11923 return;
11924 }
11925 Init = Result.get();
11926
11927 // Attach the initializer to the decl.
11928 VDecl->setInit(Init);
11929
11930 if (VDecl->isLocalVarDecl()) {
11931 // Don't check the initializer if the declaration is malformed.
11932 if (VDecl->isInvalidDecl()) {
11933 // do nothing
11934
11935 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11936 // This is true even in C++ for OpenCL.
11937 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11938 CheckForConstantInitializer(Init, DclT);
11939
11940 // Otherwise, C++ does not restrict the initializer.
11941 } else if (getLangOpts().CPlusPlus) {
11942 // do nothing
11943
11944 // C99 6.7.8p4: All the expressions in an initializer for an object that has
11945 // static storage duration shall be constant expressions or string literals.
11946 } else if (VDecl->getStorageClass() == SC_Static) {
11947 CheckForConstantInitializer(Init, DclT);
11948
11949 // C89 is stricter than C99 for aggregate initializers.
11950 // C89 6.5.7p3: All the expressions [...] in an initializer list
11951 // for an object that has aggregate or union type shall be
11952 // constant expressions.
11953 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11954 isa<InitListExpr>(Init)) {
11955 const Expr *Culprit;
11956 if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11957 Diag(Culprit->getExprLoc(),
11958 diag::ext_aggregate_init_not_constant)
11959 << Culprit->getSourceRange();
11960 }
11961 }
11962
11963 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
11964 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
11965 if (VDecl->hasLocalStorage())
11966 BE->getBlockDecl()->setCanAvoidCopyToHeap();
11967 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11968 VDecl->getLexicalDeclContext()->isRecord()) {
11969 // This is an in-class initialization for a static data member, e.g.,
11970 //
11971 // struct S {
11972 // static const int value = 17;
11973 // };
11974
11975 // C++ [class.mem]p4:
11976 // A member-declarator can contain a constant-initializer only
11977 // if it declares a static member (9.4) of const integral or
11978 // const enumeration type, see 9.4.2.
11979 //
11980 // C++11 [class.static.data]p3:
11981 // If a non-volatile non-inline const static data member is of integral
11982 // or enumeration type, its declaration in the class definition can
11983 // specify a brace-or-equal-initializer in which every initializer-clause
11984 // that is an assignment-expression is a constant expression. A static
11985 // data member of literal type can be declared in the class definition
11986 // with the constexpr specifier; if so, its declaration shall specify a
11987 // brace-or-equal-initializer in which every initializer-clause that is
11988 // an assignment-expression is a constant expression.
11989
11990 // Do nothing on dependent types.
11991 if (DclT->isDependentType()) {
11992
11993 // Allow any 'static constexpr' members, whether or not they are of literal
11994 // type. We separately check that every constexpr variable is of literal
11995 // type.
11996 } else if (VDecl->isConstexpr()) {
11997
11998 // Require constness.
11999 } else if (!DclT.isConstQualified()) {
12000 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12001 << Init->getSourceRange();
12002 VDecl->setInvalidDecl();
12003
12004 // We allow integer constant expressions in all cases.
12005 } else if (DclT->isIntegralOrEnumerationType()) {
12006 // Check whether the expression is a constant expression.
12007 SourceLocation Loc;
12008 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12009 // In C++11, a non-constexpr const static data member with an
12010 // in-class initializer cannot be volatile.
12011 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12012 else if (Init->isValueDependent())
12013 ; // Nothing to check.
12014 else if (Init->isIntegerConstantExpr(Context, &Loc))
12015 ; // Ok, it's an ICE!
12016 else if (Init->getType()->isScopedEnumeralType() &&
12017 Init->isCXX11ConstantExpr(Context))
12018 ; // Ok, it is a scoped-enum constant expression.
12019 else if (Init->isEvaluatable(Context)) {
12020 // If we can constant fold the initializer through heroics, accept it,
12021 // but report this as a use of an extension for -pedantic.
12022 Diag(Loc, diag::ext_in_class_initializer_non_constant)
12023 << Init->getSourceRange();
12024 } else {
12025 // Otherwise, this is some crazy unknown case. Report the issue at the
12026 // location provided by the isIntegerConstantExpr failed check.
12027 Diag(Loc, diag::err_in_class_initializer_non_constant)
12028 << Init->getSourceRange();
12029 VDecl->setInvalidDecl();
12030 }
12031
12032 // We allow foldable floating-point constants as an extension.
12033 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12034 // In C++98, this is a GNU extension. In C++11, it is not, but we support
12035 // it anyway and provide a fixit to add the 'constexpr'.
12036 if (getLangOpts().CPlusPlus11) {
12037 Diag(VDecl->getLocation(),
12038 diag::ext_in_class_initializer_float_type_cxx11)
12039 << DclT << Init->getSourceRange();
12040 Diag(VDecl->getBeginLoc(),
12041 diag::note_in_class_initializer_float_type_cxx11)
12042 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12043 } else {
12044 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12045 << DclT << Init->getSourceRange();
12046
12047 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12048 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12049 << Init->getSourceRange();
12050 VDecl->setInvalidDecl();
12051 }
12052 }
12053
12054 // Suggest adding 'constexpr' in C++11 for literal types.
12055 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12056 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12057 << DclT << Init->getSourceRange()
12058 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12059 VDecl->setConstexpr(true);
12060
12061 } else {
12062 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12063 << DclT << Init->getSourceRange();
12064 VDecl->setInvalidDecl();
12065 }
12066 } else if (VDecl->isFileVarDecl()) {
12067 // In C, extern is typically used to avoid tentative definitions when
12068 // declaring variables in headers, but adding an intializer makes it a
12069 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12070 // In C++, extern is often used to give implictly static const variables
12071 // external linkage, so don't warn in that case. If selectany is present,
12072 // this might be header code intended for C and C++ inclusion, so apply the
12073 // C++ rules.
12074 if (VDecl->getStorageClass() == SC_Extern &&
12075 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12076 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12077 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12078 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12079 Diag(VDecl->getLocation(), diag::warn_extern_init);
12080
12081 // In Microsoft C++ mode, a const variable defined in namespace scope has
12082 // external linkage by default if the variable is declared with
12083 // __declspec(dllexport).
12084 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12085 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12086 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12087 VDecl->setStorageClass(SC_Extern);
12088
12089 // C99 6.7.8p4. All file scoped initializers need to be constant.
12090 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12091 CheckForConstantInitializer(Init, DclT);
12092 }
12093
12094 QualType InitType = Init->getType();
12095 if (!InitType.isNull() &&
12096 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12097 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12098 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12099
12100 // We will represent direct-initialization similarly to copy-initialization:
12101 // int x(1); -as-> int x = 1;
12102 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12103 //
12104 // Clients that want to distinguish between the two forms, can check for
12105 // direct initializer using VarDecl::getInitStyle().
12106 // A major benefit is that clients that don't particularly care about which
12107 // exactly form was it (like the CodeGen) can handle both cases without
12108 // special case code.
12109
12110 // C++ 8.5p11:
12111 // The form of initialization (using parentheses or '=') is generally
12112 // insignificant, but does matter when the entity being initialized has a
12113 // class type.
12114 if (CXXDirectInit) {
12115 assert(DirectInit && "Call-style initializer must be direct init.");
12116 VDecl->setInitStyle(VarDecl::CallInit);
12117 } else if (DirectInit) {
12118 // This must be list-initialization. No other way is direct-initialization.
12119 VDecl->setInitStyle(VarDecl::ListInit);
12120 }
12121
12122 CheckCompleteVariableDeclaration(VDecl);
12123 }
12124
12125 /// ActOnInitializerError - Given that there was an error parsing an
12126 /// initializer for the given declaration, try to return to some form
12127 /// of sanity.
ActOnInitializerError(Decl * D)12128 void Sema::ActOnInitializerError(Decl *D) {
12129 // Our main concern here is re-establishing invariants like "a
12130 // variable's type is either dependent or complete".
12131 if (!D || D->isInvalidDecl()) return;
12132
12133 VarDecl *VD = dyn_cast<VarDecl>(D);
12134 if (!VD) return;
12135
12136 // Bindings are not usable if we can't make sense of the initializer.
12137 if (auto *DD = dyn_cast<DecompositionDecl>(D))
12138 for (auto *BD : DD->bindings())
12139 BD->setInvalidDecl();
12140
12141 // Auto types are meaningless if we can't make sense of the initializer.
12142 if (ParsingInitForAutoVars.count(D)) {
12143 D->setInvalidDecl();
12144 return;
12145 }
12146
12147 QualType Ty = VD->getType();
12148 if (Ty->isDependentType()) return;
12149
12150 // Require a complete type.
12151 if (RequireCompleteType(VD->getLocation(),
12152 Context.getBaseElementType(Ty),
12153 diag::err_typecheck_decl_incomplete_type)) {
12154 VD->setInvalidDecl();
12155 return;
12156 }
12157
12158 // Require a non-abstract type.
12159 if (RequireNonAbstractType(VD->getLocation(), Ty,
12160 diag::err_abstract_type_in_decl,
12161 AbstractVariableType)) {
12162 VD->setInvalidDecl();
12163 return;
12164 }
12165
12166 // Don't bother complaining about constructors or destructors,
12167 // though.
12168 }
12169
ActOnUninitializedDecl(Decl * RealDecl)12170 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12171 // If there is no declaration, there was an error parsing it. Just ignore it.
12172 if (!RealDecl)
12173 return;
12174
12175 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12176 QualType Type = Var->getType();
12177
12178 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12179 if (isa<DecompositionDecl>(RealDecl)) {
12180 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12181 Var->setInvalidDecl();
12182 return;
12183 }
12184
12185 if (Type->isUndeducedType() &&
12186 DeduceVariableDeclarationType(Var, false, nullptr))
12187 return;
12188
12189 // C++11 [class.static.data]p3: A static data member can be declared with
12190 // the constexpr specifier; if so, its declaration shall specify
12191 // a brace-or-equal-initializer.
12192 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12193 // the definition of a variable [...] or the declaration of a static data
12194 // member.
12195 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12196 !Var->isThisDeclarationADemotedDefinition()) {
12197 if (Var->isStaticDataMember()) {
12198 // C++1z removes the relevant rule; the in-class declaration is always
12199 // a definition there.
12200 if (!getLangOpts().CPlusPlus17 &&
12201 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12202 Diag(Var->getLocation(),
12203 diag::err_constexpr_static_mem_var_requires_init)
12204 << Var->getDeclName();
12205 Var->setInvalidDecl();
12206 return;
12207 }
12208 } else {
12209 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12210 Var->setInvalidDecl();
12211 return;
12212 }
12213 }
12214
12215 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12216 // be initialized.
12217 if (!Var->isInvalidDecl() &&
12218 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12219 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12220 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12221 Var->setInvalidDecl();
12222 return;
12223 }
12224
12225 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12226 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12227 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12228 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12229 NTCUC_DefaultInitializedObject, NTCUK_Init);
12230
12231
12232 switch (DefKind) {
12233 case VarDecl::Definition:
12234 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12235 break;
12236
12237 // We have an out-of-line definition of a static data member
12238 // that has an in-class initializer, so we type-check this like
12239 // a declaration.
12240 //
12241 LLVM_FALLTHROUGH;
12242
12243 case VarDecl::DeclarationOnly:
12244 // It's only a declaration.
12245
12246 // Block scope. C99 6.7p7: If an identifier for an object is
12247 // declared with no linkage (C99 6.2.2p6), the type for the
12248 // object shall be complete.
12249 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12250 !Var->hasLinkage() && !Var->isInvalidDecl() &&
12251 RequireCompleteType(Var->getLocation(), Type,
12252 diag::err_typecheck_decl_incomplete_type))
12253 Var->setInvalidDecl();
12254
12255 // Make sure that the type is not abstract.
12256 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12257 RequireNonAbstractType(Var->getLocation(), Type,
12258 diag::err_abstract_type_in_decl,
12259 AbstractVariableType))
12260 Var->setInvalidDecl();
12261 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12262 Var->getStorageClass() == SC_PrivateExtern) {
12263 Diag(Var->getLocation(), diag::warn_private_extern);
12264 Diag(Var->getLocation(), diag::note_private_extern);
12265 }
12266
12267 if (Context.getTargetInfo().allowDebugInfoForExternalVar() &&
12268 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12269 ExternalDeclarations.push_back(Var);
12270
12271 return;
12272
12273 case VarDecl::TentativeDefinition:
12274 // File scope. C99 6.9.2p2: A declaration of an identifier for an
12275 // object that has file scope without an initializer, and without a
12276 // storage-class specifier or with the storage-class specifier "static",
12277 // constitutes a tentative definition. Note: A tentative definition with
12278 // external linkage is valid (C99 6.2.2p5).
12279 if (!Var->isInvalidDecl()) {
12280 if (const IncompleteArrayType *ArrayT
12281 = Context.getAsIncompleteArrayType(Type)) {
12282 if (RequireCompleteType(Var->getLocation(),
12283 ArrayT->getElementType(),
12284 diag::err_illegal_decl_array_incomplete_type))
12285 Var->setInvalidDecl();
12286 } else if (Var->getStorageClass() == SC_Static) {
12287 // C99 6.9.2p3: If the declaration of an identifier for an object is
12288 // a tentative definition and has internal linkage (C99 6.2.2p3), the
12289 // declared type shall not be an incomplete type.
12290 // NOTE: code such as the following
12291 // static struct s;
12292 // struct s { int a; };
12293 // is accepted by gcc. Hence here we issue a warning instead of
12294 // an error and we do not invalidate the static declaration.
12295 // NOTE: to avoid multiple warnings, only check the first declaration.
12296 if (Var->isFirstDecl())
12297 RequireCompleteType(Var->getLocation(), Type,
12298 diag::ext_typecheck_decl_incomplete_type);
12299 }
12300 }
12301
12302 // Record the tentative definition; we're done.
12303 if (!Var->isInvalidDecl())
12304 TentativeDefinitions.push_back(Var);
12305 return;
12306 }
12307
12308 // Provide a specific diagnostic for uninitialized variable
12309 // definitions with incomplete array type.
12310 if (Type->isIncompleteArrayType()) {
12311 Diag(Var->getLocation(),
12312 diag::err_typecheck_incomplete_array_needs_initializer);
12313 Var->setInvalidDecl();
12314 return;
12315 }
12316
12317 // Provide a specific diagnostic for uninitialized variable
12318 // definitions with reference type.
12319 if (Type->isReferenceType()) {
12320 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12321 << Var->getDeclName()
12322 << SourceRange(Var->getLocation(), Var->getLocation());
12323 Var->setInvalidDecl();
12324 return;
12325 }
12326
12327 // Do not attempt to type-check the default initializer for a
12328 // variable with dependent type.
12329 if (Type->isDependentType())
12330 return;
12331
12332 if (Var->isInvalidDecl())
12333 return;
12334
12335 if (!Var->hasAttr<AliasAttr>()) {
12336 if (RequireCompleteType(Var->getLocation(),
12337 Context.getBaseElementType(Type),
12338 diag::err_typecheck_decl_incomplete_type)) {
12339 Var->setInvalidDecl();
12340 return;
12341 }
12342 } else {
12343 return;
12344 }
12345
12346 // The variable can not have an abstract class type.
12347 if (RequireNonAbstractType(Var->getLocation(), Type,
12348 diag::err_abstract_type_in_decl,
12349 AbstractVariableType)) {
12350 Var->setInvalidDecl();
12351 return;
12352 }
12353
12354 // Check for jumps past the implicit initializer. C++0x
12355 // clarifies that this applies to a "variable with automatic
12356 // storage duration", not a "local variable".
12357 // C++11 [stmt.dcl]p3
12358 // A program that jumps from a point where a variable with automatic
12359 // storage duration is not in scope to a point where it is in scope is
12360 // ill-formed unless the variable has scalar type, class type with a
12361 // trivial default constructor and a trivial destructor, a cv-qualified
12362 // version of one of these types, or an array of one of the preceding
12363 // types and is declared without an initializer.
12364 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12365 if (const RecordType *Record
12366 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12367 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12368 // Mark the function (if we're in one) for further checking even if the
12369 // looser rules of C++11 do not require such checks, so that we can
12370 // diagnose incompatibilities with C++98.
12371 if (!CXXRecord->isPOD())
12372 setFunctionHasBranchProtectedScope();
12373 }
12374 }
12375 // In OpenCL, we can't initialize objects in the __local address space,
12376 // even implicitly, so don't synthesize an implicit initializer.
12377 if (getLangOpts().OpenCL &&
12378 Var->getType().getAddressSpace() == LangAS::opencl_local)
12379 return;
12380 // C++03 [dcl.init]p9:
12381 // If no initializer is specified for an object, and the
12382 // object is of (possibly cv-qualified) non-POD class type (or
12383 // array thereof), the object shall be default-initialized; if
12384 // the object is of const-qualified type, the underlying class
12385 // type shall have a user-declared default
12386 // constructor. Otherwise, if no initializer is specified for
12387 // a non- static object, the object and its subobjects, if
12388 // any, have an indeterminate initial value); if the object
12389 // or any of its subobjects are of const-qualified type, the
12390 // program is ill-formed.
12391 // C++0x [dcl.init]p11:
12392 // If no initializer is specified for an object, the object is
12393 // default-initialized; [...].
12394 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12395 InitializationKind Kind
12396 = InitializationKind::CreateDefault(Var->getLocation());
12397
12398 InitializationSequence InitSeq(*this, Entity, Kind, None);
12399 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12400 if (Init.isInvalid())
12401 Var->setInvalidDecl();
12402 else if (Init.get()) {
12403 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12404 // This is important for template substitution.
12405 Var->setInitStyle(VarDecl::CallInit);
12406 }
12407
12408 CheckCompleteVariableDeclaration(Var);
12409 }
12410 }
12411
ActOnCXXForRangeDecl(Decl * D)12412 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12413 // If there is no declaration, there was an error parsing it. Ignore it.
12414 if (!D)
12415 return;
12416
12417 VarDecl *VD = dyn_cast<VarDecl>(D);
12418 if (!VD) {
12419 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12420 D->setInvalidDecl();
12421 return;
12422 }
12423
12424 VD->setCXXForRangeDecl(true);
12425
12426 // for-range-declaration cannot be given a storage class specifier.
12427 int Error = -1;
12428 switch (VD->getStorageClass()) {
12429 case SC_None:
12430 break;
12431 case SC_Extern:
12432 Error = 0;
12433 break;
12434 case SC_Static:
12435 Error = 1;
12436 break;
12437 case SC_PrivateExtern:
12438 Error = 2;
12439 break;
12440 case SC_Auto:
12441 Error = 3;
12442 break;
12443 case SC_Register:
12444 Error = 4;
12445 break;
12446 }
12447 if (Error != -1) {
12448 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12449 << VD->getDeclName() << Error;
12450 D->setInvalidDecl();
12451 }
12452 }
12453
12454 StmtResult
ActOnCXXForRangeIdentifier(Scope * S,SourceLocation IdentLoc,IdentifierInfo * Ident,ParsedAttributes & Attrs,SourceLocation AttrEnd)12455 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12456 IdentifierInfo *Ident,
12457 ParsedAttributes &Attrs,
12458 SourceLocation AttrEnd) {
12459 // C++1y [stmt.iter]p1:
12460 // A range-based for statement of the form
12461 // for ( for-range-identifier : for-range-initializer ) statement
12462 // is equivalent to
12463 // for ( auto&& for-range-identifier : for-range-initializer ) statement
12464 DeclSpec DS(Attrs.getPool().getFactory());
12465
12466 const char *PrevSpec;
12467 unsigned DiagID;
12468 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12469 getPrintingPolicy());
12470
12471 Declarator D(DS, DeclaratorContext::ForContext);
12472 D.SetIdentifier(Ident, IdentLoc);
12473 D.takeAttributes(Attrs, AttrEnd);
12474
12475 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12476 IdentLoc);
12477 Decl *Var = ActOnDeclarator(S, D);
12478 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12479 FinalizeDeclaration(Var);
12480 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12481 AttrEnd.isValid() ? AttrEnd : IdentLoc);
12482 }
12483
CheckCompleteVariableDeclaration(VarDecl * var)12484 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12485 if (var->isInvalidDecl()) return;
12486
12487 if (getLangOpts().OpenCL) {
12488 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12489 // initialiser
12490 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12491 !var->hasInit()) {
12492 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12493 << 1 /*Init*/;
12494 var->setInvalidDecl();
12495 return;
12496 }
12497 }
12498
12499 // In Objective-C, don't allow jumps past the implicit initialization of a
12500 // local retaining variable.
12501 if (getLangOpts().ObjC &&
12502 var->hasLocalStorage()) {
12503 switch (var->getType().getObjCLifetime()) {
12504 case Qualifiers::OCL_None:
12505 case Qualifiers::OCL_ExplicitNone:
12506 case Qualifiers::OCL_Autoreleasing:
12507 break;
12508
12509 case Qualifiers::OCL_Weak:
12510 case Qualifiers::OCL_Strong:
12511 setFunctionHasBranchProtectedScope();
12512 break;
12513 }
12514 }
12515
12516 if (var->hasLocalStorage() &&
12517 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12518 setFunctionHasBranchProtectedScope();
12519
12520 // Warn about externally-visible variables being defined without a
12521 // prior declaration. We only want to do this for global
12522 // declarations, but we also specifically need to avoid doing it for
12523 // class members because the linkage of an anonymous class can
12524 // change if it's later given a typedef name.
12525 if (var->isThisDeclarationADefinition() &&
12526 var->getDeclContext()->getRedeclContext()->isFileContext() &&
12527 var->isExternallyVisible() && var->hasLinkage() &&
12528 !var->isInline() && !var->getDescribedVarTemplate() &&
12529 !isa<VarTemplatePartialSpecializationDecl>(var) &&
12530 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12531 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12532 var->getLocation())) {
12533 // Find a previous declaration that's not a definition.
12534 VarDecl *prev = var->getPreviousDecl();
12535 while (prev && prev->isThisDeclarationADefinition())
12536 prev = prev->getPreviousDecl();
12537
12538 if (!prev) {
12539 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12540 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12541 << /* variable */ 0;
12542 }
12543 }
12544
12545 // Cache the result of checking for constant initialization.
12546 Optional<bool> CacheHasConstInit;
12547 const Expr *CacheCulprit = nullptr;
12548 auto checkConstInit = [&]() mutable {
12549 if (!CacheHasConstInit)
12550 CacheHasConstInit = var->getInit()->isConstantInitializer(
12551 Context, var->getType()->isReferenceType(), &CacheCulprit);
12552 return *CacheHasConstInit;
12553 };
12554
12555 if (var->getTLSKind() == VarDecl::TLS_Static) {
12556 if (var->getType().isDestructedType()) {
12557 // GNU C++98 edits for __thread, [basic.start.term]p3:
12558 // The type of an object with thread storage duration shall not
12559 // have a non-trivial destructor.
12560 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12561 if (getLangOpts().CPlusPlus11)
12562 Diag(var->getLocation(), diag::note_use_thread_local);
12563 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12564 if (!checkConstInit()) {
12565 // GNU C++98 edits for __thread, [basic.start.init]p4:
12566 // An object of thread storage duration shall not require dynamic
12567 // initialization.
12568 // FIXME: Need strict checking here.
12569 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12570 << CacheCulprit->getSourceRange();
12571 if (getLangOpts().CPlusPlus11)
12572 Diag(var->getLocation(), diag::note_use_thread_local);
12573 }
12574 }
12575 }
12576
12577 // Apply section attributes and pragmas to global variables.
12578 bool GlobalStorage = var->hasGlobalStorage();
12579 if (GlobalStorage && var->isThisDeclarationADefinition() &&
12580 !inTemplateInstantiation()) {
12581 PragmaStack<StringLiteral *> *Stack = nullptr;
12582 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
12583 if (var->getType().isConstQualified())
12584 Stack = &ConstSegStack;
12585 else if (!var->getInit()) {
12586 Stack = &BSSSegStack;
12587 SectionFlags |= ASTContext::PSF_Write;
12588 } else {
12589 Stack = &DataSegStack;
12590 SectionFlags |= ASTContext::PSF_Write;
12591 }
12592 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>())
12593 var->addAttr(SectionAttr::CreateImplicit(
12594 Context, Stack->CurrentValue->getString(),
12595 Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
12596 SectionAttr::Declspec_allocate));
12597 if (const SectionAttr *SA = var->getAttr<SectionAttr>())
12598 if (UnifySection(SA->getName(), SectionFlags, var))
12599 var->dropAttr<SectionAttr>();
12600
12601 // Apply the init_seg attribute if this has an initializer. If the
12602 // initializer turns out to not be dynamic, we'll end up ignoring this
12603 // attribute.
12604 if (CurInitSeg && var->getInit())
12605 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12606 CurInitSegLoc,
12607 AttributeCommonInfo::AS_Pragma));
12608 }
12609
12610 // All the following checks are C++ only.
12611 if (!getLangOpts().CPlusPlus) {
12612 // If this variable must be emitted, add it as an initializer for the
12613 // current module.
12614 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12615 Context.addModuleInitializer(ModuleScopes.back().Module, var);
12616 return;
12617 }
12618
12619 if (auto *DD = dyn_cast<DecompositionDecl>(var))
12620 CheckCompleteDecompositionDeclaration(DD);
12621
12622 QualType type = var->getType();
12623 if (type->isDependentType()) return;
12624
12625 if (var->hasAttr<BlocksAttr>())
12626 getCurFunction()->addByrefBlockVar(var);
12627
12628 Expr *Init = var->getInit();
12629 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12630 QualType baseType = Context.getBaseElementType(type);
12631
12632 if (Init && !Init->isValueDependent()) {
12633 if (var->isConstexpr()) {
12634 SmallVector<PartialDiagnosticAt, 8> Notes;
12635 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12636 SourceLocation DiagLoc = var->getLocation();
12637 // If the note doesn't add any useful information other than a source
12638 // location, fold it into the primary diagnostic.
12639 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12640 diag::note_invalid_subexpr_in_const_expr) {
12641 DiagLoc = Notes[0].first;
12642 Notes.clear();
12643 }
12644 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12645 << var << Init->getSourceRange();
12646 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12647 Diag(Notes[I].first, Notes[I].second);
12648 }
12649 } else if (var->mightBeUsableInConstantExpressions(Context)) {
12650 // Check whether the initializer of a const variable of integral or
12651 // enumeration type is an ICE now, since we can't tell whether it was
12652 // initialized by a constant expression if we check later.
12653 var->checkInitIsICE();
12654 }
12655
12656 // Don't emit further diagnostics about constexpr globals since they
12657 // were just diagnosed.
12658 if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
12659 // FIXME: Need strict checking in C++03 here.
12660 bool DiagErr = getLangOpts().CPlusPlus11
12661 ? !var->checkInitIsICE() : !checkConstInit();
12662 if (DiagErr) {
12663 auto *Attr = var->getAttr<ConstInitAttr>();
12664 Diag(var->getLocation(), diag::err_require_constant_init_failed)
12665 << Init->getSourceRange();
12666 Diag(Attr->getLocation(),
12667 diag::note_declared_required_constant_init_here)
12668 << Attr->getRange() << Attr->isConstinit();
12669 if (getLangOpts().CPlusPlus11) {
12670 APValue Value;
12671 SmallVector<PartialDiagnosticAt, 8> Notes;
12672 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12673 for (auto &it : Notes)
12674 Diag(it.first, it.second);
12675 } else {
12676 Diag(CacheCulprit->getExprLoc(),
12677 diag::note_invalid_subexpr_in_const_expr)
12678 << CacheCulprit->getSourceRange();
12679 }
12680 }
12681 }
12682 else if (!var->isConstexpr() && IsGlobal &&
12683 !getDiagnostics().isIgnored(diag::warn_global_constructor,
12684 var->getLocation())) {
12685 // Warn about globals which don't have a constant initializer. Don't
12686 // warn about globals with a non-trivial destructor because we already
12687 // warned about them.
12688 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12689 if (!(RD && !RD->hasTrivialDestructor())) {
12690 if (!checkConstInit())
12691 Diag(var->getLocation(), diag::warn_global_constructor)
12692 << Init->getSourceRange();
12693 }
12694 }
12695 }
12696
12697 // Require the destructor.
12698 if (const RecordType *recordType = baseType->getAs<RecordType>())
12699 FinalizeVarWithDestructor(var, recordType);
12700
12701 // If this variable must be emitted, add it as an initializer for the current
12702 // module.
12703 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12704 Context.addModuleInitializer(ModuleScopes.back().Module, var);
12705 }
12706
12707 /// Determines if a variable's alignment is dependent.
hasDependentAlignment(VarDecl * VD)12708 static bool hasDependentAlignment(VarDecl *VD) {
12709 if (VD->getType()->isDependentType())
12710 return true;
12711 for (auto *I : VD->specific_attrs<AlignedAttr>())
12712 if (I->isAlignmentDependent())
12713 return true;
12714 return false;
12715 }
12716
12717 /// Check if VD needs to be dllexport/dllimport due to being in a
12718 /// dllexport/import function.
CheckStaticLocalForDllExport(VarDecl * VD)12719 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12720 assert(VD->isStaticLocal());
12721
12722 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12723
12724 // Find outermost function when VD is in lambda function.
12725 while (FD && !getDLLAttr(FD) &&
12726 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12727 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12728 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12729 }
12730
12731 if (!FD)
12732 return;
12733
12734 // Static locals inherit dll attributes from their function.
12735 if (Attr *A = getDLLAttr(FD)) {
12736 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12737 NewAttr->setInherited(true);
12738 VD->addAttr(NewAttr);
12739 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12740 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
12741 NewAttr->setInherited(true);
12742 VD->addAttr(NewAttr);
12743
12744 // Export this function to enforce exporting this static variable even
12745 // if it is not used in this compilation unit.
12746 if (!FD->hasAttr<DLLExportAttr>())
12747 FD->addAttr(NewAttr);
12748
12749 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12750 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
12751 NewAttr->setInherited(true);
12752 VD->addAttr(NewAttr);
12753 }
12754 }
12755
12756 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12757 /// any semantic actions necessary after any initializer has been attached.
FinalizeDeclaration(Decl * ThisDecl)12758 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12759 // Note that we are no longer parsing the initializer for this declaration.
12760 ParsingInitForAutoVars.erase(ThisDecl);
12761
12762 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12763 if (!VD)
12764 return;
12765
12766 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12767 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12768 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12769 if (PragmaClangBSSSection.Valid)
12770 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
12771 Context, PragmaClangBSSSection.SectionName,
12772 PragmaClangBSSSection.PragmaLocation,
12773 AttributeCommonInfo::AS_Pragma));
12774 if (PragmaClangDataSection.Valid)
12775 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
12776 Context, PragmaClangDataSection.SectionName,
12777 PragmaClangDataSection.PragmaLocation,
12778 AttributeCommonInfo::AS_Pragma));
12779 if (PragmaClangRodataSection.Valid)
12780 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
12781 Context, PragmaClangRodataSection.SectionName,
12782 PragmaClangRodataSection.PragmaLocation,
12783 AttributeCommonInfo::AS_Pragma));
12784 if (PragmaClangRelroSection.Valid)
12785 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
12786 Context, PragmaClangRelroSection.SectionName,
12787 PragmaClangRelroSection.PragmaLocation,
12788 AttributeCommonInfo::AS_Pragma));
12789 }
12790
12791 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12792 for (auto *BD : DD->bindings()) {
12793 FinalizeDeclaration(BD);
12794 }
12795 }
12796
12797 checkAttributesAfterMerging(*this, *VD);
12798
12799 // Perform TLS alignment check here after attributes attached to the variable
12800 // which may affect the alignment have been processed. Only perform the check
12801 // if the target has a maximum TLS alignment (zero means no constraints).
12802 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12803 // Protect the check so that it's not performed on dependent types and
12804 // dependent alignments (we can't determine the alignment in that case).
12805 if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12806 !VD->isInvalidDecl()) {
12807 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12808 if (Context.getDeclAlign(VD) > MaxAlignChars) {
12809 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12810 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12811 << (unsigned)MaxAlignChars.getQuantity();
12812 }
12813 }
12814 }
12815
12816 if (VD->isStaticLocal()) {
12817 CheckStaticLocalForDllExport(VD);
12818
12819 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12820 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12821 // function, only __shared__ variables or variables without any device
12822 // memory qualifiers may be declared with static storage class.
12823 // Note: It is unclear how a function-scope non-const static variable
12824 // without device memory qualifier is implemented, therefore only static
12825 // const variable without device memory qualifier is allowed.
12826 [&]() {
12827 if (!getLangOpts().CUDA)
12828 return;
12829 if (VD->hasAttr<CUDASharedAttr>())
12830 return;
12831 if (VD->getType().isConstQualified() &&
12832 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12833 return;
12834 if (CUDADiagIfDeviceCode(VD->getLocation(),
12835 diag::err_device_static_local_var)
12836 << CurrentCUDATarget())
12837 VD->setInvalidDecl();
12838 }();
12839 }
12840 }
12841
12842 // Perform check for initializers of device-side global variables.
12843 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12844 // 7.5). We must also apply the same checks to all __shared__
12845 // variables whether they are local or not. CUDA also allows
12846 // constant initializers for __constant__ and __device__ variables.
12847 if (getLangOpts().CUDA)
12848 checkAllowedCUDAInitializer(VD);
12849
12850 // Grab the dllimport or dllexport attribute off of the VarDecl.
12851 const InheritableAttr *DLLAttr = getDLLAttr(VD);
12852
12853 // Imported static data members cannot be defined out-of-line.
12854 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12855 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12856 VD->isThisDeclarationADefinition()) {
12857 // We allow definitions of dllimport class template static data members
12858 // with a warning.
12859 CXXRecordDecl *Context =
12860 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12861 bool IsClassTemplateMember =
12862 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12863 Context->getDescribedClassTemplate();
12864
12865 Diag(VD->getLocation(),
12866 IsClassTemplateMember
12867 ? diag::warn_attribute_dllimport_static_field_definition
12868 : diag::err_attribute_dllimport_static_field_definition);
12869 Diag(IA->getLocation(), diag::note_attribute);
12870 if (!IsClassTemplateMember)
12871 VD->setInvalidDecl();
12872 }
12873 }
12874
12875 // dllimport/dllexport variables cannot be thread local, their TLS index
12876 // isn't exported with the variable.
12877 if (DLLAttr && VD->getTLSKind()) {
12878 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12879 if (F && getDLLAttr(F)) {
12880 assert(VD->isStaticLocal());
12881 // But if this is a static local in a dlimport/dllexport function, the
12882 // function will never be inlined, which means the var would never be
12883 // imported, so having it marked import/export is safe.
12884 } else {
12885 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12886 << DLLAttr;
12887 VD->setInvalidDecl();
12888 }
12889 }
12890
12891 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12892 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12893 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12894 VD->dropAttr<UsedAttr>();
12895 }
12896 }
12897
12898 const DeclContext *DC = VD->getDeclContext();
12899 // If there's a #pragma GCC visibility in scope, and this isn't a class
12900 // member, set the visibility of this variable.
12901 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12902 AddPushedVisibilityAttribute(VD);
12903
12904 // FIXME: Warn on unused var template partial specializations.
12905 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12906 MarkUnusedFileScopedDecl(VD);
12907
12908 // Now we have parsed the initializer and can update the table of magic
12909 // tag values.
12910 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12911 !VD->getType()->isIntegralOrEnumerationType())
12912 return;
12913
12914 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12915 const Expr *MagicValueExpr = VD->getInit();
12916 if (!MagicValueExpr) {
12917 continue;
12918 }
12919 llvm::APSInt MagicValueInt;
12920 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12921 Diag(I->getRange().getBegin(),
12922 diag::err_type_tag_for_datatype_not_ice)
12923 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12924 continue;
12925 }
12926 if (MagicValueInt.getActiveBits() > 64) {
12927 Diag(I->getRange().getBegin(),
12928 diag::err_type_tag_for_datatype_too_large)
12929 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12930 continue;
12931 }
12932 uint64_t MagicValue = MagicValueInt.getZExtValue();
12933 RegisterTypeTagForDatatype(I->getArgumentKind(),
12934 MagicValue,
12935 I->getMatchingCType(),
12936 I->getLayoutCompatible(),
12937 I->getMustBeNull());
12938 }
12939 }
12940
hasDeducedAuto(DeclaratorDecl * DD)12941 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12942 auto *VD = dyn_cast<VarDecl>(DD);
12943 return VD && !VD->getType()->hasAutoForTrailingReturnType();
12944 }
12945
FinalizeDeclaratorGroup(Scope * S,const DeclSpec & DS,ArrayRef<Decl * > Group)12946 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12947 ArrayRef<Decl *> Group) {
12948 SmallVector<Decl*, 8> Decls;
12949
12950 if (DS.isTypeSpecOwned())
12951 Decls.push_back(DS.getRepAsDecl());
12952
12953 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12954 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12955 bool DiagnosedMultipleDecomps = false;
12956 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12957 bool DiagnosedNonDeducedAuto = false;
12958
12959 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12960 if (Decl *D = Group[i]) {
12961 // For declarators, there are some additional syntactic-ish checks we need
12962 // to perform.
12963 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12964 if (!FirstDeclaratorInGroup)
12965 FirstDeclaratorInGroup = DD;
12966 if (!FirstDecompDeclaratorInGroup)
12967 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12968 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12969 !hasDeducedAuto(DD))
12970 FirstNonDeducedAutoInGroup = DD;
12971
12972 if (FirstDeclaratorInGroup != DD) {
12973 // A decomposition declaration cannot be combined with any other
12974 // declaration in the same group.
12975 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12976 Diag(FirstDecompDeclaratorInGroup->getLocation(),
12977 diag::err_decomp_decl_not_alone)
12978 << FirstDeclaratorInGroup->getSourceRange()
12979 << DD->getSourceRange();
12980 DiagnosedMultipleDecomps = true;
12981 }
12982
12983 // A declarator that uses 'auto' in any way other than to declare a
12984 // variable with a deduced type cannot be combined with any other
12985 // declarator in the same group.
12986 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12987 Diag(FirstNonDeducedAutoInGroup->getLocation(),
12988 diag::err_auto_non_deduced_not_alone)
12989 << FirstNonDeducedAutoInGroup->getType()
12990 ->hasAutoForTrailingReturnType()
12991 << FirstDeclaratorInGroup->getSourceRange()
12992 << DD->getSourceRange();
12993 DiagnosedNonDeducedAuto = true;
12994 }
12995 }
12996 }
12997
12998 Decls.push_back(D);
12999 }
13000 }
13001
13002 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13003 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13004 handleTagNumbering(Tag, S);
13005 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13006 getLangOpts().CPlusPlus)
13007 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13008 }
13009 }
13010
13011 return BuildDeclaratorGroup(Decls);
13012 }
13013
13014 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13015 /// group, performing any necessary semantic checking.
13016 Sema::DeclGroupPtrTy
BuildDeclaratorGroup(MutableArrayRef<Decl * > Group)13017 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13018 // C++14 [dcl.spec.auto]p7: (DR1347)
13019 // If the type that replaces the placeholder type is not the same in each
13020 // deduction, the program is ill-formed.
13021 if (Group.size() > 1) {
13022 QualType Deduced;
13023 VarDecl *DeducedDecl = nullptr;
13024 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13025 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13026 if (!D || D->isInvalidDecl())
13027 break;
13028 DeducedType *DT = D->getType()->getContainedDeducedType();
13029 if (!DT || DT->getDeducedType().isNull())
13030 continue;
13031 if (Deduced.isNull()) {
13032 Deduced = DT->getDeducedType();
13033 DeducedDecl = D;
13034 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13035 auto *AT = dyn_cast<AutoType>(DT);
13036 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13037 diag::err_auto_different_deductions)
13038 << (AT ? (unsigned)AT->getKeyword() : 3)
13039 << Deduced << DeducedDecl->getDeclName()
13040 << DT->getDeducedType() << D->getDeclName()
13041 << DeducedDecl->getInit()->getSourceRange()
13042 << D->getInit()->getSourceRange();
13043 D->setInvalidDecl();
13044 break;
13045 }
13046 }
13047 }
13048
13049 ActOnDocumentableDecls(Group);
13050
13051 return DeclGroupPtrTy::make(
13052 DeclGroupRef::Create(Context, Group.data(), Group.size()));
13053 }
13054
ActOnDocumentableDecl(Decl * D)13055 void Sema::ActOnDocumentableDecl(Decl *D) {
13056 ActOnDocumentableDecls(D);
13057 }
13058
ActOnDocumentableDecls(ArrayRef<Decl * > Group)13059 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13060 // Don't parse the comment if Doxygen diagnostics are ignored.
13061 if (Group.empty() || !Group[0])
13062 return;
13063
13064 if (Diags.isIgnored(diag::warn_doc_param_not_found,
13065 Group[0]->getLocation()) &&
13066 Diags.isIgnored(diag::warn_unknown_comment_command_name,
13067 Group[0]->getLocation()))
13068 return;
13069
13070 if (Group.size() >= 2) {
13071 // This is a decl group. Normally it will contain only declarations
13072 // produced from declarator list. But in case we have any definitions or
13073 // additional declaration references:
13074 // 'typedef struct S {} S;'
13075 // 'typedef struct S *S;'
13076 // 'struct S *pS;'
13077 // FinalizeDeclaratorGroup adds these as separate declarations.
13078 Decl *MaybeTagDecl = Group[0];
13079 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13080 Group = Group.slice(1);
13081 }
13082 }
13083
13084 // FIMXE: We assume every Decl in the group is in the same file.
13085 // This is false when preprocessor constructs the group from decls in
13086 // different files (e. g. macros or #include).
13087 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13088 }
13089
13090 /// Common checks for a parameter-declaration that should apply to both function
13091 /// parameters and non-type template parameters.
CheckFunctionOrTemplateParamDeclarator(Scope * S,Declarator & D)13092 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13093 // Check that there are no default arguments inside the type of this
13094 // parameter.
13095 if (getLangOpts().CPlusPlus)
13096 CheckExtraCXXDefaultArguments(D);
13097
13098 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13099 if (D.getCXXScopeSpec().isSet()) {
13100 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13101 << D.getCXXScopeSpec().getRange();
13102 }
13103
13104 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13105 // simple identifier except [...irrelevant cases...].
13106 switch (D.getName().getKind()) {
13107 case UnqualifiedIdKind::IK_Identifier:
13108 break;
13109
13110 case UnqualifiedIdKind::IK_OperatorFunctionId:
13111 case UnqualifiedIdKind::IK_ConversionFunctionId:
13112 case UnqualifiedIdKind::IK_LiteralOperatorId:
13113 case UnqualifiedIdKind::IK_ConstructorName:
13114 case UnqualifiedIdKind::IK_DestructorName:
13115 case UnqualifiedIdKind::IK_ImplicitSelfParam:
13116 case UnqualifiedIdKind::IK_DeductionGuideName:
13117 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13118 << GetNameForDeclarator(D).getName();
13119 break;
13120
13121 case UnqualifiedIdKind::IK_TemplateId:
13122 case UnqualifiedIdKind::IK_ConstructorTemplateId:
13123 // GetNameForDeclarator would not produce a useful name in this case.
13124 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13125 break;
13126 }
13127 }
13128
13129 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13130 /// to introduce parameters into function prototype scope.
ActOnParamDeclarator(Scope * S,Declarator & D)13131 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13132 const DeclSpec &DS = D.getDeclSpec();
13133
13134 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13135
13136 // C++03 [dcl.stc]p2 also permits 'auto'.
13137 StorageClass SC = SC_None;
13138 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13139 SC = SC_Register;
13140 // In C++11, the 'register' storage class specifier is deprecated.
13141 // In C++17, it is not allowed, but we tolerate it as an extension.
13142 if (getLangOpts().CPlusPlus11) {
13143 Diag(DS.getStorageClassSpecLoc(),
13144 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13145 : diag::warn_deprecated_register)
13146 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13147 }
13148 } else if (getLangOpts().CPlusPlus &&
13149 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13150 SC = SC_Auto;
13151 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13152 Diag(DS.getStorageClassSpecLoc(),
13153 diag::err_invalid_storage_class_in_func_decl);
13154 D.getMutableDeclSpec().ClearStorageClassSpecs();
13155 }
13156
13157 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13158 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13159 << DeclSpec::getSpecifierName(TSCS);
13160 if (DS.isInlineSpecified())
13161 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13162 << getLangOpts().CPlusPlus17;
13163 if (DS.hasConstexprSpecifier())
13164 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13165 << 0 << D.getDeclSpec().getConstexprSpecifier();
13166
13167 DiagnoseFunctionSpecifiers(DS);
13168
13169 CheckFunctionOrTemplateParamDeclarator(S, D);
13170
13171 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13172 QualType parmDeclType = TInfo->getType();
13173
13174 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13175 IdentifierInfo *II = D.getIdentifier();
13176 if (II) {
13177 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13178 ForVisibleRedeclaration);
13179 LookupName(R, S);
13180 if (R.isSingleResult()) {
13181 NamedDecl *PrevDecl = R.getFoundDecl();
13182 if (PrevDecl->isTemplateParameter()) {
13183 // Maybe we will complain about the shadowed template parameter.
13184 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13185 // Just pretend that we didn't see the previous declaration.
13186 PrevDecl = nullptr;
13187 } else if (S->isDeclScope(PrevDecl)) {
13188 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13189 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13190
13191 // Recover by removing the name
13192 II = nullptr;
13193 D.SetIdentifier(nullptr, D.getIdentifierLoc());
13194 D.setInvalidType(true);
13195 }
13196 }
13197 }
13198
13199 // Temporarily put parameter variables in the translation unit, not
13200 // the enclosing context. This prevents them from accidentally
13201 // looking like class members in C++.
13202 ParmVarDecl *New =
13203 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13204 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13205
13206 if (D.isInvalidType())
13207 New->setInvalidDecl();
13208
13209 assert(S->isFunctionPrototypeScope());
13210 assert(S->getFunctionPrototypeDepth() >= 1);
13211 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13212 S->getNextFunctionPrototypeIndex());
13213
13214 // Add the parameter declaration into this scope.
13215 S->AddDecl(New);
13216 if (II)
13217 IdResolver.AddDecl(New);
13218
13219 ProcessDeclAttributes(S, New, D);
13220
13221 if (D.getDeclSpec().isModulePrivateSpecified())
13222 Diag(New->getLocation(), diag::err_module_private_local)
13223 << 1 << New->getDeclName()
13224 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13225 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13226
13227 if (New->hasAttr<BlocksAttr>()) {
13228 Diag(New->getLocation(), diag::err_block_on_nonlocal);
13229 }
13230
13231 if (getLangOpts().OpenCL)
13232 deduceOpenCLAddressSpace(New);
13233
13234 return New;
13235 }
13236
13237 /// Synthesizes a variable for a parameter arising from a
13238 /// typedef.
BuildParmVarDeclForTypedef(DeclContext * DC,SourceLocation Loc,QualType T)13239 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13240 SourceLocation Loc,
13241 QualType T) {
13242 /* FIXME: setting StartLoc == Loc.
13243 Would it be worth to modify callers so as to provide proper source
13244 location for the unnamed parameters, embedding the parameter's type? */
13245 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13246 T, Context.getTrivialTypeSourceInfo(T, Loc),
13247 SC_None, nullptr);
13248 Param->setImplicit();
13249 return Param;
13250 }
13251
DiagnoseUnusedParameters(ArrayRef<ParmVarDecl * > Parameters)13252 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13253 // Don't diagnose unused-parameter errors in template instantiations; we
13254 // will already have done so in the template itself.
13255 if (inTemplateInstantiation())
13256 return;
13257
13258 for (const ParmVarDecl *Parameter : Parameters) {
13259 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13260 !Parameter->hasAttr<UnusedAttr>()) {
13261 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13262 << Parameter->getDeclName();
13263 }
13264 }
13265 }
13266
DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl * > Parameters,QualType ReturnTy,NamedDecl * D)13267 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13268 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13269 if (LangOpts.NumLargeByValueCopy == 0) // No check.
13270 return;
13271
13272 // Warn if the return value is pass-by-value and larger than the specified
13273 // threshold.
13274 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13275 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13276 if (Size > LangOpts.NumLargeByValueCopy)
13277 Diag(D->getLocation(), diag::warn_return_value_size)
13278 << D->getDeclName() << Size;
13279 }
13280
13281 // Warn if any parameter is pass-by-value and larger than the specified
13282 // threshold.
13283 for (const ParmVarDecl *Parameter : Parameters) {
13284 QualType T = Parameter->getType();
13285 if (T->isDependentType() || !T.isPODType(Context))
13286 continue;
13287 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13288 if (Size > LangOpts.NumLargeByValueCopy)
13289 Diag(Parameter->getLocation(), diag::warn_parameter_size)
13290 << Parameter->getDeclName() << Size;
13291 }
13292 }
13293
CheckParameter(DeclContext * DC,SourceLocation StartLoc,SourceLocation NameLoc,IdentifierInfo * Name,QualType T,TypeSourceInfo * TSInfo,StorageClass SC)13294 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13295 SourceLocation NameLoc, IdentifierInfo *Name,
13296 QualType T, TypeSourceInfo *TSInfo,
13297 StorageClass SC) {
13298 // In ARC, infer a lifetime qualifier for appropriate parameter types.
13299 if (getLangOpts().ObjCAutoRefCount &&
13300 T.getObjCLifetime() == Qualifiers::OCL_None &&
13301 T->isObjCLifetimeType()) {
13302
13303 Qualifiers::ObjCLifetime lifetime;
13304
13305 // Special cases for arrays:
13306 // - if it's const, use __unsafe_unretained
13307 // - otherwise, it's an error
13308 if (T->isArrayType()) {
13309 if (!T.isConstQualified()) {
13310 if (DelayedDiagnostics.shouldDelayDiagnostics())
13311 DelayedDiagnostics.add(
13312 sema::DelayedDiagnostic::makeForbiddenType(
13313 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13314 else
13315 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13316 << TSInfo->getTypeLoc().getSourceRange();
13317 }
13318 lifetime = Qualifiers::OCL_ExplicitNone;
13319 } else {
13320 lifetime = T->getObjCARCImplicitLifetime();
13321 }
13322 T = Context.getLifetimeQualifiedType(T, lifetime);
13323 }
13324
13325 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13326 Context.getAdjustedParameterType(T),
13327 TSInfo, SC, nullptr);
13328
13329 // Make a note if we created a new pack in the scope of a lambda, so that
13330 // we know that references to that pack must also be expanded within the
13331 // lambda scope.
13332 if (New->isParameterPack())
13333 if (auto *LSI = getEnclosingLambda())
13334 LSI->LocalPacks.push_back(New);
13335
13336 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13337 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13338 checkNonTrivialCUnion(New->getType(), New->getLocation(),
13339 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13340
13341 // Parameters can not be abstract class types.
13342 // For record types, this is done by the AbstractClassUsageDiagnoser once
13343 // the class has been completely parsed.
13344 if (!CurContext->isRecord() &&
13345 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13346 AbstractParamType))
13347 New->setInvalidDecl();
13348
13349 // Parameter declarators cannot be interface types. All ObjC objects are
13350 // passed by reference.
13351 if (T->isObjCObjectType()) {
13352 SourceLocation TypeEndLoc =
13353 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13354 Diag(NameLoc,
13355 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13356 << FixItHint::CreateInsertion(TypeEndLoc, "*");
13357 T = Context.getObjCObjectPointerType(T);
13358 New->setType(T);
13359 }
13360
13361 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13362 // duration shall not be qualified by an address-space qualifier."
13363 // Since all parameters have automatic store duration, they can not have
13364 // an address space.
13365 if (T.getAddressSpace() != LangAS::Default &&
13366 // OpenCL allows function arguments declared to be an array of a type
13367 // to be qualified with an address space.
13368 !(getLangOpts().OpenCL &&
13369 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13370 Diag(NameLoc, diag::err_arg_with_address_space);
13371 New->setInvalidDecl();
13372 }
13373
13374 return New;
13375 }
13376
ActOnFinishKNRParamDeclarations(Scope * S,Declarator & D,SourceLocation LocAfterDecls)13377 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13378 SourceLocation LocAfterDecls) {
13379 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13380
13381 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13382 // for a K&R function.
13383 if (!FTI.hasPrototype) {
13384 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13385 --i;
13386 if (FTI.Params[i].Param == nullptr) {
13387 SmallString<256> Code;
13388 llvm::raw_svector_ostream(Code)
13389 << " int " << FTI.Params[i].Ident->getName() << ";\n";
13390 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13391 << FTI.Params[i].Ident
13392 << FixItHint::CreateInsertion(LocAfterDecls, Code);
13393
13394 // Implicitly declare the argument as type 'int' for lack of a better
13395 // type.
13396 AttributeFactory attrs;
13397 DeclSpec DS(attrs);
13398 const char* PrevSpec; // unused
13399 unsigned DiagID; // unused
13400 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13401 DiagID, Context.getPrintingPolicy());
13402 // Use the identifier location for the type source range.
13403 DS.SetRangeStart(FTI.Params[i].IdentLoc);
13404 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13405 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13406 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13407 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13408 }
13409 }
13410 }
13411 }
13412
13413 Decl *
ActOnStartOfFunctionDef(Scope * FnBodyScope,Declarator & D,MultiTemplateParamsArg TemplateParameterLists,SkipBodyInfo * SkipBody)13414 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13415 MultiTemplateParamsArg TemplateParameterLists,
13416 SkipBodyInfo *SkipBody) {
13417 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13418 assert(D.isFunctionDeclarator() && "Not a function declarator!");
13419 Scope *ParentScope = FnBodyScope->getParent();
13420
13421 D.setFunctionDefinitionKind(FDK_Definition);
13422 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13423 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13424 }
13425
ActOnFinishInlineFunctionDef(FunctionDecl * D)13426 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13427 Consumer.HandleInlineFunctionDefinition(D);
13428 }
13429
13430 static bool
ShouldWarnAboutMissingPrototype(const FunctionDecl * FD,const FunctionDecl * & PossiblePrototype)13431 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13432 const FunctionDecl *&PossiblePrototype) {
13433 // Don't warn about invalid declarations.
13434 if (FD->isInvalidDecl())
13435 return false;
13436
13437 // Or declarations that aren't global.
13438 if (!FD->isGlobal())
13439 return false;
13440
13441 // Don't warn about C++ member functions.
13442 if (isa<CXXMethodDecl>(FD))
13443 return false;
13444
13445 // Don't warn about 'main'.
13446 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13447 if (IdentifierInfo *II = FD->getIdentifier())
13448 if (II->isStr("main"))
13449 return false;
13450
13451 // Don't warn about inline functions.
13452 if (FD->isInlined())
13453 return false;
13454
13455 // Don't warn about function templates.
13456 if (FD->getDescribedFunctionTemplate())
13457 return false;
13458
13459 // Don't warn about function template specializations.
13460 if (FD->isFunctionTemplateSpecialization())
13461 return false;
13462
13463 // Don't warn for OpenCL kernels.
13464 if (FD->hasAttr<OpenCLKernelAttr>())
13465 return false;
13466
13467 // Don't warn on explicitly deleted functions.
13468 if (FD->isDeleted())
13469 return false;
13470
13471 for (const FunctionDecl *Prev = FD->getPreviousDecl();
13472 Prev; Prev = Prev->getPreviousDecl()) {
13473 // Ignore any declarations that occur in function or method
13474 // scope, because they aren't visible from the header.
13475 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13476 continue;
13477
13478 PossiblePrototype = Prev;
13479 return Prev->getType()->isFunctionNoProtoType();
13480 }
13481
13482 return true;
13483 }
13484
13485 void
CheckForFunctionRedefinition(FunctionDecl * FD,const FunctionDecl * EffectiveDefinition,SkipBodyInfo * SkipBody)13486 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13487 const FunctionDecl *EffectiveDefinition,
13488 SkipBodyInfo *SkipBody) {
13489 const FunctionDecl *Definition = EffectiveDefinition;
13490 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13491 // If this is a friend function defined in a class template, it does not
13492 // have a body until it is used, nevertheless it is a definition, see
13493 // [temp.inst]p2:
13494 //
13495 // ... for the purpose of determining whether an instantiated redeclaration
13496 // is valid according to [basic.def.odr] and [class.mem], a declaration that
13497 // corresponds to a definition in the template is considered to be a
13498 // definition.
13499 //
13500 // The following code must produce redefinition error:
13501 //
13502 // template<typename T> struct C20 { friend void func_20() {} };
13503 // C20<int> c20i;
13504 // void func_20() {}
13505 //
13506 for (auto I : FD->redecls()) {
13507 if (I != FD && !I->isInvalidDecl() &&
13508 I->getFriendObjectKind() != Decl::FOK_None) {
13509 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13510 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13511 // A merged copy of the same function, instantiated as a member of
13512 // the same class, is OK.
13513 if (declaresSameEntity(OrigFD, Original) &&
13514 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13515 cast<Decl>(FD->getLexicalDeclContext())))
13516 continue;
13517 }
13518
13519 if (Original->isThisDeclarationADefinition()) {
13520 Definition = I;
13521 break;
13522 }
13523 }
13524 }
13525 }
13526 }
13527
13528 if (!Definition)
13529 // Similar to friend functions a friend function template may be a
13530 // definition and do not have a body if it is instantiated in a class
13531 // template.
13532 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13533 for (auto I : FTD->redecls()) {
13534 auto D = cast<FunctionTemplateDecl>(I);
13535 if (D != FTD) {
13536 assert(!D->isThisDeclarationADefinition() &&
13537 "More than one definition in redeclaration chain");
13538 if (D->getFriendObjectKind() != Decl::FOK_None)
13539 if (FunctionTemplateDecl *FT =
13540 D->getInstantiatedFromMemberTemplate()) {
13541 if (FT->isThisDeclarationADefinition()) {
13542 Definition = D->getTemplatedDecl();
13543 break;
13544 }
13545 }
13546 }
13547 }
13548 }
13549
13550 if (!Definition)
13551 return;
13552
13553 if (canRedefineFunction(Definition, getLangOpts()))
13554 return;
13555
13556 // Don't emit an error when this is redefinition of a typo-corrected
13557 // definition.
13558 if (TypoCorrectedFunctionDefinitions.count(Definition))
13559 return;
13560
13561 // If we don't have a visible definition of the function, and it's inline or
13562 // a template, skip the new definition.
13563 if (SkipBody && !hasVisibleDefinition(Definition) &&
13564 (Definition->getFormalLinkage() == InternalLinkage ||
13565 Definition->isInlined() ||
13566 Definition->getDescribedFunctionTemplate() ||
13567 Definition->getNumTemplateParameterLists())) {
13568 SkipBody->ShouldSkip = true;
13569 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13570 if (auto *TD = Definition->getDescribedFunctionTemplate())
13571 makeMergedDefinitionVisible(TD);
13572 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13573 return;
13574 }
13575
13576 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13577 Definition->getStorageClass() == SC_Extern)
13578 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13579 << FD->getDeclName() << getLangOpts().CPlusPlus;
13580 else
13581 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
13582
13583 Diag(Definition->getLocation(), diag::note_previous_definition);
13584 FD->setInvalidDecl();
13585 }
13586
RebuildLambdaScopeInfo(CXXMethodDecl * CallOperator,Sema & S)13587 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13588 Sema &S) {
13589 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13590
13591 LambdaScopeInfo *LSI = S.PushLambdaScope();
13592 LSI->CallOperator = CallOperator;
13593 LSI->Lambda = LambdaClass;
13594 LSI->ReturnType = CallOperator->getReturnType();
13595 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13596
13597 if (LCD == LCD_None)
13598 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13599 else if (LCD == LCD_ByCopy)
13600 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13601 else if (LCD == LCD_ByRef)
13602 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13603 DeclarationNameInfo DNI = CallOperator->getNameInfo();
13604
13605 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13606 LSI->Mutable = !CallOperator->isConst();
13607
13608 // Add the captures to the LSI so they can be noted as already
13609 // captured within tryCaptureVar.
13610 auto I = LambdaClass->field_begin();
13611 for (const auto &C : LambdaClass->captures()) {
13612 if (C.capturesVariable()) {
13613 VarDecl *VD = C.getCapturedVar();
13614 if (VD->isInitCapture())
13615 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13616 QualType CaptureType = VD->getType();
13617 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13618 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13619 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13620 /*EllipsisLoc*/C.isPackExpansion()
13621 ? C.getEllipsisLoc() : SourceLocation(),
13622 CaptureType, /*Invalid*/false);
13623
13624 } else if (C.capturesThis()) {
13625 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13626 C.getCaptureKind() == LCK_StarThis);
13627 } else {
13628 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13629 I->getType());
13630 }
13631 ++I;
13632 }
13633 }
13634
ActOnStartOfFunctionDef(Scope * FnBodyScope,Decl * D,SkipBodyInfo * SkipBody)13635 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13636 SkipBodyInfo *SkipBody) {
13637 if (!D) {
13638 // Parsing the function declaration failed in some way. Push on a fake scope
13639 // anyway so we can try to parse the function body.
13640 PushFunctionScope();
13641 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13642 return D;
13643 }
13644
13645 FunctionDecl *FD = nullptr;
13646
13647 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13648 FD = FunTmpl->getTemplatedDecl();
13649 else
13650 FD = cast<FunctionDecl>(D);
13651
13652 // Do not push if it is a lambda because one is already pushed when building
13653 // the lambda in ActOnStartOfLambdaDefinition().
13654 if (!isLambdaCallOperator(FD))
13655 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13656
13657 // Check for defining attributes before the check for redefinition.
13658 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13659 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13660 FD->dropAttr<AliasAttr>();
13661 FD->setInvalidDecl();
13662 }
13663 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13664 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13665 FD->dropAttr<IFuncAttr>();
13666 FD->setInvalidDecl();
13667 }
13668
13669 // See if this is a redefinition. If 'will have body' is already set, then
13670 // these checks were already performed when it was set.
13671 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13672 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13673
13674 // If we're skipping the body, we're done. Don't enter the scope.
13675 if (SkipBody && SkipBody->ShouldSkip)
13676 return D;
13677 }
13678
13679 // Mark this function as "will have a body eventually". This lets users to
13680 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13681 // this function.
13682 FD->setWillHaveBody();
13683
13684 // If we are instantiating a generic lambda call operator, push
13685 // a LambdaScopeInfo onto the function stack. But use the information
13686 // that's already been calculated (ActOnLambdaExpr) to prime the current
13687 // LambdaScopeInfo.
13688 // When the template operator is being specialized, the LambdaScopeInfo,
13689 // has to be properly restored so that tryCaptureVariable doesn't try
13690 // and capture any new variables. In addition when calculating potential
13691 // captures during transformation of nested lambdas, it is necessary to
13692 // have the LSI properly restored.
13693 if (isGenericLambdaCallOperatorSpecialization(FD)) {
13694 assert(inTemplateInstantiation() &&
13695 "There should be an active template instantiation on the stack "
13696 "when instantiating a generic lambda!");
13697 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13698 } else {
13699 // Enter a new function scope
13700 PushFunctionScope();
13701 }
13702
13703 // Builtin functions cannot be defined.
13704 if (unsigned BuiltinID = FD->getBuiltinID()) {
13705 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
13706 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
13707 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
13708 FD->setInvalidDecl();
13709 }
13710 }
13711
13712 // The return type of a function definition must be complete
13713 // (C99 6.9.1p3, C++ [dcl.fct]p6).
13714 QualType ResultType = FD->getReturnType();
13715 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
13716 !FD->isInvalidDecl() &&
13717 RequireCompleteType(FD->getLocation(), ResultType,
13718 diag::err_func_def_incomplete_result))
13719 FD->setInvalidDecl();
13720
13721 if (FnBodyScope)
13722 PushDeclContext(FnBodyScope, FD);
13723
13724 // Check the validity of our function parameters
13725 CheckParmsForFunctionDef(FD->parameters(),
13726 /*CheckParameterNames=*/true);
13727
13728 // Add non-parameter declarations already in the function to the current
13729 // scope.
13730 if (FnBodyScope) {
13731 for (Decl *NPD : FD->decls()) {
13732 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13733 if (!NonParmDecl)
13734 continue;
13735 assert(!isa<ParmVarDecl>(NonParmDecl) &&
13736 "parameters should not be in newly created FD yet");
13737
13738 // If the decl has a name, make it accessible in the current scope.
13739 if (NonParmDecl->getDeclName())
13740 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13741
13742 // Similarly, dive into enums and fish their constants out, making them
13743 // accessible in this scope.
13744 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13745 for (auto *EI : ED->enumerators())
13746 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13747 }
13748 }
13749 }
13750
13751 // Introduce our parameters into the function scope
13752 for (auto Param : FD->parameters()) {
13753 Param->setOwningFunction(FD);
13754
13755 // If this has an identifier, add it to the scope stack.
13756 if (Param->getIdentifier() && FnBodyScope) {
13757 CheckShadow(FnBodyScope, Param);
13758
13759 PushOnScopeChains(Param, FnBodyScope);
13760 }
13761 }
13762
13763 // Ensure that the function's exception specification is instantiated.
13764 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13765 ResolveExceptionSpec(D->getLocation(), FPT);
13766
13767 // dllimport cannot be applied to non-inline function definitions.
13768 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13769 !FD->isTemplateInstantiation()) {
13770 assert(!FD->hasAttr<DLLExportAttr>());
13771 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13772 FD->setInvalidDecl();
13773 return D;
13774 }
13775 // We want to attach documentation to original Decl (which might be
13776 // a function template).
13777 ActOnDocumentableDecl(D);
13778 if (getCurLexicalContext()->isObjCContainer() &&
13779 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13780 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13781 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13782
13783 return D;
13784 }
13785
13786 /// Given the set of return statements within a function body,
13787 /// compute the variables that are subject to the named return value
13788 /// optimization.
13789 ///
13790 /// Each of the variables that is subject to the named return value
13791 /// optimization will be marked as NRVO variables in the AST, and any
13792 /// return statement that has a marked NRVO variable as its NRVO candidate can
13793 /// use the named return value optimization.
13794 ///
13795 /// This function applies a very simplistic algorithm for NRVO: if every return
13796 /// statement in the scope of a variable has the same NRVO candidate, that
13797 /// candidate is an NRVO variable.
computeNRVO(Stmt * Body,FunctionScopeInfo * Scope)13798 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13799 ReturnStmt **Returns = Scope->Returns.data();
13800
13801 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13802 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13803 if (!NRVOCandidate->isNRVOVariable())
13804 Returns[I]->setNRVOCandidate(nullptr);
13805 }
13806 }
13807 }
13808
canDelayFunctionBody(const Declarator & D)13809 bool Sema::canDelayFunctionBody(const Declarator &D) {
13810 // We can't delay parsing the body of a constexpr function template (yet).
13811 if (D.getDeclSpec().hasConstexprSpecifier())
13812 return false;
13813
13814 // We can't delay parsing the body of a function template with a deduced
13815 // return type (yet).
13816 if (D.getDeclSpec().hasAutoTypeSpec()) {
13817 // If the placeholder introduces a non-deduced trailing return type,
13818 // we can still delay parsing it.
13819 if (D.getNumTypeObjects()) {
13820 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13821 if (Outer.Kind == DeclaratorChunk::Function &&
13822 Outer.Fun.hasTrailingReturnType()) {
13823 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13824 return Ty.isNull() || !Ty->isUndeducedType();
13825 }
13826 }
13827 return false;
13828 }
13829
13830 return true;
13831 }
13832
canSkipFunctionBody(Decl * D)13833 bool Sema::canSkipFunctionBody(Decl *D) {
13834 // We cannot skip the body of a function (or function template) which is
13835 // constexpr, since we may need to evaluate its body in order to parse the
13836 // rest of the file.
13837 // We cannot skip the body of a function with an undeduced return type,
13838 // because any callers of that function need to know the type.
13839 if (const FunctionDecl *FD = D->getAsFunction()) {
13840 if (FD->isConstexpr())
13841 return false;
13842 // We can't simply call Type::isUndeducedType here, because inside template
13843 // auto can be deduced to a dependent type, which is not considered
13844 // "undeduced".
13845 if (FD->getReturnType()->getContainedDeducedType())
13846 return false;
13847 }
13848 return Consumer.shouldSkipFunctionBody(D);
13849 }
13850
ActOnSkippedFunctionBody(Decl * Decl)13851 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13852 if (!Decl)
13853 return nullptr;
13854 if (FunctionDecl *FD = Decl->getAsFunction())
13855 FD->setHasSkippedBody();
13856 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13857 MD->setHasSkippedBody();
13858 return Decl;
13859 }
13860
ActOnFinishFunctionBody(Decl * D,Stmt * BodyArg)13861 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13862 return ActOnFinishFunctionBody(D, BodyArg, false);
13863 }
13864
13865 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
13866 /// body.
13867 class ExitFunctionBodyRAII {
13868 public:
ExitFunctionBodyRAII(Sema & S,bool IsLambda)13869 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
~ExitFunctionBodyRAII()13870 ~ExitFunctionBodyRAII() {
13871 if (!IsLambda)
13872 S.PopExpressionEvaluationContext();
13873 }
13874
13875 private:
13876 Sema &S;
13877 bool IsLambda = false;
13878 };
13879
diagnoseImplicitlyRetainedSelf(Sema & S)13880 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
13881 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
13882
13883 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
13884 if (EscapeInfo.count(BD))
13885 return EscapeInfo[BD];
13886
13887 bool R = false;
13888 const BlockDecl *CurBD = BD;
13889
13890 do {
13891 R = !CurBD->doesNotEscape();
13892 if (R)
13893 break;
13894 CurBD = CurBD->getParent()->getInnermostBlockDecl();
13895 } while (CurBD);
13896
13897 return EscapeInfo[BD] = R;
13898 };
13899
13900 // If the location where 'self' is implicitly retained is inside a escaping
13901 // block, emit a diagnostic.
13902 for (const std::pair<SourceLocation, const BlockDecl *> &P :
13903 S.ImplicitlyRetainedSelfLocs)
13904 if (IsOrNestedInEscapingBlock(P.second))
13905 S.Diag(P.first, diag::warn_implicitly_retains_self)
13906 << FixItHint::CreateInsertion(P.first, "self->");
13907 }
13908
ActOnFinishFunctionBody(Decl * dcl,Stmt * Body,bool IsInstantiation)13909 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13910 bool IsInstantiation) {
13911 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13912
13913 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13914 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13915
13916 if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
13917 CheckCompletedCoroutineBody(FD, Body);
13918
13919 // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13920 // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13921 // meant to pop the context added in ActOnStartOfFunctionDef().
13922 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13923
13924 if (FD) {
13925 FD->setBody(Body);
13926 FD->setWillHaveBody(false);
13927
13928 if (getLangOpts().CPlusPlus14) {
13929 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13930 FD->getReturnType()->isUndeducedType()) {
13931 // If the function has a deduced result type but contains no 'return'
13932 // statements, the result type as written must be exactly 'auto', and
13933 // the deduced result type is 'void'.
13934 if (!FD->getReturnType()->getAs<AutoType>()) {
13935 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13936 << FD->getReturnType();
13937 FD->setInvalidDecl();
13938 } else {
13939 // Substitute 'void' for the 'auto' in the type.
13940 TypeLoc ResultType = getReturnTypeLoc(FD);
13941 Context.adjustDeducedFunctionResultType(
13942 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13943 }
13944 }
13945 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13946 // In C++11, we don't use 'auto' deduction rules for lambda call
13947 // operators because we don't support return type deduction.
13948 auto *LSI = getCurLambda();
13949 if (LSI->HasImplicitReturnType) {
13950 deduceClosureReturnType(*LSI);
13951
13952 // C++11 [expr.prim.lambda]p4:
13953 // [...] if there are no return statements in the compound-statement
13954 // [the deduced type is] the type void
13955 QualType RetType =
13956 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13957
13958 // Update the return type to the deduced type.
13959 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
13960 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13961 Proto->getExtProtoInfo()));
13962 }
13963 }
13964
13965 // If the function implicitly returns zero (like 'main') or is naked,
13966 // don't complain about missing return statements.
13967 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13968 WP.disableCheckFallThrough();
13969
13970 // MSVC permits the use of pure specifier (=0) on function definition,
13971 // defined at class scope, warn about this non-standard construct.
13972 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
13973 Diag(FD->getLocation(), diag::ext_pure_function_definition);
13974
13975 if (!FD->isInvalidDecl()) {
13976 // Don't diagnose unused parameters of defaulted or deleted functions.
13977 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13978 DiagnoseUnusedParameters(FD->parameters());
13979 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13980 FD->getReturnType(), FD);
13981
13982 // If this is a structor, we need a vtable.
13983 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13984 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13985 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13986 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13987
13988 // Try to apply the named return value optimization. We have to check
13989 // if we can do this here because lambdas keep return statements around
13990 // to deduce an implicit return type.
13991 if (FD->getReturnType()->isRecordType() &&
13992 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13993 computeNRVO(Body, getCurFunction());
13994 }
13995
13996 // GNU warning -Wmissing-prototypes:
13997 // Warn if a global function is defined without a previous
13998 // prototype declaration. This warning is issued even if the
13999 // definition itself provides a prototype. The aim is to detect
14000 // global functions that fail to be declared in header files.
14001 const FunctionDecl *PossiblePrototype = nullptr;
14002 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14003 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14004
14005 if (PossiblePrototype) {
14006 // We found a declaration that is not a prototype,
14007 // but that could be a zero-parameter prototype
14008 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14009 TypeLoc TL = TI->getTypeLoc();
14010 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14011 Diag(PossiblePrototype->getLocation(),
14012 diag::note_declaration_not_a_prototype)
14013 << (FD->getNumParams() != 0)
14014 << (FD->getNumParams() == 0
14015 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14016 : FixItHint{});
14017 }
14018 } else {
14019 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14020 << /* function */ 1
14021 << (FD->getStorageClass() == SC_None
14022 ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
14023 "static ")
14024 : FixItHint{});
14025 }
14026
14027 // GNU warning -Wstrict-prototypes
14028 // Warn if K&R function is defined without a previous declaration.
14029 // This warning is issued only if the definition itself does not provide
14030 // a prototype. Only K&R definitions do not provide a prototype.
14031 // An empty list in a function declarator that is part of a definition
14032 // of that function specifies that the function has no parameters
14033 // (C99 6.7.5.3p14)
14034 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
14035 !LangOpts.CPlusPlus) {
14036 TypeSourceInfo *TI = FD->getTypeSourceInfo();
14037 TypeLoc TL = TI->getTypeLoc();
14038 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14039 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14040 }
14041 }
14042
14043 // Warn on CPUDispatch with an actual body.
14044 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14045 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14046 if (!CmpndBody->body_empty())
14047 Diag(CmpndBody->body_front()->getBeginLoc(),
14048 diag::warn_dispatch_body_ignored);
14049
14050 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14051 const CXXMethodDecl *KeyFunction;
14052 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14053 MD->isVirtual() &&
14054 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14055 MD == KeyFunction->getCanonicalDecl()) {
14056 // Update the key-function state if necessary for this ABI.
14057 if (FD->isInlined() &&
14058 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14059 Context.setNonKeyFunction(MD);
14060
14061 // If the newly-chosen key function is already defined, then we
14062 // need to mark the vtable as used retroactively.
14063 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14064 const FunctionDecl *Definition;
14065 if (KeyFunction && KeyFunction->isDefined(Definition))
14066 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14067 } else {
14068 // We just defined they key function; mark the vtable as used.
14069 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14070 }
14071 }
14072 }
14073
14074 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14075 "Function parsing confused");
14076 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14077 assert(MD == getCurMethodDecl() && "Method parsing confused");
14078 MD->setBody(Body);
14079 if (!MD->isInvalidDecl()) {
14080 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14081 MD->getReturnType(), MD);
14082
14083 if (Body)
14084 computeNRVO(Body, getCurFunction());
14085 }
14086 if (getCurFunction()->ObjCShouldCallSuper) {
14087 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14088 << MD->getSelector().getAsString();
14089 getCurFunction()->ObjCShouldCallSuper = false;
14090 }
14091 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
14092 const ObjCMethodDecl *InitMethod = nullptr;
14093 bool isDesignated =
14094 MD->isDesignatedInitializerForTheInterface(&InitMethod);
14095 assert(isDesignated && InitMethod);
14096 (void)isDesignated;
14097
14098 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14099 auto IFace = MD->getClassInterface();
14100 if (!IFace)
14101 return false;
14102 auto SuperD = IFace->getSuperClass();
14103 if (!SuperD)
14104 return false;
14105 return SuperD->getIdentifier() ==
14106 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14107 };
14108 // Don't issue this warning for unavailable inits or direct subclasses
14109 // of NSObject.
14110 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14111 Diag(MD->getLocation(),
14112 diag::warn_objc_designated_init_missing_super_call);
14113 Diag(InitMethod->getLocation(),
14114 diag::note_objc_designated_init_marked_here);
14115 }
14116 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
14117 }
14118 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
14119 // Don't issue this warning for unavaialable inits.
14120 if (!MD->isUnavailable())
14121 Diag(MD->getLocation(),
14122 diag::warn_objc_secondary_init_missing_init_call);
14123 getCurFunction()->ObjCWarnForNoInitDelegation = false;
14124 }
14125
14126 diagnoseImplicitlyRetainedSelf(*this);
14127 } else {
14128 // Parsing the function declaration failed in some way. Pop the fake scope
14129 // we pushed on.
14130 PopFunctionScopeInfo(ActivePolicy, dcl);
14131 return nullptr;
14132 }
14133
14134 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14135 DiagnoseUnguardedAvailabilityViolations(dcl);
14136
14137 assert(!getCurFunction()->ObjCShouldCallSuper &&
14138 "This should only be set for ObjC methods, which should have been "
14139 "handled in the block above.");
14140
14141 // Verify and clean out per-function state.
14142 if (Body && (!FD || !FD->isDefaulted())) {
14143 // C++ constructors that have function-try-blocks can't have return
14144 // statements in the handlers of that block. (C++ [except.handle]p14)
14145 // Verify this.
14146 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14147 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14148
14149 // Verify that gotos and switch cases don't jump into scopes illegally.
14150 if (getCurFunction()->NeedsScopeChecking() &&
14151 !PP.isCodeCompletionEnabled())
14152 DiagnoseInvalidJumps(Body);
14153
14154 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14155 if (!Destructor->getParent()->isDependentType())
14156 CheckDestructor(Destructor);
14157
14158 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14159 Destructor->getParent());
14160 }
14161
14162 // If any errors have occurred, clear out any temporaries that may have
14163 // been leftover. This ensures that these temporaries won't be picked up for
14164 // deletion in some later function.
14165 if (getDiagnostics().hasErrorOccurred() ||
14166 getDiagnostics().getSuppressAllDiagnostics()) {
14167 DiscardCleanupsInEvaluationContext();
14168 }
14169 if (!getDiagnostics().hasUncompilableErrorOccurred() &&
14170 !isa<FunctionTemplateDecl>(dcl)) {
14171 // Since the body is valid, issue any analysis-based warnings that are
14172 // enabled.
14173 ActivePolicy = &WP;
14174 }
14175
14176 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14177 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14178 FD->setInvalidDecl();
14179
14180 if (FD && FD->hasAttr<NakedAttr>()) {
14181 for (const Stmt *S : Body->children()) {
14182 // Allow local register variables without initializer as they don't
14183 // require prologue.
14184 bool RegisterVariables = false;
14185 if (auto *DS = dyn_cast<DeclStmt>(S)) {
14186 for (const auto *Decl : DS->decls()) {
14187 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14188 RegisterVariables =
14189 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14190 if (!RegisterVariables)
14191 break;
14192 }
14193 }
14194 }
14195 if (RegisterVariables)
14196 continue;
14197 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14198 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14199 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14200 FD->setInvalidDecl();
14201 break;
14202 }
14203 }
14204 }
14205
14206 assert(ExprCleanupObjects.size() ==
14207 ExprEvalContexts.back().NumCleanupObjects &&
14208 "Leftover temporaries in function");
14209 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14210 assert(MaybeODRUseExprs.empty() &&
14211 "Leftover expressions for odr-use checking");
14212 }
14213
14214 if (!IsInstantiation)
14215 PopDeclContext();
14216
14217 PopFunctionScopeInfo(ActivePolicy, dcl);
14218 // If any errors have occurred, clear out any temporaries that may have
14219 // been leftover. This ensures that these temporaries won't be picked up for
14220 // deletion in some later function.
14221 if (getDiagnostics().hasErrorOccurred()) {
14222 DiscardCleanupsInEvaluationContext();
14223 }
14224
14225 return dcl;
14226 }
14227
14228 /// When we finish delayed parsing of an attribute, we must attach it to the
14229 /// relevant Decl.
ActOnFinishDelayedAttribute(Scope * S,Decl * D,ParsedAttributes & Attrs)14230 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14231 ParsedAttributes &Attrs) {
14232 // Always attach attributes to the underlying decl.
14233 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14234 D = TD->getTemplatedDecl();
14235 ProcessDeclAttributeList(S, D, Attrs);
14236
14237 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14238 if (Method->isStatic())
14239 checkThisInStaticMemberFunctionAttributes(Method);
14240 }
14241
14242 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14243 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
ImplicitlyDefineFunction(SourceLocation Loc,IdentifierInfo & II,Scope * S)14244 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14245 IdentifierInfo &II, Scope *S) {
14246 // Find the scope in which the identifier is injected and the corresponding
14247 // DeclContext.
14248 // FIXME: C89 does not say what happens if there is no enclosing block scope.
14249 // In that case, we inject the declaration into the translation unit scope
14250 // instead.
14251 Scope *BlockScope = S;
14252 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14253 BlockScope = BlockScope->getParent();
14254
14255 Scope *ContextScope = BlockScope;
14256 while (!ContextScope->getEntity())
14257 ContextScope = ContextScope->getParent();
14258 ContextRAII SavedContext(*this, ContextScope->getEntity());
14259
14260 // Before we produce a declaration for an implicitly defined
14261 // function, see whether there was a locally-scoped declaration of
14262 // this name as a function or variable. If so, use that
14263 // (non-visible) declaration, and complain about it.
14264 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14265 if (ExternCPrev) {
14266 // We still need to inject the function into the enclosing block scope so
14267 // that later (non-call) uses can see it.
14268 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14269
14270 // C89 footnote 38:
14271 // If in fact it is not defined as having type "function returning int",
14272 // the behavior is undefined.
14273 if (!isa<FunctionDecl>(ExternCPrev) ||
14274 !Context.typesAreCompatible(
14275 cast<FunctionDecl>(ExternCPrev)->getType(),
14276 Context.getFunctionNoProtoType(Context.IntTy))) {
14277 Diag(Loc, diag::ext_use_out_of_scope_declaration)
14278 << ExternCPrev << !getLangOpts().C99;
14279 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14280 return ExternCPrev;
14281 }
14282 }
14283
14284 // Extension in C99. Legal in C90, but warn about it.
14285 unsigned diag_id;
14286 if (II.getName().startswith("__builtin_"))
14287 diag_id = diag::warn_builtin_unknown;
14288 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14289 else if (getLangOpts().OpenCL)
14290 diag_id = diag::err_opencl_implicit_function_decl;
14291 else if (getLangOpts().C99)
14292 diag_id = diag::ext_implicit_function_decl;
14293 else
14294 diag_id = diag::warn_implicit_function_decl;
14295 Diag(Loc, diag_id) << &II;
14296
14297 // If we found a prior declaration of this function, don't bother building
14298 // another one. We've already pushed that one into scope, so there's nothing
14299 // more to do.
14300 if (ExternCPrev)
14301 return ExternCPrev;
14302
14303 // Because typo correction is expensive, only do it if the implicit
14304 // function declaration is going to be treated as an error.
14305 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14306 TypoCorrection Corrected;
14307 DeclFilterCCC<FunctionDecl> CCC{};
14308 if (S && (Corrected =
14309 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14310 S, nullptr, CCC, CTK_NonError)))
14311 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14312 /*ErrorRecovery*/false);
14313 }
14314
14315 // Set a Declarator for the implicit definition: int foo();
14316 const char *Dummy;
14317 AttributeFactory attrFactory;
14318 DeclSpec DS(attrFactory);
14319 unsigned DiagID;
14320 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14321 Context.getPrintingPolicy());
14322 (void)Error; // Silence warning.
14323 assert(!Error && "Error setting up implicit decl!");
14324 SourceLocation NoLoc;
14325 Declarator D(DS, DeclaratorContext::BlockContext);
14326 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14327 /*IsAmbiguous=*/false,
14328 /*LParenLoc=*/NoLoc,
14329 /*Params=*/nullptr,
14330 /*NumParams=*/0,
14331 /*EllipsisLoc=*/NoLoc,
14332 /*RParenLoc=*/NoLoc,
14333 /*RefQualifierIsLvalueRef=*/true,
14334 /*RefQualifierLoc=*/NoLoc,
14335 /*MutableLoc=*/NoLoc, EST_None,
14336 /*ESpecRange=*/SourceRange(),
14337 /*Exceptions=*/nullptr,
14338 /*ExceptionRanges=*/nullptr,
14339 /*NumExceptions=*/0,
14340 /*NoexceptExpr=*/nullptr,
14341 /*ExceptionSpecTokens=*/nullptr,
14342 /*DeclsInPrototype=*/None, Loc,
14343 Loc, D),
14344 std::move(DS.getAttributes()), SourceLocation());
14345 D.SetIdentifier(&II, Loc);
14346
14347 // Insert this function into the enclosing block scope.
14348 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14349 FD->setImplicit();
14350
14351 AddKnownFunctionAttributes(FD);
14352
14353 return FD;
14354 }
14355
14356 /// Adds any function attributes that we know a priori based on
14357 /// the declaration of this function.
14358 ///
14359 /// These attributes can apply both to implicitly-declared builtins
14360 /// (like __builtin___printf_chk) or to library-declared functions
14361 /// like NSLog or printf.
14362 ///
14363 /// We need to check for duplicate attributes both here and where user-written
14364 /// attributes are applied to declarations.
AddKnownFunctionAttributes(FunctionDecl * FD)14365 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14366 if (FD->isInvalidDecl())
14367 return;
14368
14369 // If this is a built-in function, map its builtin attributes to
14370 // actual attributes.
14371 if (unsigned BuiltinID = FD->getBuiltinID()) {
14372 // Handle printf-formatting attributes.
14373 unsigned FormatIdx;
14374 bool HasVAListArg;
14375 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14376 if (!FD->hasAttr<FormatAttr>()) {
14377 const char *fmt = "printf";
14378 unsigned int NumParams = FD->getNumParams();
14379 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14380 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14381 fmt = "NSString";
14382 FD->addAttr(FormatAttr::CreateImplicit(Context,
14383 &Context.Idents.get(fmt),
14384 FormatIdx+1,
14385 HasVAListArg ? 0 : FormatIdx+2,
14386 FD->getLocation()));
14387 }
14388 }
14389 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14390 HasVAListArg)) {
14391 if (!FD->hasAttr<FormatAttr>())
14392 FD->addAttr(FormatAttr::CreateImplicit(Context,
14393 &Context.Idents.get("scanf"),
14394 FormatIdx+1,
14395 HasVAListArg ? 0 : FormatIdx+2,
14396 FD->getLocation()));
14397 }
14398
14399 // Handle automatically recognized callbacks.
14400 SmallVector<int, 4> Encoding;
14401 if (!FD->hasAttr<CallbackAttr>() &&
14402 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14403 FD->addAttr(CallbackAttr::CreateImplicit(
14404 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14405
14406 // Mark const if we don't care about errno and that is the only thing
14407 // preventing the function from being const. This allows IRgen to use LLVM
14408 // intrinsics for such functions.
14409 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14410 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14411 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14412
14413 // We make "fma" on some platforms const because we know it does not set
14414 // errno in those environments even though it could set errno based on the
14415 // C standard.
14416 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14417 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14418 !FD->hasAttr<ConstAttr>()) {
14419 switch (BuiltinID) {
14420 case Builtin::BI__builtin_fma:
14421 case Builtin::BI__builtin_fmaf:
14422 case Builtin::BI__builtin_fmal:
14423 case Builtin::BIfma:
14424 case Builtin::BIfmaf:
14425 case Builtin::BIfmal:
14426 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14427 break;
14428 default:
14429 break;
14430 }
14431 }
14432
14433 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14434 !FD->hasAttr<ReturnsTwiceAttr>())
14435 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14436 FD->getLocation()));
14437 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14438 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14439 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14440 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14441 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14442 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14443 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14444 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14445 // Add the appropriate attribute, depending on the CUDA compilation mode
14446 // and which target the builtin belongs to. For example, during host
14447 // compilation, aux builtins are __device__, while the rest are __host__.
14448 if (getLangOpts().CUDAIsDevice !=
14449 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14450 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14451 else
14452 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14453 }
14454 }
14455
14456 // If C++ exceptions are enabled but we are told extern "C" functions cannot
14457 // throw, add an implicit nothrow attribute to any extern "C" function we come
14458 // across.
14459 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14460 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14461 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14462 if (!FPT || FPT->getExceptionSpecType() == EST_None)
14463 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14464 }
14465
14466 IdentifierInfo *Name = FD->getIdentifier();
14467 if (!Name)
14468 return;
14469 if ((!getLangOpts().CPlusPlus &&
14470 FD->getDeclContext()->isTranslationUnit()) ||
14471 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14472 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14473 LinkageSpecDecl::lang_c)) {
14474 // Okay: this could be a libc/libm/Objective-C function we know
14475 // about.
14476 } else
14477 return;
14478
14479 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14480 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14481 // target-specific builtins, perhaps?
14482 if (!FD->hasAttr<FormatAttr>())
14483 FD->addAttr(FormatAttr::CreateImplicit(Context,
14484 &Context.Idents.get("printf"), 2,
14485 Name->isStr("vasprintf") ? 0 : 3,
14486 FD->getLocation()));
14487 }
14488
14489 if (Name->isStr("__CFStringMakeConstantString")) {
14490 // We already have a __builtin___CFStringMakeConstantString,
14491 // but builds that use -fno-constant-cfstrings don't go through that.
14492 if (!FD->hasAttr<FormatArgAttr>())
14493 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14494 FD->getLocation()));
14495 }
14496 }
14497
ParseTypedefDecl(Scope * S,Declarator & D,QualType T,TypeSourceInfo * TInfo)14498 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14499 TypeSourceInfo *TInfo) {
14500 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
14501 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
14502
14503 if (!TInfo) {
14504 assert(D.isInvalidType() && "no declarator info for valid type");
14505 TInfo = Context.getTrivialTypeSourceInfo(T);
14506 }
14507
14508 // Scope manipulation handled by caller.
14509 TypedefDecl *NewTD =
14510 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14511 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14512
14513 // Bail out immediately if we have an invalid declaration.
14514 if (D.isInvalidType()) {
14515 NewTD->setInvalidDecl();
14516 return NewTD;
14517 }
14518
14519 if (D.getDeclSpec().isModulePrivateSpecified()) {
14520 if (CurContext->isFunctionOrMethod())
14521 Diag(NewTD->getLocation(), diag::err_module_private_local)
14522 << 2 << NewTD->getDeclName()
14523 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14524 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14525 else
14526 NewTD->setModulePrivate();
14527 }
14528
14529 // C++ [dcl.typedef]p8:
14530 // If the typedef declaration defines an unnamed class (or
14531 // enum), the first typedef-name declared by the declaration
14532 // to be that class type (or enum type) is used to denote the
14533 // class type (or enum type) for linkage purposes only.
14534 // We need to check whether the type was declared in the declaration.
14535 switch (D.getDeclSpec().getTypeSpecType()) {
14536 case TST_enum:
14537 case TST_struct:
14538 case TST_interface:
14539 case TST_union:
14540 case TST_class: {
14541 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
14542 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
14543 break;
14544 }
14545
14546 default:
14547 break;
14548 }
14549
14550 return NewTD;
14551 }
14552
14553 /// Check that this is a valid underlying type for an enum declaration.
CheckEnumUnderlyingType(TypeSourceInfo * TI)14554 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
14555 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
14556 QualType T = TI->getType();
14557
14558 if (T->isDependentType())
14559 return false;
14560
14561 if (const BuiltinType *BT = T->getAs<BuiltinType>())
14562 if (BT->isInteger())
14563 return false;
14564
14565 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
14566 return true;
14567 }
14568
14569 /// Check whether this is a valid redeclaration of a previous enumeration.
14570 /// \return true if the redeclaration was invalid.
CheckEnumRedeclaration(SourceLocation EnumLoc,bool IsScoped,QualType EnumUnderlyingTy,bool IsFixed,const EnumDecl * Prev)14571 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
14572 QualType EnumUnderlyingTy, bool IsFixed,
14573 const EnumDecl *Prev) {
14574 if (IsScoped != Prev->isScoped()) {
14575 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
14576 << Prev->isScoped();
14577 Diag(Prev->getLocation(), diag::note_previous_declaration);
14578 return true;
14579 }
14580
14581 if (IsFixed && Prev->isFixed()) {
14582 if (!EnumUnderlyingTy->isDependentType() &&
14583 !Prev->getIntegerType()->isDependentType() &&
14584 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
14585 Prev->getIntegerType())) {
14586 // TODO: Highlight the underlying type of the redeclaration.
14587 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
14588 << EnumUnderlyingTy << Prev->getIntegerType();
14589 Diag(Prev->getLocation(), diag::note_previous_declaration)
14590 << Prev->getIntegerTypeRange();
14591 return true;
14592 }
14593 } else if (IsFixed != Prev->isFixed()) {
14594 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
14595 << Prev->isFixed();
14596 Diag(Prev->getLocation(), diag::note_previous_declaration);
14597 return true;
14598 }
14599
14600 return false;
14601 }
14602
14603 /// Get diagnostic %select index for tag kind for
14604 /// redeclaration diagnostic message.
14605 /// WARNING: Indexes apply to particular diagnostics only!
14606 ///
14607 /// \returns diagnostic %select index.
getRedeclDiagFromTagKind(TagTypeKind Tag)14608 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
14609 switch (Tag) {
14610 case TTK_Struct: return 0;
14611 case TTK_Interface: return 1;
14612 case TTK_Class: return 2;
14613 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
14614 }
14615 }
14616
14617 /// Determine if tag kind is a class-key compatible with
14618 /// class for redeclaration (class, struct, or __interface).
14619 ///
14620 /// \returns true iff the tag kind is compatible.
isClassCompatTagKind(TagTypeKind Tag)14621 static bool isClassCompatTagKind(TagTypeKind Tag)
14622 {
14623 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
14624 }
14625
getNonTagTypeDeclKind(const Decl * PrevDecl,TagTypeKind TTK)14626 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
14627 TagTypeKind TTK) {
14628 if (isa<TypedefDecl>(PrevDecl))
14629 return NTK_Typedef;
14630 else if (isa<TypeAliasDecl>(PrevDecl))
14631 return NTK_TypeAlias;
14632 else if (isa<ClassTemplateDecl>(PrevDecl))
14633 return NTK_Template;
14634 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
14635 return NTK_TypeAliasTemplate;
14636 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
14637 return NTK_TemplateTemplateArgument;
14638 switch (TTK) {
14639 case TTK_Struct:
14640 case TTK_Interface:
14641 case TTK_Class:
14642 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
14643 case TTK_Union:
14644 return NTK_NonUnion;
14645 case TTK_Enum:
14646 return NTK_NonEnum;
14647 }
14648 llvm_unreachable("invalid TTK");
14649 }
14650
14651 /// Determine whether a tag with a given kind is acceptable
14652 /// as a redeclaration of the given tag declaration.
14653 ///
14654 /// \returns true if the new tag kind is acceptable, false otherwise.
isAcceptableTagRedeclaration(const TagDecl * Previous,TagTypeKind NewTag,bool isDefinition,SourceLocation NewTagLoc,const IdentifierInfo * Name)14655 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
14656 TagTypeKind NewTag, bool isDefinition,
14657 SourceLocation NewTagLoc,
14658 const IdentifierInfo *Name) {
14659 // C++ [dcl.type.elab]p3:
14660 // The class-key or enum keyword present in the
14661 // elaborated-type-specifier shall agree in kind with the
14662 // declaration to which the name in the elaborated-type-specifier
14663 // refers. This rule also applies to the form of
14664 // elaborated-type-specifier that declares a class-name or
14665 // friend class since it can be construed as referring to the
14666 // definition of the class. Thus, in any
14667 // elaborated-type-specifier, the enum keyword shall be used to
14668 // refer to an enumeration (7.2), the union class-key shall be
14669 // used to refer to a union (clause 9), and either the class or
14670 // struct class-key shall be used to refer to a class (clause 9)
14671 // declared using the class or struct class-key.
14672 TagTypeKind OldTag = Previous->getTagKind();
14673 if (OldTag != NewTag &&
14674 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
14675 return false;
14676
14677 // Tags are compatible, but we might still want to warn on mismatched tags.
14678 // Non-class tags can't be mismatched at this point.
14679 if (!isClassCompatTagKind(NewTag))
14680 return true;
14681
14682 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
14683 // by our warning analysis. We don't want to warn about mismatches with (eg)
14684 // declarations in system headers that are designed to be specialized, but if
14685 // a user asks us to warn, we should warn if their code contains mismatched
14686 // declarations.
14687 auto IsIgnoredLoc = [&](SourceLocation Loc) {
14688 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
14689 Loc);
14690 };
14691 if (IsIgnoredLoc(NewTagLoc))
14692 return true;
14693
14694 auto IsIgnored = [&](const TagDecl *Tag) {
14695 return IsIgnoredLoc(Tag->getLocation());
14696 };
14697 while (IsIgnored(Previous)) {
14698 Previous = Previous->getPreviousDecl();
14699 if (!Previous)
14700 return true;
14701 OldTag = Previous->getTagKind();
14702 }
14703
14704 bool isTemplate = false;
14705 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
14706 isTemplate = Record->getDescribedClassTemplate();
14707
14708 if (inTemplateInstantiation()) {
14709 if (OldTag != NewTag) {
14710 // In a template instantiation, do not offer fix-its for tag mismatches
14711 // since they usually mess up the template instead of fixing the problem.
14712 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14713 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14714 << getRedeclDiagFromTagKind(OldTag);
14715 // FIXME: Note previous location?
14716 }
14717 return true;
14718 }
14719
14720 if (isDefinition) {
14721 // On definitions, check all previous tags and issue a fix-it for each
14722 // one that doesn't match the current tag.
14723 if (Previous->getDefinition()) {
14724 // Don't suggest fix-its for redefinitions.
14725 return true;
14726 }
14727
14728 bool previousMismatch = false;
14729 for (const TagDecl *I : Previous->redecls()) {
14730 if (I->getTagKind() != NewTag) {
14731 // Ignore previous declarations for which the warning was disabled.
14732 if (IsIgnored(I))
14733 continue;
14734
14735 if (!previousMismatch) {
14736 previousMismatch = true;
14737 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
14738 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14739 << getRedeclDiagFromTagKind(I->getTagKind());
14740 }
14741 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
14742 << getRedeclDiagFromTagKind(NewTag)
14743 << FixItHint::CreateReplacement(I->getInnerLocStart(),
14744 TypeWithKeyword::getTagTypeKindName(NewTag));
14745 }
14746 }
14747 return true;
14748 }
14749
14750 // Identify the prevailing tag kind: this is the kind of the definition (if
14751 // there is a non-ignored definition), or otherwise the kind of the prior
14752 // (non-ignored) declaration.
14753 const TagDecl *PrevDef = Previous->getDefinition();
14754 if (PrevDef && IsIgnored(PrevDef))
14755 PrevDef = nullptr;
14756 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
14757 if (Redecl->getTagKind() != NewTag) {
14758 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14759 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14760 << getRedeclDiagFromTagKind(OldTag);
14761 Diag(Redecl->getLocation(), diag::note_previous_use);
14762
14763 // If there is a previous definition, suggest a fix-it.
14764 if (PrevDef) {
14765 Diag(NewTagLoc, diag::note_struct_class_suggestion)
14766 << getRedeclDiagFromTagKind(Redecl->getTagKind())
14767 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
14768 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
14769 }
14770 }
14771
14772 return true;
14773 }
14774
14775 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
14776 /// from an outer enclosing namespace or file scope inside a friend declaration.
14777 /// This should provide the commented out code in the following snippet:
14778 /// namespace N {
14779 /// struct X;
14780 /// namespace M {
14781 /// struct Y { friend struct /*N::*/ X; };
14782 /// }
14783 /// }
createFriendTagNNSFixIt(Sema & SemaRef,NamedDecl * ND,Scope * S,SourceLocation NameLoc)14784 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
14785 SourceLocation NameLoc) {
14786 // While the decl is in a namespace, do repeated lookup of that name and see
14787 // if we get the same namespace back. If we do not, continue until
14788 // translation unit scope, at which point we have a fully qualified NNS.
14789 SmallVector<IdentifierInfo *, 4> Namespaces;
14790 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14791 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
14792 // This tag should be declared in a namespace, which can only be enclosed by
14793 // other namespaces. Bail if there's an anonymous namespace in the chain.
14794 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
14795 if (!Namespace || Namespace->isAnonymousNamespace())
14796 return FixItHint();
14797 IdentifierInfo *II = Namespace->getIdentifier();
14798 Namespaces.push_back(II);
14799 NamedDecl *Lookup = SemaRef.LookupSingleName(
14800 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
14801 if (Lookup == Namespace)
14802 break;
14803 }
14804
14805 // Once we have all the namespaces, reverse them to go outermost first, and
14806 // build an NNS.
14807 SmallString<64> Insertion;
14808 llvm::raw_svector_ostream OS(Insertion);
14809 if (DC->isTranslationUnit())
14810 OS << "::";
14811 std::reverse(Namespaces.begin(), Namespaces.end());
14812 for (auto *II : Namespaces)
14813 OS << II->getName() << "::";
14814 return FixItHint::CreateInsertion(NameLoc, Insertion);
14815 }
14816
14817 /// Determine whether a tag originally declared in context \p OldDC can
14818 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14819 /// found a declaration in \p OldDC as a previous decl, perhaps through a
14820 /// using-declaration).
isAcceptableTagRedeclContext(Sema & S,DeclContext * OldDC,DeclContext * NewDC)14821 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14822 DeclContext *NewDC) {
14823 OldDC = OldDC->getRedeclContext();
14824 NewDC = NewDC->getRedeclContext();
14825
14826 if (OldDC->Equals(NewDC))
14827 return true;
14828
14829 // In MSVC mode, we allow a redeclaration if the contexts are related (either
14830 // encloses the other).
14831 if (S.getLangOpts().MSVCCompat &&
14832 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14833 return true;
14834
14835 return false;
14836 }
14837
14838 /// This is invoked when we see 'struct foo' or 'struct {'. In the
14839 /// former case, Name will be non-null. In the later case, Name will be null.
14840 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14841 /// reference/declaration/definition of a tag.
14842 ///
14843 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
14844 /// trailing-type-specifier) other than one in an alias-declaration.
14845 ///
14846 /// \param SkipBody If non-null, will be set to indicate if the caller should
14847 /// 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)14848 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14849 SourceLocation KWLoc, CXXScopeSpec &SS,
14850 IdentifierInfo *Name, SourceLocation NameLoc,
14851 const ParsedAttributesView &Attrs, AccessSpecifier AS,
14852 SourceLocation ModulePrivateLoc,
14853 MultiTemplateParamsArg TemplateParameterLists,
14854 bool &OwnedDecl, bool &IsDependent,
14855 SourceLocation ScopedEnumKWLoc,
14856 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14857 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14858 SkipBodyInfo *SkipBody) {
14859 // If this is not a definition, it must have a name.
14860 IdentifierInfo *OrigName = Name;
14861 assert((Name != nullptr || TUK == TUK_Definition) &&
14862 "Nameless record must be a definition!");
14863 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14864
14865 OwnedDecl = false;
14866 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14867 bool ScopedEnum = ScopedEnumKWLoc.isValid();
14868
14869 // FIXME: Check member specializations more carefully.
14870 bool isMemberSpecialization = false;
14871 bool Invalid = false;
14872
14873 // We only need to do this matching if we have template parameters
14874 // or a scope specifier, which also conveniently avoids this work
14875 // for non-C++ cases.
14876 if (TemplateParameterLists.size() > 0 ||
14877 (SS.isNotEmpty() && TUK != TUK_Reference)) {
14878 if (TemplateParameterList *TemplateParams =
14879 MatchTemplateParametersToScopeSpecifier(
14880 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14881 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14882 if (Kind == TTK_Enum) {
14883 Diag(KWLoc, diag::err_enum_template);
14884 return nullptr;
14885 }
14886
14887 if (TemplateParams->size() > 0) {
14888 // This is a declaration or definition of a class template (which may
14889 // be a member of another template).
14890
14891 if (Invalid)
14892 return nullptr;
14893
14894 OwnedDecl = false;
14895 DeclResult Result = CheckClassTemplate(
14896 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14897 AS, ModulePrivateLoc,
14898 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14899 TemplateParameterLists.data(), SkipBody);
14900 return Result.get();
14901 } else {
14902 // The "template<>" header is extraneous.
14903 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14904 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14905 isMemberSpecialization = true;
14906 }
14907 }
14908 }
14909
14910 // Figure out the underlying type if this a enum declaration. We need to do
14911 // this early, because it's needed to detect if this is an incompatible
14912 // redeclaration.
14913 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14914 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14915
14916 if (Kind == TTK_Enum) {
14917 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14918 // No underlying type explicitly specified, or we failed to parse the
14919 // type, default to int.
14920 EnumUnderlying = Context.IntTy.getTypePtr();
14921 } else if (UnderlyingType.get()) {
14922 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14923 // integral type; any cv-qualification is ignored.
14924 TypeSourceInfo *TI = nullptr;
14925 GetTypeFromParser(UnderlyingType.get(), &TI);
14926 EnumUnderlying = TI;
14927
14928 if (CheckEnumUnderlyingType(TI))
14929 // Recover by falling back to int.
14930 EnumUnderlying = Context.IntTy.getTypePtr();
14931
14932 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14933 UPPC_FixedUnderlyingType))
14934 EnumUnderlying = Context.IntTy.getTypePtr();
14935
14936 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
14937 // For MSVC ABI compatibility, unfixed enums must use an underlying type
14938 // of 'int'. However, if this is an unfixed forward declaration, don't set
14939 // the underlying type unless the user enables -fms-compatibility. This
14940 // makes unfixed forward declared enums incomplete and is more conforming.
14941 if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14942 EnumUnderlying = Context.IntTy.getTypePtr();
14943 }
14944 }
14945
14946 DeclContext *SearchDC = CurContext;
14947 DeclContext *DC = CurContext;
14948 bool isStdBadAlloc = false;
14949 bool isStdAlignValT = false;
14950
14951 RedeclarationKind Redecl = forRedeclarationInCurContext();
14952 if (TUK == TUK_Friend || TUK == TUK_Reference)
14953 Redecl = NotForRedeclaration;
14954
14955 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14956 /// implemented asks for structural equivalence checking, the returned decl
14957 /// here is passed back to the parser, allowing the tag body to be parsed.
14958 auto createTagFromNewDecl = [&]() -> TagDecl * {
14959 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14960 // If there is an identifier, use the location of the identifier as the
14961 // location of the decl, otherwise use the location of the struct/union
14962 // keyword.
14963 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14964 TagDecl *New = nullptr;
14965
14966 if (Kind == TTK_Enum) {
14967 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14968 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14969 // If this is an undefined enum, bail.
14970 if (TUK != TUK_Definition && !Invalid)
14971 return nullptr;
14972 if (EnumUnderlying) {
14973 EnumDecl *ED = cast<EnumDecl>(New);
14974 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14975 ED->setIntegerTypeSourceInfo(TI);
14976 else
14977 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14978 ED->setPromotionType(ED->getIntegerType());
14979 }
14980 } else { // struct/union
14981 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14982 nullptr);
14983 }
14984
14985 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14986 // Add alignment attributes if necessary; these attributes are checked
14987 // when the ASTContext lays out the structure.
14988 //
14989 // It is important for implementing the correct semantics that this
14990 // happen here (in ActOnTag). The #pragma pack stack is
14991 // maintained as a result of parser callbacks which can occur at
14992 // many points during the parsing of a struct declaration (because
14993 // the #pragma tokens are effectively skipped over during the
14994 // parsing of the struct).
14995 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14996 AddAlignmentAttributesForRecord(RD);
14997 AddMsStructLayoutForRecord(RD);
14998 }
14999 }
15000 New->setLexicalDeclContext(CurContext);
15001 return New;
15002 };
15003
15004 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15005 if (Name && SS.isNotEmpty()) {
15006 // We have a nested-name tag ('struct foo::bar').
15007
15008 // Check for invalid 'foo::'.
15009 if (SS.isInvalid()) {
15010 Name = nullptr;
15011 goto CreateNewDecl;
15012 }
15013
15014 // If this is a friend or a reference to a class in a dependent
15015 // context, don't try to make a decl for it.
15016 if (TUK == TUK_Friend || TUK == TUK_Reference) {
15017 DC = computeDeclContext(SS, false);
15018 if (!DC) {
15019 IsDependent = true;
15020 return nullptr;
15021 }
15022 } else {
15023 DC = computeDeclContext(SS, true);
15024 if (!DC) {
15025 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15026 << SS.getRange();
15027 return nullptr;
15028 }
15029 }
15030
15031 if (RequireCompleteDeclContext(SS, DC))
15032 return nullptr;
15033
15034 SearchDC = DC;
15035 // Look-up name inside 'foo::'.
15036 LookupQualifiedName(Previous, DC);
15037
15038 if (Previous.isAmbiguous())
15039 return nullptr;
15040
15041 if (Previous.empty()) {
15042 // Name lookup did not find anything. However, if the
15043 // nested-name-specifier refers to the current instantiation,
15044 // and that current instantiation has any dependent base
15045 // classes, we might find something at instantiation time: treat
15046 // this as a dependent elaborated-type-specifier.
15047 // But this only makes any sense for reference-like lookups.
15048 if (Previous.wasNotFoundInCurrentInstantiation() &&
15049 (TUK == TUK_Reference || TUK == TUK_Friend)) {
15050 IsDependent = true;
15051 return nullptr;
15052 }
15053
15054 // A tag 'foo::bar' must already exist.
15055 Diag(NameLoc, diag::err_not_tag_in_scope)
15056 << Kind << Name << DC << SS.getRange();
15057 Name = nullptr;
15058 Invalid = true;
15059 goto CreateNewDecl;
15060 }
15061 } else if (Name) {
15062 // C++14 [class.mem]p14:
15063 // If T is the name of a class, then each of the following shall have a
15064 // name different from T:
15065 // -- every member of class T that is itself a type
15066 if (TUK != TUK_Reference && TUK != TUK_Friend &&
15067 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15068 return nullptr;
15069
15070 // If this is a named struct, check to see if there was a previous forward
15071 // declaration or definition.
15072 // FIXME: We're looking into outer scopes here, even when we
15073 // shouldn't be. Doing so can result in ambiguities that we
15074 // shouldn't be diagnosing.
15075 LookupName(Previous, S);
15076
15077 // When declaring or defining a tag, ignore ambiguities introduced
15078 // by types using'ed into this scope.
15079 if (Previous.isAmbiguous() &&
15080 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15081 LookupResult::Filter F = Previous.makeFilter();
15082 while (F.hasNext()) {
15083 NamedDecl *ND = F.next();
15084 if (!ND->getDeclContext()->getRedeclContext()->Equals(
15085 SearchDC->getRedeclContext()))
15086 F.erase();
15087 }
15088 F.done();
15089 }
15090
15091 // C++11 [namespace.memdef]p3:
15092 // If the name in a friend declaration is neither qualified nor
15093 // a template-id and the declaration is a function or an
15094 // elaborated-type-specifier, the lookup to determine whether
15095 // the entity has been previously declared shall not consider
15096 // any scopes outside the innermost enclosing namespace.
15097 //
15098 // MSVC doesn't implement the above rule for types, so a friend tag
15099 // declaration may be a redeclaration of a type declared in an enclosing
15100 // scope. They do implement this rule for friend functions.
15101 //
15102 // Does it matter that this should be by scope instead of by
15103 // semantic context?
15104 if (!Previous.empty() && TUK == TUK_Friend) {
15105 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15106 LookupResult::Filter F = Previous.makeFilter();
15107 bool FriendSawTagOutsideEnclosingNamespace = false;
15108 while (F.hasNext()) {
15109 NamedDecl *ND = F.next();
15110 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15111 if (DC->isFileContext() &&
15112 !EnclosingNS->Encloses(ND->getDeclContext())) {
15113 if (getLangOpts().MSVCCompat)
15114 FriendSawTagOutsideEnclosingNamespace = true;
15115 else
15116 F.erase();
15117 }
15118 }
15119 F.done();
15120
15121 // Diagnose this MSVC extension in the easy case where lookup would have
15122 // unambiguously found something outside the enclosing namespace.
15123 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15124 NamedDecl *ND = Previous.getFoundDecl();
15125 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15126 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15127 }
15128 }
15129
15130 // Note: there used to be some attempt at recovery here.
15131 if (Previous.isAmbiguous())
15132 return nullptr;
15133
15134 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15135 // FIXME: This makes sure that we ignore the contexts associated
15136 // with C structs, unions, and enums when looking for a matching
15137 // tag declaration or definition. See the similar lookup tweak
15138 // in Sema::LookupName; is there a better way to deal with this?
15139 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15140 SearchDC = SearchDC->getParent();
15141 }
15142 }
15143
15144 if (Previous.isSingleResult() &&
15145 Previous.getFoundDecl()->isTemplateParameter()) {
15146 // Maybe we will complain about the shadowed template parameter.
15147 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15148 // Just pretend that we didn't see the previous declaration.
15149 Previous.clear();
15150 }
15151
15152 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15153 DC->Equals(getStdNamespace())) {
15154 if (Name->isStr("bad_alloc")) {
15155 // This is a declaration of or a reference to "std::bad_alloc".
15156 isStdBadAlloc = true;
15157
15158 // If std::bad_alloc has been implicitly declared (but made invisible to
15159 // name lookup), fill in this implicit declaration as the previous
15160 // declaration, so that the declarations get chained appropriately.
15161 if (Previous.empty() && StdBadAlloc)
15162 Previous.addDecl(getStdBadAlloc());
15163 } else if (Name->isStr("align_val_t")) {
15164 isStdAlignValT = true;
15165 if (Previous.empty() && StdAlignValT)
15166 Previous.addDecl(getStdAlignValT());
15167 }
15168 }
15169
15170 // If we didn't find a previous declaration, and this is a reference
15171 // (or friend reference), move to the correct scope. In C++, we
15172 // also need to do a redeclaration lookup there, just in case
15173 // there's a shadow friend decl.
15174 if (Name && Previous.empty() &&
15175 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15176 if (Invalid) goto CreateNewDecl;
15177 assert(SS.isEmpty());
15178
15179 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15180 // C++ [basic.scope.pdecl]p5:
15181 // -- for an elaborated-type-specifier of the form
15182 //
15183 // class-key identifier
15184 //
15185 // if the elaborated-type-specifier is used in the
15186 // decl-specifier-seq or parameter-declaration-clause of a
15187 // function defined in namespace scope, the identifier is
15188 // declared as a class-name in the namespace that contains
15189 // the declaration; otherwise, except as a friend
15190 // declaration, the identifier is declared in the smallest
15191 // non-class, non-function-prototype scope that contains the
15192 // declaration.
15193 //
15194 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15195 // C structs and unions.
15196 //
15197 // It is an error in C++ to declare (rather than define) an enum
15198 // type, including via an elaborated type specifier. We'll
15199 // diagnose that later; for now, declare the enum in the same
15200 // scope as we would have picked for any other tag type.
15201 //
15202 // GNU C also supports this behavior as part of its incomplete
15203 // enum types extension, while GNU C++ does not.
15204 //
15205 // Find the context where we'll be declaring the tag.
15206 // FIXME: We would like to maintain the current DeclContext as the
15207 // lexical context,
15208 SearchDC = getTagInjectionContext(SearchDC);
15209
15210 // Find the scope where we'll be declaring the tag.
15211 S = getTagInjectionScope(S, getLangOpts());
15212 } else {
15213 assert(TUK == TUK_Friend);
15214 // C++ [namespace.memdef]p3:
15215 // If a friend declaration in a non-local class first declares a
15216 // class or function, the friend class or function is a member of
15217 // the innermost enclosing namespace.
15218 SearchDC = SearchDC->getEnclosingNamespaceContext();
15219 }
15220
15221 // In C++, we need to do a redeclaration lookup to properly
15222 // diagnose some problems.
15223 // FIXME: redeclaration lookup is also used (with and without C++) to find a
15224 // hidden declaration so that we don't get ambiguity errors when using a
15225 // type declared by an elaborated-type-specifier. In C that is not correct
15226 // and we should instead merge compatible types found by lookup.
15227 if (getLangOpts().CPlusPlus) {
15228 Previous.setRedeclarationKind(forRedeclarationInCurContext());
15229 LookupQualifiedName(Previous, SearchDC);
15230 } else {
15231 Previous.setRedeclarationKind(forRedeclarationInCurContext());
15232 LookupName(Previous, S);
15233 }
15234 }
15235
15236 // If we have a known previous declaration to use, then use it.
15237 if (Previous.empty() && SkipBody && SkipBody->Previous)
15238 Previous.addDecl(SkipBody->Previous);
15239
15240 if (!Previous.empty()) {
15241 NamedDecl *PrevDecl = Previous.getFoundDecl();
15242 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15243
15244 // It's okay to have a tag decl in the same scope as a typedef
15245 // which hides a tag decl in the same scope. Finding this
15246 // insanity with a redeclaration lookup can only actually happen
15247 // in C++.
15248 //
15249 // This is also okay for elaborated-type-specifiers, which is
15250 // technically forbidden by the current standard but which is
15251 // okay according to the likely resolution of an open issue;
15252 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15253 if (getLangOpts().CPlusPlus) {
15254 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15255 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15256 TagDecl *Tag = TT->getDecl();
15257 if (Tag->getDeclName() == Name &&
15258 Tag->getDeclContext()->getRedeclContext()
15259 ->Equals(TD->getDeclContext()->getRedeclContext())) {
15260 PrevDecl = Tag;
15261 Previous.clear();
15262 Previous.addDecl(Tag);
15263 Previous.resolveKind();
15264 }
15265 }
15266 }
15267 }
15268
15269 // If this is a redeclaration of a using shadow declaration, it must
15270 // declare a tag in the same context. In MSVC mode, we allow a
15271 // redefinition if either context is within the other.
15272 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15273 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15274 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15275 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15276 !(OldTag && isAcceptableTagRedeclContext(
15277 *this, OldTag->getDeclContext(), SearchDC))) {
15278 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15279 Diag(Shadow->getTargetDecl()->getLocation(),
15280 diag::note_using_decl_target);
15281 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15282 << 0;
15283 // Recover by ignoring the old declaration.
15284 Previous.clear();
15285 goto CreateNewDecl;
15286 }
15287 }
15288
15289 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15290 // If this is a use of a previous tag, or if the tag is already declared
15291 // in the same scope (so that the definition/declaration completes or
15292 // rementions the tag), reuse the decl.
15293 if (TUK == TUK_Reference || TUK == TUK_Friend ||
15294 isDeclInScope(DirectPrevDecl, SearchDC, S,
15295 SS.isNotEmpty() || isMemberSpecialization)) {
15296 // Make sure that this wasn't declared as an enum and now used as a
15297 // struct or something similar.
15298 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15299 TUK == TUK_Definition, KWLoc,
15300 Name)) {
15301 bool SafeToContinue
15302 = (PrevTagDecl->getTagKind() != TTK_Enum &&
15303 Kind != TTK_Enum);
15304 if (SafeToContinue)
15305 Diag(KWLoc, diag::err_use_with_wrong_tag)
15306 << Name
15307 << FixItHint::CreateReplacement(SourceRange(KWLoc),
15308 PrevTagDecl->getKindName());
15309 else
15310 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15311 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15312
15313 if (SafeToContinue)
15314 Kind = PrevTagDecl->getTagKind();
15315 else {
15316 // Recover by making this an anonymous redefinition.
15317 Name = nullptr;
15318 Previous.clear();
15319 Invalid = true;
15320 }
15321 }
15322
15323 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15324 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15325
15326 // If this is an elaborated-type-specifier for a scoped enumeration,
15327 // the 'class' keyword is not necessary and not permitted.
15328 if (TUK == TUK_Reference || TUK == TUK_Friend) {
15329 if (ScopedEnum)
15330 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
15331 << PrevEnum->isScoped()
15332 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
15333 return PrevTagDecl;
15334 }
15335
15336 QualType EnumUnderlyingTy;
15337 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15338 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15339 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15340 EnumUnderlyingTy = QualType(T, 0);
15341
15342 // All conflicts with previous declarations are recovered by
15343 // returning the previous declaration, unless this is a definition,
15344 // in which case we want the caller to bail out.
15345 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15346 ScopedEnum, EnumUnderlyingTy,
15347 IsFixed, PrevEnum))
15348 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15349 }
15350
15351 // C++11 [class.mem]p1:
15352 // A member shall not be declared twice in the member-specification,
15353 // except that a nested class or member class template can be declared
15354 // and then later defined.
15355 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15356 S->isDeclScope(PrevDecl)) {
15357 Diag(NameLoc, diag::ext_member_redeclared);
15358 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15359 }
15360
15361 if (!Invalid) {
15362 // If this is a use, just return the declaration we found, unless
15363 // we have attributes.
15364 if (TUK == TUK_Reference || TUK == TUK_Friend) {
15365 if (!Attrs.empty()) {
15366 // FIXME: Diagnose these attributes. For now, we create a new
15367 // declaration to hold them.
15368 } else if (TUK == TUK_Reference &&
15369 (PrevTagDecl->getFriendObjectKind() ==
15370 Decl::FOK_Undeclared ||
15371 PrevDecl->getOwningModule() != getCurrentModule()) &&
15372 SS.isEmpty()) {
15373 // This declaration is a reference to an existing entity, but
15374 // has different visibility from that entity: it either makes
15375 // a friend visible or it makes a type visible in a new module.
15376 // In either case, create a new declaration. We only do this if
15377 // the declaration would have meant the same thing if no prior
15378 // declaration were found, that is, if it was found in the same
15379 // scope where we would have injected a declaration.
15380 if (!getTagInjectionContext(CurContext)->getRedeclContext()
15381 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15382 return PrevTagDecl;
15383 // This is in the injected scope, create a new declaration in
15384 // that scope.
15385 S = getTagInjectionScope(S, getLangOpts());
15386 } else {
15387 return PrevTagDecl;
15388 }
15389 }
15390
15391 // Diagnose attempts to redefine a tag.
15392 if (TUK == TUK_Definition) {
15393 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15394 // If we're defining a specialization and the previous definition
15395 // is from an implicit instantiation, don't emit an error
15396 // here; we'll catch this in the general case below.
15397 bool IsExplicitSpecializationAfterInstantiation = false;
15398 if (isMemberSpecialization) {
15399 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15400 IsExplicitSpecializationAfterInstantiation =
15401 RD->getTemplateSpecializationKind() !=
15402 TSK_ExplicitSpecialization;
15403 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15404 IsExplicitSpecializationAfterInstantiation =
15405 ED->getTemplateSpecializationKind() !=
15406 TSK_ExplicitSpecialization;
15407 }
15408
15409 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15410 // not keep more that one definition around (merge them). However,
15411 // ensure the decl passes the structural compatibility check in
15412 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15413 NamedDecl *Hidden = nullptr;
15414 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15415 // There is a definition of this tag, but it is not visible. We
15416 // explicitly make use of C++'s one definition rule here, and
15417 // assume that this definition is identical to the hidden one
15418 // we already have. Make the existing definition visible and
15419 // use it in place of this one.
15420 if (!getLangOpts().CPlusPlus) {
15421 // Postpone making the old definition visible until after we
15422 // complete parsing the new one and do the structural
15423 // comparison.
15424 SkipBody->CheckSameAsPrevious = true;
15425 SkipBody->New = createTagFromNewDecl();
15426 SkipBody->Previous = Def;
15427 return Def;
15428 } else {
15429 SkipBody->ShouldSkip = true;
15430 SkipBody->Previous = Def;
15431 makeMergedDefinitionVisible(Hidden);
15432 // Carry on and handle it like a normal definition. We'll
15433 // skip starting the definitiion later.
15434 }
15435 } else if (!IsExplicitSpecializationAfterInstantiation) {
15436 // A redeclaration in function prototype scope in C isn't
15437 // visible elsewhere, so merely issue a warning.
15438 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15439 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15440 else
15441 Diag(NameLoc, diag::err_redefinition) << Name;
15442 notePreviousDefinition(Def,
15443 NameLoc.isValid() ? NameLoc : KWLoc);
15444 // If this is a redefinition, recover by making this
15445 // struct be anonymous, which will make any later
15446 // references get the previous definition.
15447 Name = nullptr;
15448 Previous.clear();
15449 Invalid = true;
15450 }
15451 } else {
15452 // If the type is currently being defined, complain
15453 // about a nested redefinition.
15454 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15455 if (TD->isBeingDefined()) {
15456 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15457 Diag(PrevTagDecl->getLocation(),
15458 diag::note_previous_definition);
15459 Name = nullptr;
15460 Previous.clear();
15461 Invalid = true;
15462 }
15463 }
15464
15465 // Okay, this is definition of a previously declared or referenced
15466 // tag. We're going to create a new Decl for it.
15467 }
15468
15469 // Okay, we're going to make a redeclaration. If this is some kind
15470 // of reference, make sure we build the redeclaration in the same DC
15471 // as the original, and ignore the current access specifier.
15472 if (TUK == TUK_Friend || TUK == TUK_Reference) {
15473 SearchDC = PrevTagDecl->getDeclContext();
15474 AS = AS_none;
15475 }
15476 }
15477 // If we get here we have (another) forward declaration or we
15478 // have a definition. Just create a new decl.
15479
15480 } else {
15481 // If we get here, this is a definition of a new tag type in a nested
15482 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15483 // new decl/type. We set PrevDecl to NULL so that the entities
15484 // have distinct types.
15485 Previous.clear();
15486 }
15487 // If we get here, we're going to create a new Decl. If PrevDecl
15488 // is non-NULL, it's a definition of the tag declared by
15489 // PrevDecl. If it's NULL, we have a new definition.
15490
15491 // Otherwise, PrevDecl is not a tag, but was found with tag
15492 // lookup. This is only actually possible in C++, where a few
15493 // things like templates still live in the tag namespace.
15494 } else {
15495 // Use a better diagnostic if an elaborated-type-specifier
15496 // found the wrong kind of type on the first
15497 // (non-redeclaration) lookup.
15498 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15499 !Previous.isForRedeclaration()) {
15500 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15501 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15502 << Kind;
15503 Diag(PrevDecl->getLocation(), diag::note_declared_at);
15504 Invalid = true;
15505
15506 // Otherwise, only diagnose if the declaration is in scope.
15507 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15508 SS.isNotEmpty() || isMemberSpecialization)) {
15509 // do nothing
15510
15511 // Diagnose implicit declarations introduced by elaborated types.
15512 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15513 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15514 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15515 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15516 Invalid = true;
15517
15518 // Otherwise it's a declaration. Call out a particularly common
15519 // case here.
15520 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15521 unsigned Kind = 0;
15522 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15523 Diag(NameLoc, diag::err_tag_definition_of_typedef)
15524 << Name << Kind << TND->getUnderlyingType();
15525 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15526 Invalid = true;
15527
15528 // Otherwise, diagnose.
15529 } else {
15530 // The tag name clashes with something else in the target scope,
15531 // issue an error and recover by making this tag be anonymous.
15532 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15533 notePreviousDefinition(PrevDecl, NameLoc);
15534 Name = nullptr;
15535 Invalid = true;
15536 }
15537
15538 // The existing declaration isn't relevant to us; we're in a
15539 // new scope, so clear out the previous declaration.
15540 Previous.clear();
15541 }
15542 }
15543
15544 CreateNewDecl:
15545
15546 TagDecl *PrevDecl = nullptr;
15547 if (Previous.isSingleResult())
15548 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
15549
15550 // If there is an identifier, use the location of the identifier as the
15551 // location of the decl, otherwise use the location of the struct/union
15552 // keyword.
15553 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15554
15555 // Otherwise, create a new declaration. If there is a previous
15556 // declaration of the same entity, the two will be linked via
15557 // PrevDecl.
15558 TagDecl *New;
15559
15560 if (Kind == TTK_Enum) {
15561 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15562 // enum X { A, B, C } D; D should chain to X.
15563 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
15564 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
15565 ScopedEnumUsesClassTag, IsFixed);
15566
15567 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
15568 StdAlignValT = cast<EnumDecl>(New);
15569
15570 // If this is an undefined enum, warn.
15571 if (TUK != TUK_Definition && !Invalid) {
15572 TagDecl *Def;
15573 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
15574 // C++0x: 7.2p2: opaque-enum-declaration.
15575 // Conflicts are diagnosed above. Do nothing.
15576 }
15577 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
15578 Diag(Loc, diag::ext_forward_ref_enum_def)
15579 << New;
15580 Diag(Def->getLocation(), diag::note_previous_definition);
15581 } else {
15582 unsigned DiagID = diag::ext_forward_ref_enum;
15583 if (getLangOpts().MSVCCompat)
15584 DiagID = diag::ext_ms_forward_ref_enum;
15585 else if (getLangOpts().CPlusPlus)
15586 DiagID = diag::err_forward_ref_enum;
15587 Diag(Loc, DiagID);
15588 }
15589 }
15590
15591 if (EnumUnderlying) {
15592 EnumDecl *ED = cast<EnumDecl>(New);
15593 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15594 ED->setIntegerTypeSourceInfo(TI);
15595 else
15596 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
15597 ED->setPromotionType(ED->getIntegerType());
15598 assert(ED->isComplete() && "enum with type should be complete");
15599 }
15600 } else {
15601 // struct/union/class
15602
15603 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15604 // struct X { int A; } D; D should chain to X.
15605 if (getLangOpts().CPlusPlus) {
15606 // FIXME: Look for a way to use RecordDecl for simple structs.
15607 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15608 cast_or_null<CXXRecordDecl>(PrevDecl));
15609
15610 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
15611 StdBadAlloc = cast<CXXRecordDecl>(New);
15612 } else
15613 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15614 cast_or_null<RecordDecl>(PrevDecl));
15615 }
15616
15617 // C++11 [dcl.type]p3:
15618 // A type-specifier-seq shall not define a class or enumeration [...].
15619 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
15620 TUK == TUK_Definition) {
15621 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
15622 << Context.getTagDeclType(New);
15623 Invalid = true;
15624 }
15625
15626 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
15627 DC->getDeclKind() == Decl::Enum) {
15628 Diag(New->getLocation(), diag::err_type_defined_in_enum)
15629 << Context.getTagDeclType(New);
15630 Invalid = true;
15631 }
15632
15633 // Maybe add qualifier info.
15634 if (SS.isNotEmpty()) {
15635 if (SS.isSet()) {
15636 // If this is either a declaration or a definition, check the
15637 // nested-name-specifier against the current context.
15638 if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
15639 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
15640 isMemberSpecialization))
15641 Invalid = true;
15642
15643 New->setQualifierInfo(SS.getWithLocInContext(Context));
15644 if (TemplateParameterLists.size() > 0) {
15645 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
15646 }
15647 }
15648 else
15649 Invalid = true;
15650 }
15651
15652 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15653 // Add alignment attributes if necessary; these attributes are checked when
15654 // the ASTContext lays out the structure.
15655 //
15656 // It is important for implementing the correct semantics that this
15657 // happen here (in ActOnTag). The #pragma pack stack is
15658 // maintained as a result of parser callbacks which can occur at
15659 // many points during the parsing of a struct declaration (because
15660 // the #pragma tokens are effectively skipped over during the
15661 // parsing of the struct).
15662 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15663 AddAlignmentAttributesForRecord(RD);
15664 AddMsStructLayoutForRecord(RD);
15665 }
15666 }
15667
15668 if (ModulePrivateLoc.isValid()) {
15669 if (isMemberSpecialization)
15670 Diag(New->getLocation(), diag::err_module_private_specialization)
15671 << 2
15672 << FixItHint::CreateRemoval(ModulePrivateLoc);
15673 // __module_private__ does not apply to local classes. However, we only
15674 // diagnose this as an error when the declaration specifiers are
15675 // freestanding. Here, we just ignore the __module_private__.
15676 else if (!SearchDC->isFunctionOrMethod())
15677 New->setModulePrivate();
15678 }
15679
15680 // If this is a specialization of a member class (of a class template),
15681 // check the specialization.
15682 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
15683 Invalid = true;
15684
15685 // If we're declaring or defining a tag in function prototype scope in C,
15686 // note that this type can only be used within the function and add it to
15687 // the list of decls to inject into the function definition scope.
15688 if ((Name || Kind == TTK_Enum) &&
15689 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
15690 if (getLangOpts().CPlusPlus) {
15691 // C++ [dcl.fct]p6:
15692 // Types shall not be defined in return or parameter types.
15693 if (TUK == TUK_Definition && !IsTypeSpecifier) {
15694 Diag(Loc, diag::err_type_defined_in_param_type)
15695 << Name;
15696 Invalid = true;
15697 }
15698 } else if (!PrevDecl) {
15699 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
15700 }
15701 }
15702
15703 if (Invalid)
15704 New->setInvalidDecl();
15705
15706 // Set the lexical context. If the tag has a C++ scope specifier, the
15707 // lexical context will be different from the semantic context.
15708 New->setLexicalDeclContext(CurContext);
15709
15710 // Mark this as a friend decl if applicable.
15711 // In Microsoft mode, a friend declaration also acts as a forward
15712 // declaration so we always pass true to setObjectOfFriendDecl to make
15713 // the tag name visible.
15714 if (TUK == TUK_Friend)
15715 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
15716
15717 // Set the access specifier.
15718 if (!Invalid && SearchDC->isRecord())
15719 SetMemberAccessSpecifier(New, PrevDecl, AS);
15720
15721 if (PrevDecl)
15722 CheckRedeclarationModuleOwnership(New, PrevDecl);
15723
15724 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
15725 New->startDefinition();
15726
15727 ProcessDeclAttributeList(S, New, Attrs);
15728 AddPragmaAttributes(S, New);
15729
15730 // If this has an identifier, add it to the scope stack.
15731 if (TUK == TUK_Friend) {
15732 // We might be replacing an existing declaration in the lookup tables;
15733 // if so, borrow its access specifier.
15734 if (PrevDecl)
15735 New->setAccess(PrevDecl->getAccess());
15736
15737 DeclContext *DC = New->getDeclContext()->getRedeclContext();
15738 DC->makeDeclVisibleInContext(New);
15739 if (Name) // can be null along some error paths
15740 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
15741 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
15742 } else if (Name) {
15743 S = getNonFieldDeclScope(S);
15744 PushOnScopeChains(New, S, true);
15745 } else {
15746 CurContext->addDecl(New);
15747 }
15748
15749 // If this is the C FILE type, notify the AST context.
15750 if (IdentifierInfo *II = New->getIdentifier())
15751 if (!New->isInvalidDecl() &&
15752 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
15753 II->isStr("FILE"))
15754 Context.setFILEDecl(New);
15755
15756 if (PrevDecl)
15757 mergeDeclAttributes(New, PrevDecl);
15758
15759 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
15760 inferGslOwnerPointerAttribute(CXXRD);
15761
15762 // If there's a #pragma GCC visibility in scope, set the visibility of this
15763 // record.
15764 AddPushedVisibilityAttribute(New);
15765
15766 if (isMemberSpecialization && !New->isInvalidDecl())
15767 CompleteMemberSpecialization(New, Previous);
15768
15769 OwnedDecl = true;
15770 // In C++, don't return an invalid declaration. We can't recover well from
15771 // the cases where we make the type anonymous.
15772 if (Invalid && getLangOpts().CPlusPlus) {
15773 if (New->isBeingDefined())
15774 if (auto RD = dyn_cast<RecordDecl>(New))
15775 RD->completeDefinition();
15776 return nullptr;
15777 } else if (SkipBody && SkipBody->ShouldSkip) {
15778 return SkipBody->Previous;
15779 } else {
15780 return New;
15781 }
15782 }
15783
ActOnTagStartDefinition(Scope * S,Decl * TagD)15784 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
15785 AdjustDeclIfTemplate(TagD);
15786 TagDecl *Tag = cast<TagDecl>(TagD);
15787
15788 // Enter the tag context.
15789 PushDeclContext(S, Tag);
15790
15791 ActOnDocumentableDecl(TagD);
15792
15793 // If there's a #pragma GCC visibility in scope, set the visibility of this
15794 // record.
15795 AddPushedVisibilityAttribute(Tag);
15796 }
15797
ActOnDuplicateDefinition(DeclSpec & DS,Decl * Prev,SkipBodyInfo & SkipBody)15798 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
15799 SkipBodyInfo &SkipBody) {
15800 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
15801 return false;
15802
15803 // Make the previous decl visible.
15804 makeMergedDefinitionVisible(SkipBody.Previous);
15805 return true;
15806 }
15807
ActOnObjCContainerStartDefinition(Decl * IDecl)15808 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15809 assert(isa<ObjCContainerDecl>(IDecl) &&
15810 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15811 DeclContext *OCD = cast<DeclContext>(IDecl);
15812 assert(getContainingDC(OCD) == CurContext &&
15813 "The next DeclContext should be lexically contained in the current one.");
15814 CurContext = OCD;
15815 return IDecl;
15816 }
15817
ActOnStartCXXMemberDeclarations(Scope * S,Decl * TagD,SourceLocation FinalLoc,bool IsFinalSpelledSealed,SourceLocation LBraceLoc)15818 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15819 SourceLocation FinalLoc,
15820 bool IsFinalSpelledSealed,
15821 SourceLocation LBraceLoc) {
15822 AdjustDeclIfTemplate(TagD);
15823 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15824
15825 FieldCollector->StartClass();
15826
15827 if (!Record->getIdentifier())
15828 return;
15829
15830 if (FinalLoc.isValid())
15831 Record->addAttr(FinalAttr::Create(
15832 Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
15833 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
15834
15835 // C++ [class]p2:
15836 // [...] The class-name is also inserted into the scope of the
15837 // class itself; this is known as the injected-class-name. For
15838 // purposes of access checking, the injected-class-name is treated
15839 // as if it were a public member name.
15840 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15841 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15842 Record->getLocation(), Record->getIdentifier(),
15843 /*PrevDecl=*/nullptr,
15844 /*DelayTypeCreation=*/true);
15845 Context.getTypeDeclType(InjectedClassName, Record);
15846 InjectedClassName->setImplicit();
15847 InjectedClassName->setAccess(AS_public);
15848 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15849 InjectedClassName->setDescribedClassTemplate(Template);
15850 PushOnScopeChains(InjectedClassName, S);
15851 assert(InjectedClassName->isInjectedClassName() &&
15852 "Broken injected-class-name");
15853 }
15854
ActOnTagFinishDefinition(Scope * S,Decl * TagD,SourceRange BraceRange)15855 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15856 SourceRange BraceRange) {
15857 AdjustDeclIfTemplate(TagD);
15858 TagDecl *Tag = cast<TagDecl>(TagD);
15859 Tag->setBraceRange(BraceRange);
15860
15861 // Make sure we "complete" the definition even it is invalid.
15862 if (Tag->isBeingDefined()) {
15863 assert(Tag->isInvalidDecl() && "We should already have completed it");
15864 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15865 RD->completeDefinition();
15866 }
15867
15868 if (isa<CXXRecordDecl>(Tag)) {
15869 FieldCollector->FinishClass();
15870 }
15871
15872 // Exit this scope of this tag's definition.
15873 PopDeclContext();
15874
15875 if (getCurLexicalContext()->isObjCContainer() &&
15876 Tag->getDeclContext()->isFileContext())
15877 Tag->setTopLevelDeclInObjCContainer();
15878
15879 // Notify the consumer that we've defined a tag.
15880 if (!Tag->isInvalidDecl())
15881 Consumer.HandleTagDeclDefinition(Tag);
15882 }
15883
ActOnObjCContainerFinishDefinition()15884 void Sema::ActOnObjCContainerFinishDefinition() {
15885 // Exit this scope of this interface definition.
15886 PopDeclContext();
15887 }
15888
ActOnObjCTemporaryExitContainerContext(DeclContext * DC)15889 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15890 assert(DC == CurContext && "Mismatch of container contexts");
15891 OriginalLexicalContext = DC;
15892 ActOnObjCContainerFinishDefinition();
15893 }
15894
ActOnObjCReenterContainerContext(DeclContext * DC)15895 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15896 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15897 OriginalLexicalContext = nullptr;
15898 }
15899
ActOnTagDefinitionError(Scope * S,Decl * TagD)15900 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15901 AdjustDeclIfTemplate(TagD);
15902 TagDecl *Tag = cast<TagDecl>(TagD);
15903 Tag->setInvalidDecl();
15904
15905 // Make sure we "complete" the definition even it is invalid.
15906 if (Tag->isBeingDefined()) {
15907 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15908 RD->completeDefinition();
15909 }
15910
15911 // We're undoing ActOnTagStartDefinition here, not
15912 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15913 // the FieldCollector.
15914
15915 PopDeclContext();
15916 }
15917
15918 // Note that FieldName may be null for anonymous bitfields.
VerifyBitField(SourceLocation FieldLoc,IdentifierInfo * FieldName,QualType FieldTy,bool IsMsStruct,Expr * BitWidth,bool * ZeroWidth)15919 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15920 IdentifierInfo *FieldName,
15921 QualType FieldTy, bool IsMsStruct,
15922 Expr *BitWidth, bool *ZeroWidth) {
15923 // Default to true; that shouldn't confuse checks for emptiness
15924 if (ZeroWidth)
15925 *ZeroWidth = true;
15926
15927 // C99 6.7.2.1p4 - verify the field type.
15928 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15929 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15930 // Handle incomplete types with specific error.
15931 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15932 return ExprError();
15933 if (FieldName)
15934 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15935 << FieldName << FieldTy << BitWidth->getSourceRange();
15936 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15937 << FieldTy << BitWidth->getSourceRange();
15938 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15939 UPPC_BitFieldWidth))
15940 return ExprError();
15941
15942 // If the bit-width is type- or value-dependent, don't try to check
15943 // it now.
15944 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15945 return BitWidth;
15946
15947 llvm::APSInt Value;
15948 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15949 if (ICE.isInvalid())
15950 return ICE;
15951 BitWidth = ICE.get();
15952
15953 if (Value != 0 && ZeroWidth)
15954 *ZeroWidth = false;
15955
15956 // Zero-width bitfield is ok for anonymous field.
15957 if (Value == 0 && FieldName)
15958 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15959
15960 if (Value.isSigned() && Value.isNegative()) {
15961 if (FieldName)
15962 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15963 << FieldName << Value.toString(10);
15964 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15965 << Value.toString(10);
15966 }
15967
15968 if (!FieldTy->isDependentType()) {
15969 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15970 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15971 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15972
15973 // Over-wide bitfields are an error in C or when using the MSVC bitfield
15974 // ABI.
15975 bool CStdConstraintViolation =
15976 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15977 bool MSBitfieldViolation =
15978 Value.ugt(TypeStorageSize) &&
15979 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15980 if (CStdConstraintViolation || MSBitfieldViolation) {
15981 unsigned DiagWidth =
15982 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15983 if (FieldName)
15984 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15985 << FieldName << (unsigned)Value.getZExtValue()
15986 << !CStdConstraintViolation << DiagWidth;
15987
15988 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15989 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15990 << DiagWidth;
15991 }
15992
15993 // Warn on types where the user might conceivably expect to get all
15994 // specified bits as value bits: that's all integral types other than
15995 // 'bool'.
15996 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15997 if (FieldName)
15998 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15999 << FieldName << (unsigned)Value.getZExtValue()
16000 << (unsigned)TypeWidth;
16001 else
16002 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
16003 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
16004 }
16005 }
16006
16007 return BitWidth;
16008 }
16009
16010 /// ActOnField - Each field of a C struct/union is passed into this in order
16011 /// to create a FieldDecl object for it.
ActOnField(Scope * S,Decl * TagD,SourceLocation DeclStart,Declarator & D,Expr * BitfieldWidth)16012 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16013 Declarator &D, Expr *BitfieldWidth) {
16014 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16015 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16016 /*InitStyle=*/ICIS_NoInit, AS_public);
16017 return Res;
16018 }
16019
16020 /// HandleField - Analyze a field of a C struct or a C++ data member.
16021 ///
HandleField(Scope * S,RecordDecl * Record,SourceLocation DeclStart,Declarator & D,Expr * BitWidth,InClassInitStyle InitStyle,AccessSpecifier AS)16022 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16023 SourceLocation DeclStart,
16024 Declarator &D, Expr *BitWidth,
16025 InClassInitStyle InitStyle,
16026 AccessSpecifier AS) {
16027 if (D.isDecompositionDeclarator()) {
16028 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16029 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16030 << Decomp.getSourceRange();
16031 return nullptr;
16032 }
16033
16034 IdentifierInfo *II = D.getIdentifier();
16035 SourceLocation Loc = DeclStart;
16036 if (II) Loc = D.getIdentifierLoc();
16037
16038 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16039 QualType T = TInfo->getType();
16040 if (getLangOpts().CPlusPlus) {
16041 CheckExtraCXXDefaultArguments(D);
16042
16043 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16044 UPPC_DataMemberType)) {
16045 D.setInvalidType();
16046 T = Context.IntTy;
16047 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16048 }
16049 }
16050
16051 DiagnoseFunctionSpecifiers(D.getDeclSpec());
16052
16053 if (D.getDeclSpec().isInlineSpecified())
16054 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16055 << getLangOpts().CPlusPlus17;
16056 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16057 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16058 diag::err_invalid_thread)
16059 << DeclSpec::getSpecifierName(TSCS);
16060
16061 // Check to see if this name was declared as a member previously
16062 NamedDecl *PrevDecl = nullptr;
16063 LookupResult Previous(*this, II, Loc, LookupMemberName,
16064 ForVisibleRedeclaration);
16065 LookupName(Previous, S);
16066 switch (Previous.getResultKind()) {
16067 case LookupResult::Found:
16068 case LookupResult::FoundUnresolvedValue:
16069 PrevDecl = Previous.getAsSingle<NamedDecl>();
16070 break;
16071
16072 case LookupResult::FoundOverloaded:
16073 PrevDecl = Previous.getRepresentativeDecl();
16074 break;
16075
16076 case LookupResult::NotFound:
16077 case LookupResult::NotFoundInCurrentInstantiation:
16078 case LookupResult::Ambiguous:
16079 break;
16080 }
16081 Previous.suppressDiagnostics();
16082
16083 if (PrevDecl && PrevDecl->isTemplateParameter()) {
16084 // Maybe we will complain about the shadowed template parameter.
16085 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16086 // Just pretend that we didn't see the previous declaration.
16087 PrevDecl = nullptr;
16088 }
16089
16090 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16091 PrevDecl = nullptr;
16092
16093 bool Mutable
16094 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16095 SourceLocation TSSL = D.getBeginLoc();
16096 FieldDecl *NewFD
16097 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16098 TSSL, AS, PrevDecl, &D);
16099
16100 if (NewFD->isInvalidDecl())
16101 Record->setInvalidDecl();
16102
16103 if (D.getDeclSpec().isModulePrivateSpecified())
16104 NewFD->setModulePrivate();
16105
16106 if (NewFD->isInvalidDecl() && PrevDecl) {
16107 // Don't introduce NewFD into scope; there's already something
16108 // with the same name in the same scope.
16109 } else if (II) {
16110 PushOnScopeChains(NewFD, S);
16111 } else
16112 Record->addDecl(NewFD);
16113
16114 return NewFD;
16115 }
16116
16117 /// Build a new FieldDecl and check its well-formedness.
16118 ///
16119 /// This routine builds a new FieldDecl given the fields name, type,
16120 /// record, etc. \p PrevDecl should refer to any previous declaration
16121 /// with the same name and in the same scope as the field to be
16122 /// created.
16123 ///
16124 /// \returns a new FieldDecl.
16125 ///
16126 /// \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)16127 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16128 TypeSourceInfo *TInfo,
16129 RecordDecl *Record, SourceLocation Loc,
16130 bool Mutable, Expr *BitWidth,
16131 InClassInitStyle InitStyle,
16132 SourceLocation TSSL,
16133 AccessSpecifier AS, NamedDecl *PrevDecl,
16134 Declarator *D) {
16135 IdentifierInfo *II = Name.getAsIdentifierInfo();
16136 bool InvalidDecl = false;
16137 if (D) InvalidDecl = D->isInvalidType();
16138
16139 // If we receive a broken type, recover by assuming 'int' and
16140 // marking this declaration as invalid.
16141 if (T.isNull()) {
16142 InvalidDecl = true;
16143 T = Context.IntTy;
16144 }
16145
16146 QualType EltTy = Context.getBaseElementType(T);
16147 if (!EltTy->isDependentType()) {
16148 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
16149 // Fields of incomplete type force their record to be invalid.
16150 Record->setInvalidDecl();
16151 InvalidDecl = true;
16152 } else {
16153 NamedDecl *Def;
16154 EltTy->isIncompleteType(&Def);
16155 if (Def && Def->isInvalidDecl()) {
16156 Record->setInvalidDecl();
16157 InvalidDecl = true;
16158 }
16159 }
16160 }
16161
16162 // TR 18037 does not allow fields to be declared with address space
16163 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16164 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16165 Diag(Loc, diag::err_field_with_address_space);
16166 Record->setInvalidDecl();
16167 InvalidDecl = true;
16168 }
16169
16170 if (LangOpts.OpenCL) {
16171 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16172 // used as structure or union field: image, sampler, event or block types.
16173 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16174 T->isBlockPointerType()) {
16175 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16176 Record->setInvalidDecl();
16177 InvalidDecl = true;
16178 }
16179 // OpenCL v1.2 s6.9.c: bitfields are not supported.
16180 if (BitWidth) {
16181 Diag(Loc, diag::err_opencl_bitfields);
16182 InvalidDecl = true;
16183 }
16184 }
16185
16186 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16187 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16188 T.hasQualifiers()) {
16189 InvalidDecl = true;
16190 Diag(Loc, diag::err_anon_bitfield_qualifiers);
16191 }
16192
16193 // C99 6.7.2.1p8: A member of a structure or union may have any type other
16194 // than a variably modified type.
16195 if (!InvalidDecl && T->isVariablyModifiedType()) {
16196 bool SizeIsNegative;
16197 llvm::APSInt Oversized;
16198
16199 TypeSourceInfo *FixedTInfo =
16200 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16201 SizeIsNegative,
16202 Oversized);
16203 if (FixedTInfo) {
16204 Diag(Loc, diag::warn_illegal_constant_array_size);
16205 TInfo = FixedTInfo;
16206 T = FixedTInfo->getType();
16207 } else {
16208 if (SizeIsNegative)
16209 Diag(Loc, diag::err_typecheck_negative_array_size);
16210 else if (Oversized.getBoolValue())
16211 Diag(Loc, diag::err_array_too_large)
16212 << Oversized.toString(10);
16213 else
16214 Diag(Loc, diag::err_typecheck_field_variable_size);
16215 InvalidDecl = true;
16216 }
16217 }
16218
16219 // Fields can not have abstract class types
16220 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16221 diag::err_abstract_type_in_decl,
16222 AbstractFieldType))
16223 InvalidDecl = true;
16224
16225 bool ZeroWidth = false;
16226 if (InvalidDecl)
16227 BitWidth = nullptr;
16228 // If this is declared as a bit-field, check the bit-field.
16229 if (BitWidth) {
16230 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16231 &ZeroWidth).get();
16232 if (!BitWidth) {
16233 InvalidDecl = true;
16234 BitWidth = nullptr;
16235 ZeroWidth = false;
16236 }
16237 }
16238
16239 // Check that 'mutable' is consistent with the type of the declaration.
16240 if (!InvalidDecl && Mutable) {
16241 unsigned DiagID = 0;
16242 if (T->isReferenceType())
16243 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16244 : diag::err_mutable_reference;
16245 else if (T.isConstQualified())
16246 DiagID = diag::err_mutable_const;
16247
16248 if (DiagID) {
16249 SourceLocation ErrLoc = Loc;
16250 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16251 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16252 Diag(ErrLoc, DiagID);
16253 if (DiagID != diag::ext_mutable_reference) {
16254 Mutable = false;
16255 InvalidDecl = true;
16256 }
16257 }
16258 }
16259
16260 // C++11 [class.union]p8 (DR1460):
16261 // At most one variant member of a union may have a
16262 // brace-or-equal-initializer.
16263 if (InitStyle != ICIS_NoInit)
16264 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16265
16266 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16267 BitWidth, Mutable, InitStyle);
16268 if (InvalidDecl)
16269 NewFD->setInvalidDecl();
16270
16271 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16272 Diag(Loc, diag::err_duplicate_member) << II;
16273 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16274 NewFD->setInvalidDecl();
16275 }
16276
16277 if (!InvalidDecl && getLangOpts().CPlusPlus) {
16278 if (Record->isUnion()) {
16279 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16280 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16281 if (RDecl->getDefinition()) {
16282 // C++ [class.union]p1: An object of a class with a non-trivial
16283 // constructor, a non-trivial copy constructor, a non-trivial
16284 // destructor, or a non-trivial copy assignment operator
16285 // cannot be a member of a union, nor can an array of such
16286 // objects.
16287 if (CheckNontrivialField(NewFD))
16288 NewFD->setInvalidDecl();
16289 }
16290 }
16291
16292 // C++ [class.union]p1: If a union contains a member of reference type,
16293 // the program is ill-formed, except when compiling with MSVC extensions
16294 // enabled.
16295 if (EltTy->isReferenceType()) {
16296 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16297 diag::ext_union_member_of_reference_type :
16298 diag::err_union_member_of_reference_type)
16299 << NewFD->getDeclName() << EltTy;
16300 if (!getLangOpts().MicrosoftExt)
16301 NewFD->setInvalidDecl();
16302 }
16303 }
16304 }
16305
16306 // FIXME: We need to pass in the attributes given an AST
16307 // representation, not a parser representation.
16308 if (D) {
16309 // FIXME: The current scope is almost... but not entirely... correct here.
16310 ProcessDeclAttributes(getCurScope(), NewFD, *D);
16311
16312 if (NewFD->hasAttrs())
16313 CheckAlignasUnderalignment(NewFD);
16314 }
16315
16316 // In auto-retain/release, infer strong retension for fields of
16317 // retainable type.
16318 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16319 NewFD->setInvalidDecl();
16320
16321 if (T.isObjCGCWeak())
16322 Diag(Loc, diag::warn_attribute_weak_on_field);
16323
16324 NewFD->setAccess(AS);
16325 return NewFD;
16326 }
16327
CheckNontrivialField(FieldDecl * FD)16328 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16329 assert(FD);
16330 assert(getLangOpts().CPlusPlus && "valid check only for C++");
16331
16332 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16333 return false;
16334
16335 QualType EltTy = Context.getBaseElementType(FD->getType());
16336 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16337 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16338 if (RDecl->getDefinition()) {
16339 // We check for copy constructors before constructors
16340 // because otherwise we'll never get complaints about
16341 // copy constructors.
16342
16343 CXXSpecialMember member = CXXInvalid;
16344 // We're required to check for any non-trivial constructors. Since the
16345 // implicit default constructor is suppressed if there are any
16346 // user-declared constructors, we just need to check that there is a
16347 // trivial default constructor and a trivial copy constructor. (We don't
16348 // worry about move constructors here, since this is a C++98 check.)
16349 if (RDecl->hasNonTrivialCopyConstructor())
16350 member = CXXCopyConstructor;
16351 else if (!RDecl->hasTrivialDefaultConstructor())
16352 member = CXXDefaultConstructor;
16353 else if (RDecl->hasNonTrivialCopyAssignment())
16354 member = CXXCopyAssignment;
16355 else if (RDecl->hasNonTrivialDestructor())
16356 member = CXXDestructor;
16357
16358 if (member != CXXInvalid) {
16359 if (!getLangOpts().CPlusPlus11 &&
16360 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16361 // Objective-C++ ARC: it is an error to have a non-trivial field of
16362 // a union. However, system headers in Objective-C programs
16363 // occasionally have Objective-C lifetime objects within unions,
16364 // and rather than cause the program to fail, we make those
16365 // members unavailable.
16366 SourceLocation Loc = FD->getLocation();
16367 if (getSourceManager().isInSystemHeader(Loc)) {
16368 if (!FD->hasAttr<UnavailableAttr>())
16369 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16370 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16371 return false;
16372 }
16373 }
16374
16375 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16376 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16377 diag::err_illegal_union_or_anon_struct_member)
16378 << FD->getParent()->isUnion() << FD->getDeclName() << member;
16379 DiagnoseNontrivial(RDecl, member);
16380 return !getLangOpts().CPlusPlus11;
16381 }
16382 }
16383 }
16384
16385 return false;
16386 }
16387
16388 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16389 /// AST enum value.
16390 static ObjCIvarDecl::AccessControl
TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility)16391 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16392 switch (ivarVisibility) {
16393 default: llvm_unreachable("Unknown visitibility kind");
16394 case tok::objc_private: return ObjCIvarDecl::Private;
16395 case tok::objc_public: return ObjCIvarDecl::Public;
16396 case tok::objc_protected: return ObjCIvarDecl::Protected;
16397 case tok::objc_package: return ObjCIvarDecl::Package;
16398 }
16399 }
16400
16401 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16402 /// in order to create an IvarDecl object for it.
ActOnIvar(Scope * S,SourceLocation DeclStart,Declarator & D,Expr * BitfieldWidth,tok::ObjCKeywordKind Visibility)16403 Decl *Sema::ActOnIvar(Scope *S,
16404 SourceLocation DeclStart,
16405 Declarator &D, Expr *BitfieldWidth,
16406 tok::ObjCKeywordKind Visibility) {
16407
16408 IdentifierInfo *II = D.getIdentifier();
16409 Expr *BitWidth = (Expr*)BitfieldWidth;
16410 SourceLocation Loc = DeclStart;
16411 if (II) Loc = D.getIdentifierLoc();
16412
16413 // FIXME: Unnamed fields can be handled in various different ways, for
16414 // example, unnamed unions inject all members into the struct namespace!
16415
16416 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16417 QualType T = TInfo->getType();
16418
16419 if (BitWidth) {
16420 // 6.7.2.1p3, 6.7.2.1p4
16421 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16422 if (!BitWidth)
16423 D.setInvalidType();
16424 } else {
16425 // Not a bitfield.
16426
16427 // validate II.
16428
16429 }
16430 if (T->isReferenceType()) {
16431 Diag(Loc, diag::err_ivar_reference_type);
16432 D.setInvalidType();
16433 }
16434 // C99 6.7.2.1p8: A member of a structure or union may have any type other
16435 // than a variably modified type.
16436 else if (T->isVariablyModifiedType()) {
16437 Diag(Loc, diag::err_typecheck_ivar_variable_size);
16438 D.setInvalidType();
16439 }
16440
16441 // Get the visibility (access control) for this ivar.
16442 ObjCIvarDecl::AccessControl ac =
16443 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16444 : ObjCIvarDecl::None;
16445 // Must set ivar's DeclContext to its enclosing interface.
16446 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16447 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16448 return nullptr;
16449 ObjCContainerDecl *EnclosingContext;
16450 if (ObjCImplementationDecl *IMPDecl =
16451 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16452 if (LangOpts.ObjCRuntime.isFragile()) {
16453 // Case of ivar declared in an implementation. Context is that of its class.
16454 EnclosingContext = IMPDecl->getClassInterface();
16455 assert(EnclosingContext && "Implementation has no class interface!");
16456 }
16457 else
16458 EnclosingContext = EnclosingDecl;
16459 } else {
16460 if (ObjCCategoryDecl *CDecl =
16461 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16462 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16463 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16464 return nullptr;
16465 }
16466 }
16467 EnclosingContext = EnclosingDecl;
16468 }
16469
16470 // Construct the decl.
16471 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16472 DeclStart, Loc, II, T,
16473 TInfo, ac, (Expr *)BitfieldWidth);
16474
16475 if (II) {
16476 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16477 ForVisibleRedeclaration);
16478 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16479 && !isa<TagDecl>(PrevDecl)) {
16480 Diag(Loc, diag::err_duplicate_member) << II;
16481 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16482 NewID->setInvalidDecl();
16483 }
16484 }
16485
16486 // Process attributes attached to the ivar.
16487 ProcessDeclAttributes(S, NewID, D);
16488
16489 if (D.isInvalidType())
16490 NewID->setInvalidDecl();
16491
16492 // In ARC, infer 'retaining' for ivars of retainable type.
16493 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16494 NewID->setInvalidDecl();
16495
16496 if (D.getDeclSpec().isModulePrivateSpecified())
16497 NewID->setModulePrivate();
16498
16499 if (II) {
16500 // FIXME: When interfaces are DeclContexts, we'll need to add
16501 // these to the interface.
16502 S->AddDecl(NewID);
16503 IdResolver.AddDecl(NewID);
16504 }
16505
16506 if (LangOpts.ObjCRuntime.isNonFragile() &&
16507 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16508 Diag(Loc, diag::warn_ivars_in_interface);
16509
16510 return NewID;
16511 }
16512
16513 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16514 /// class and class extensions. For every class \@interface and class
16515 /// extension \@interface, if the last ivar is a bitfield of any type,
16516 /// then add an implicit `char :0` ivar to the end of that interface.
ActOnLastBitfield(SourceLocation DeclLoc,SmallVectorImpl<Decl * > & AllIvarDecls)16517 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16518 SmallVectorImpl<Decl *> &AllIvarDecls) {
16519 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16520 return;
16521
16522 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16523 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16524
16525 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
16526 return;
16527 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
16528 if (!ID) {
16529 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
16530 if (!CD->IsClassExtension())
16531 return;
16532 }
16533 // No need to add this to end of @implementation.
16534 else
16535 return;
16536 }
16537 // All conditions are met. Add a new bitfield to the tail end of ivars.
16538 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
16539 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
16540
16541 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
16542 DeclLoc, DeclLoc, nullptr,
16543 Context.CharTy,
16544 Context.getTrivialTypeSourceInfo(Context.CharTy,
16545 DeclLoc),
16546 ObjCIvarDecl::Private, BW,
16547 true);
16548 AllIvarDecls.push_back(Ivar);
16549 }
16550
ActOnFields(Scope * S,SourceLocation RecLoc,Decl * EnclosingDecl,ArrayRef<Decl * > Fields,SourceLocation LBrac,SourceLocation RBrac,const ParsedAttributesView & Attrs)16551 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
16552 ArrayRef<Decl *> Fields, SourceLocation LBrac,
16553 SourceLocation RBrac,
16554 const ParsedAttributesView &Attrs) {
16555 assert(EnclosingDecl && "missing record or interface decl");
16556
16557 // If this is an Objective-C @implementation or category and we have
16558 // new fields here we should reset the layout of the interface since
16559 // it will now change.
16560 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
16561 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
16562 switch (DC->getKind()) {
16563 default: break;
16564 case Decl::ObjCCategory:
16565 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
16566 break;
16567 case Decl::ObjCImplementation:
16568 Context.
16569 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
16570 break;
16571 }
16572 }
16573
16574 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
16575 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
16576
16577 // Start counting up the number of named members; make sure to include
16578 // members of anonymous structs and unions in the total.
16579 unsigned NumNamedMembers = 0;
16580 if (Record) {
16581 for (const auto *I : Record->decls()) {
16582 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
16583 if (IFD->getDeclName())
16584 ++NumNamedMembers;
16585 }
16586 }
16587
16588 // Verify that all the fields are okay.
16589 SmallVector<FieldDecl*, 32> RecFields;
16590
16591 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
16592 i != end; ++i) {
16593 FieldDecl *FD = cast<FieldDecl>(*i);
16594
16595 // Get the type for the field.
16596 const Type *FDTy = FD->getType().getTypePtr();
16597
16598 if (!FD->isAnonymousStructOrUnion()) {
16599 // Remember all fields written by the user.
16600 RecFields.push_back(FD);
16601 }
16602
16603 // If the field is already invalid for some reason, don't emit more
16604 // diagnostics about it.
16605 if (FD->isInvalidDecl()) {
16606 EnclosingDecl->setInvalidDecl();
16607 continue;
16608 }
16609
16610 // C99 6.7.2.1p2:
16611 // A structure or union shall not contain a member with
16612 // incomplete or function type (hence, a structure shall not
16613 // contain an instance of itself, but may contain a pointer to
16614 // an instance of itself), except that the last member of a
16615 // structure with more than one named member may have incomplete
16616 // array type; such a structure (and any union containing,
16617 // possibly recursively, a member that is such a structure)
16618 // shall not be a member of a structure or an element of an
16619 // array.
16620 bool IsLastField = (i + 1 == Fields.end());
16621 if (FDTy->isFunctionType()) {
16622 // Field declared as a function.
16623 Diag(FD->getLocation(), diag::err_field_declared_as_function)
16624 << FD->getDeclName();
16625 FD->setInvalidDecl();
16626 EnclosingDecl->setInvalidDecl();
16627 continue;
16628 } else if (FDTy->isIncompleteArrayType() &&
16629 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
16630 if (Record) {
16631 // Flexible array member.
16632 // Microsoft and g++ is more permissive regarding flexible array.
16633 // It will accept flexible array in union and also
16634 // as the sole element of a struct/class.
16635 unsigned DiagID = 0;
16636 if (!Record->isUnion() && !IsLastField) {
16637 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
16638 << FD->getDeclName() << FD->getType() << Record->getTagKind();
16639 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
16640 FD->setInvalidDecl();
16641 EnclosingDecl->setInvalidDecl();
16642 continue;
16643 } else if (Record->isUnion())
16644 DiagID = getLangOpts().MicrosoftExt
16645 ? diag::ext_flexible_array_union_ms
16646 : getLangOpts().CPlusPlus
16647 ? diag::ext_flexible_array_union_gnu
16648 : diag::err_flexible_array_union;
16649 else if (NumNamedMembers < 1)
16650 DiagID = getLangOpts().MicrosoftExt
16651 ? diag::ext_flexible_array_empty_aggregate_ms
16652 : getLangOpts().CPlusPlus
16653 ? diag::ext_flexible_array_empty_aggregate_gnu
16654 : diag::err_flexible_array_empty_aggregate;
16655
16656 if (DiagID)
16657 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
16658 << Record->getTagKind();
16659 // While the layout of types that contain virtual bases is not specified
16660 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
16661 // virtual bases after the derived members. This would make a flexible
16662 // array member declared at the end of an object not adjacent to the end
16663 // of the type.
16664 if (CXXRecord && CXXRecord->getNumVBases() != 0)
16665 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
16666 << FD->getDeclName() << Record->getTagKind();
16667 if (!getLangOpts().C99)
16668 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
16669 << FD->getDeclName() << Record->getTagKind();
16670
16671 // If the element type has a non-trivial destructor, we would not
16672 // implicitly destroy the elements, so disallow it for now.
16673 //
16674 // FIXME: GCC allows this. We should probably either implicitly delete
16675 // the destructor of the containing class, or just allow this.
16676 QualType BaseElem = Context.getBaseElementType(FD->getType());
16677 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
16678 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
16679 << FD->getDeclName() << FD->getType();
16680 FD->setInvalidDecl();
16681 EnclosingDecl->setInvalidDecl();
16682 continue;
16683 }
16684 // Okay, we have a legal flexible array member at the end of the struct.
16685 Record->setHasFlexibleArrayMember(true);
16686 } else {
16687 // In ObjCContainerDecl ivars with incomplete array type are accepted,
16688 // unless they are followed by another ivar. That check is done
16689 // elsewhere, after synthesized ivars are known.
16690 }
16691 } else if (!FDTy->isDependentType() &&
16692 RequireCompleteType(FD->getLocation(), FD->getType(),
16693 diag::err_field_incomplete)) {
16694 // Incomplete type
16695 FD->setInvalidDecl();
16696 EnclosingDecl->setInvalidDecl();
16697 continue;
16698 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
16699 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
16700 // A type which contains a flexible array member is considered to be a
16701 // flexible array member.
16702 Record->setHasFlexibleArrayMember(true);
16703 if (!Record->isUnion()) {
16704 // If this is a struct/class and this is not the last element, reject
16705 // it. Note that GCC supports variable sized arrays in the middle of
16706 // structures.
16707 if (!IsLastField)
16708 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
16709 << FD->getDeclName() << FD->getType();
16710 else {
16711 // We support flexible arrays at the end of structs in
16712 // other structs as an extension.
16713 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
16714 << FD->getDeclName();
16715 }
16716 }
16717 }
16718 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
16719 RequireNonAbstractType(FD->getLocation(), FD->getType(),
16720 diag::err_abstract_type_in_decl,
16721 AbstractIvarType)) {
16722 // Ivars can not have abstract class types
16723 FD->setInvalidDecl();
16724 }
16725 if (Record && FDTTy->getDecl()->hasObjectMember())
16726 Record->setHasObjectMember(true);
16727 if (Record && FDTTy->getDecl()->hasVolatileMember())
16728 Record->setHasVolatileMember(true);
16729 } else if (FDTy->isObjCObjectType()) {
16730 /// A field cannot be an Objective-c object
16731 Diag(FD->getLocation(), diag::err_statically_allocated_object)
16732 << FixItHint::CreateInsertion(FD->getLocation(), "*");
16733 QualType T = Context.getObjCObjectPointerType(FD->getType());
16734 FD->setType(T);
16735 } else if (Record && Record->isUnion() &&
16736 FD->getType().hasNonTrivialObjCLifetime() &&
16737 getSourceManager().isInSystemHeader(FD->getLocation()) &&
16738 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
16739 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
16740 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
16741 // For backward compatibility, fields of C unions declared in system
16742 // headers that have non-trivial ObjC ownership qualifications are marked
16743 // as unavailable unless the qualifier is explicit and __strong. This can
16744 // break ABI compatibility between programs compiled with ARC and MRR, but
16745 // is a better option than rejecting programs using those unions under
16746 // ARC.
16747 FD->addAttr(UnavailableAttr::CreateImplicit(
16748 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
16749 FD->getLocation()));
16750 } else if (getLangOpts().ObjC &&
16751 getLangOpts().getGC() != LangOptions::NonGC &&
16752 Record && !Record->hasObjectMember()) {
16753 if (FD->getType()->isObjCObjectPointerType() ||
16754 FD->getType().isObjCGCStrong())
16755 Record->setHasObjectMember(true);
16756 else if (Context.getAsArrayType(FD->getType())) {
16757 QualType BaseType = Context.getBaseElementType(FD->getType());
16758 if (BaseType->isRecordType() &&
16759 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
16760 Record->setHasObjectMember(true);
16761 else if (BaseType->isObjCObjectPointerType() ||
16762 BaseType.isObjCGCStrong())
16763 Record->setHasObjectMember(true);
16764 }
16765 }
16766
16767 if (Record && !getLangOpts().CPlusPlus &&
16768 !shouldIgnoreForRecordTriviality(FD)) {
16769 QualType FT = FD->getType();
16770 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
16771 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
16772 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
16773 Record->isUnion())
16774 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
16775 }
16776 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
16777 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
16778 Record->setNonTrivialToPrimitiveCopy(true);
16779 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
16780 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
16781 }
16782 if (FT.isDestructedType()) {
16783 Record->setNonTrivialToPrimitiveDestroy(true);
16784 Record->setParamDestroyedInCallee(true);
16785 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
16786 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
16787 }
16788
16789 if (const auto *RT = FT->getAs<RecordType>()) {
16790 if (RT->getDecl()->getArgPassingRestrictions() ==
16791 RecordDecl::APK_CanNeverPassInRegs)
16792 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16793 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
16794 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16795 }
16796
16797 if (Record && FD->getType().isVolatileQualified())
16798 Record->setHasVolatileMember(true);
16799 // Keep track of the number of named members.
16800 if (FD->getIdentifier())
16801 ++NumNamedMembers;
16802 }
16803
16804 // Okay, we successfully defined 'Record'.
16805 if (Record) {
16806 bool Completed = false;
16807 if (CXXRecord) {
16808 if (!CXXRecord->isInvalidDecl()) {
16809 // Set access bits correctly on the directly-declared conversions.
16810 for (CXXRecordDecl::conversion_iterator
16811 I = CXXRecord->conversion_begin(),
16812 E = CXXRecord->conversion_end(); I != E; ++I)
16813 I.setAccess((*I)->getAccess());
16814 }
16815
16816 if (!CXXRecord->isDependentType()) {
16817 // Add any implicitly-declared members to this class.
16818 AddImplicitlyDeclaredMembersToClass(CXXRecord);
16819
16820 if (!CXXRecord->isInvalidDecl()) {
16821 // If we have virtual base classes, we may end up finding multiple
16822 // final overriders for a given virtual function. Check for this
16823 // problem now.
16824 if (CXXRecord->getNumVBases()) {
16825 CXXFinalOverriderMap FinalOverriders;
16826 CXXRecord->getFinalOverriders(FinalOverriders);
16827
16828 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16829 MEnd = FinalOverriders.end();
16830 M != MEnd; ++M) {
16831 for (OverridingMethods::iterator SO = M->second.begin(),
16832 SOEnd = M->second.end();
16833 SO != SOEnd; ++SO) {
16834 assert(SO->second.size() > 0 &&
16835 "Virtual function without overriding functions?");
16836 if (SO->second.size() == 1)
16837 continue;
16838
16839 // C++ [class.virtual]p2:
16840 // In a derived class, if a virtual member function of a base
16841 // class subobject has more than one final overrider the
16842 // program is ill-formed.
16843 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16844 << (const NamedDecl *)M->first << Record;
16845 Diag(M->first->getLocation(),
16846 diag::note_overridden_virtual_function);
16847 for (OverridingMethods::overriding_iterator
16848 OM = SO->second.begin(),
16849 OMEnd = SO->second.end();
16850 OM != OMEnd; ++OM)
16851 Diag(OM->Method->getLocation(), diag::note_final_overrider)
16852 << (const NamedDecl *)M->first << OM->Method->getParent();
16853
16854 Record->setInvalidDecl();
16855 }
16856 }
16857 CXXRecord->completeDefinition(&FinalOverriders);
16858 Completed = true;
16859 }
16860 }
16861 }
16862 }
16863
16864 if (!Completed)
16865 Record->completeDefinition();
16866
16867 // Handle attributes before checking the layout.
16868 ProcessDeclAttributeList(S, Record, Attrs);
16869
16870 // We may have deferred checking for a deleted destructor. Check now.
16871 if (CXXRecord) {
16872 auto *Dtor = CXXRecord->getDestructor();
16873 if (Dtor && Dtor->isImplicit() &&
16874 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16875 CXXRecord->setImplicitDestructorIsDeleted();
16876 SetDeclDeleted(Dtor, CXXRecord->getLocation());
16877 }
16878 }
16879
16880 if (Record->hasAttrs()) {
16881 CheckAlignasUnderalignment(Record);
16882
16883 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16884 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16885 IA->getRange(), IA->getBestCase(),
16886 IA->getInheritanceModel());
16887 }
16888
16889 // Check if the structure/union declaration is a type that can have zero
16890 // size in C. For C this is a language extension, for C++ it may cause
16891 // compatibility problems.
16892 bool CheckForZeroSize;
16893 if (!getLangOpts().CPlusPlus) {
16894 CheckForZeroSize = true;
16895 } else {
16896 // For C++ filter out types that cannot be referenced in C code.
16897 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16898 CheckForZeroSize =
16899 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16900 !CXXRecord->isDependentType() &&
16901 CXXRecord->isCLike();
16902 }
16903 if (CheckForZeroSize) {
16904 bool ZeroSize = true;
16905 bool IsEmpty = true;
16906 unsigned NonBitFields = 0;
16907 for (RecordDecl::field_iterator I = Record->field_begin(),
16908 E = Record->field_end();
16909 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16910 IsEmpty = false;
16911 if (I->isUnnamedBitfield()) {
16912 if (!I->isZeroLengthBitField(Context))
16913 ZeroSize = false;
16914 } else {
16915 ++NonBitFields;
16916 QualType FieldType = I->getType();
16917 if (FieldType->isIncompleteType() ||
16918 !Context.getTypeSizeInChars(FieldType).isZero())
16919 ZeroSize = false;
16920 }
16921 }
16922
16923 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16924 // allowed in C++, but warn if its declaration is inside
16925 // extern "C" block.
16926 if (ZeroSize) {
16927 Diag(RecLoc, getLangOpts().CPlusPlus ?
16928 diag::warn_zero_size_struct_union_in_extern_c :
16929 diag::warn_zero_size_struct_union_compat)
16930 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16931 }
16932
16933 // Structs without named members are extension in C (C99 6.7.2.1p7),
16934 // but are accepted by GCC.
16935 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16936 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16937 diag::ext_no_named_members_in_struct_union)
16938 << Record->isUnion();
16939 }
16940 }
16941 } else {
16942 ObjCIvarDecl **ClsFields =
16943 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16944 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16945 ID->setEndOfDefinitionLoc(RBrac);
16946 // Add ivar's to class's DeclContext.
16947 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16948 ClsFields[i]->setLexicalDeclContext(ID);
16949 ID->addDecl(ClsFields[i]);
16950 }
16951 // Must enforce the rule that ivars in the base classes may not be
16952 // duplicates.
16953 if (ID->getSuperClass())
16954 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16955 } else if (ObjCImplementationDecl *IMPDecl =
16956 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16957 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16958 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16959 // Ivar declared in @implementation never belongs to the implementation.
16960 // Only it is in implementation's lexical context.
16961 ClsFields[I]->setLexicalDeclContext(IMPDecl);
16962 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16963 IMPDecl->setIvarLBraceLoc(LBrac);
16964 IMPDecl->setIvarRBraceLoc(RBrac);
16965 } else if (ObjCCategoryDecl *CDecl =
16966 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16967 // case of ivars in class extension; all other cases have been
16968 // reported as errors elsewhere.
16969 // FIXME. Class extension does not have a LocEnd field.
16970 // CDecl->setLocEnd(RBrac);
16971 // Add ivar's to class extension's DeclContext.
16972 // Diagnose redeclaration of private ivars.
16973 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16974 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16975 if (IDecl) {
16976 if (const ObjCIvarDecl *ClsIvar =
16977 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16978 Diag(ClsFields[i]->getLocation(),
16979 diag::err_duplicate_ivar_declaration);
16980 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16981 continue;
16982 }
16983 for (const auto *Ext : IDecl->known_extensions()) {
16984 if (const ObjCIvarDecl *ClsExtIvar
16985 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16986 Diag(ClsFields[i]->getLocation(),
16987 diag::err_duplicate_ivar_declaration);
16988 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16989 continue;
16990 }
16991 }
16992 }
16993 ClsFields[i]->setLexicalDeclContext(CDecl);
16994 CDecl->addDecl(ClsFields[i]);
16995 }
16996 CDecl->setIvarLBraceLoc(LBrac);
16997 CDecl->setIvarRBraceLoc(RBrac);
16998 }
16999 }
17000 }
17001
17002 /// Determine whether the given integral value is representable within
17003 /// the given type T.
isRepresentableIntegerValue(ASTContext & Context,llvm::APSInt & Value,QualType T)17004 static bool isRepresentableIntegerValue(ASTContext &Context,
17005 llvm::APSInt &Value,
17006 QualType T) {
17007 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17008 "Integral type required!");
17009 unsigned BitWidth = Context.getIntWidth(T);
17010
17011 if (Value.isUnsigned() || Value.isNonNegative()) {
17012 if (T->isSignedIntegerOrEnumerationType())
17013 --BitWidth;
17014 return Value.getActiveBits() <= BitWidth;
17015 }
17016 return Value.getMinSignedBits() <= BitWidth;
17017 }
17018
17019 // Given an integral type, return the next larger integral type
17020 // (or a NULL type of no such type exists).
getNextLargerIntegralType(ASTContext & Context,QualType T)17021 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17022 // FIXME: Int128/UInt128 support, which also needs to be introduced into
17023 // enum checking below.
17024 assert((T->isIntegralType(Context) ||
17025 T->isEnumeralType()) && "Integral type required!");
17026 const unsigned NumTypes = 4;
17027 QualType SignedIntegralTypes[NumTypes] = {
17028 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17029 };
17030 QualType UnsignedIntegralTypes[NumTypes] = {
17031 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17032 Context.UnsignedLongLongTy
17033 };
17034
17035 unsigned BitWidth = Context.getTypeSize(T);
17036 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17037 : UnsignedIntegralTypes;
17038 for (unsigned I = 0; I != NumTypes; ++I)
17039 if (Context.getTypeSize(Types[I]) > BitWidth)
17040 return Types[I];
17041
17042 return QualType();
17043 }
17044
CheckEnumConstant(EnumDecl * Enum,EnumConstantDecl * LastEnumConst,SourceLocation IdLoc,IdentifierInfo * Id,Expr * Val)17045 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17046 EnumConstantDecl *LastEnumConst,
17047 SourceLocation IdLoc,
17048 IdentifierInfo *Id,
17049 Expr *Val) {
17050 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17051 llvm::APSInt EnumVal(IntWidth);
17052 QualType EltTy;
17053
17054 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17055 Val = nullptr;
17056
17057 if (Val)
17058 Val = DefaultLvalueConversion(Val).get();
17059
17060 if (Val) {
17061 if (Enum->isDependentType() || Val->isTypeDependent())
17062 EltTy = Context.DependentTy;
17063 else {
17064 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17065 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17066 // constant-expression in the enumerator-definition shall be a converted
17067 // constant expression of the underlying type.
17068 EltTy = Enum->getIntegerType();
17069 ExprResult Converted =
17070 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17071 CCEK_Enumerator);
17072 if (Converted.isInvalid())
17073 Val = nullptr;
17074 else
17075 Val = Converted.get();
17076 } else if (!Val->isValueDependent() &&
17077 !(Val = VerifyIntegerConstantExpression(Val,
17078 &EnumVal).get())) {
17079 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17080 } else {
17081 if (Enum->isComplete()) {
17082 EltTy = Enum->getIntegerType();
17083
17084 // In Obj-C and Microsoft mode, require the enumeration value to be
17085 // representable in the underlying type of the enumeration. In C++11,
17086 // we perform a non-narrowing conversion as part of converted constant
17087 // expression checking.
17088 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17089 if (Context.getTargetInfo()
17090 .getTriple()
17091 .isWindowsMSVCEnvironment()) {
17092 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17093 } else {
17094 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17095 }
17096 }
17097
17098 // Cast to the underlying type.
17099 Val = ImpCastExprToType(Val, EltTy,
17100 EltTy->isBooleanType() ? CK_IntegralToBoolean
17101 : CK_IntegralCast)
17102 .get();
17103 } else if (getLangOpts().CPlusPlus) {
17104 // C++11 [dcl.enum]p5:
17105 // If the underlying type is not fixed, the type of each enumerator
17106 // is the type of its initializing value:
17107 // - If an initializer is specified for an enumerator, the
17108 // initializing value has the same type as the expression.
17109 EltTy = Val->getType();
17110 } else {
17111 // C99 6.7.2.2p2:
17112 // The expression that defines the value of an enumeration constant
17113 // shall be an integer constant expression that has a value
17114 // representable as an int.
17115
17116 // Complain if the value is not representable in an int.
17117 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17118 Diag(IdLoc, diag::ext_enum_value_not_int)
17119 << EnumVal.toString(10) << Val->getSourceRange()
17120 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17121 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17122 // Force the type of the expression to 'int'.
17123 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17124 }
17125 EltTy = Val->getType();
17126 }
17127 }
17128 }
17129 }
17130
17131 if (!Val) {
17132 if (Enum->isDependentType())
17133 EltTy = Context.DependentTy;
17134 else if (!LastEnumConst) {
17135 // C++0x [dcl.enum]p5:
17136 // If the underlying type is not fixed, the type of each enumerator
17137 // is the type of its initializing value:
17138 // - If no initializer is specified for the first enumerator, the
17139 // initializing value has an unspecified integral type.
17140 //
17141 // GCC uses 'int' for its unspecified integral type, as does
17142 // C99 6.7.2.2p3.
17143 if (Enum->isFixed()) {
17144 EltTy = Enum->getIntegerType();
17145 }
17146 else {
17147 EltTy = Context.IntTy;
17148 }
17149 } else {
17150 // Assign the last value + 1.
17151 EnumVal = LastEnumConst->getInitVal();
17152 ++EnumVal;
17153 EltTy = LastEnumConst->getType();
17154
17155 // Check for overflow on increment.
17156 if (EnumVal < LastEnumConst->getInitVal()) {
17157 // C++0x [dcl.enum]p5:
17158 // If the underlying type is not fixed, the type of each enumerator
17159 // is the type of its initializing value:
17160 //
17161 // - Otherwise the type of the initializing value is the same as
17162 // the type of the initializing value of the preceding enumerator
17163 // unless the incremented value is not representable in that type,
17164 // in which case the type is an unspecified integral type
17165 // sufficient to contain the incremented value. If no such type
17166 // exists, the program is ill-formed.
17167 QualType T = getNextLargerIntegralType(Context, EltTy);
17168 if (T.isNull() || Enum->isFixed()) {
17169 // There is no integral type larger enough to represent this
17170 // value. Complain, then allow the value to wrap around.
17171 EnumVal = LastEnumConst->getInitVal();
17172 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17173 ++EnumVal;
17174 if (Enum->isFixed())
17175 // When the underlying type is fixed, this is ill-formed.
17176 Diag(IdLoc, diag::err_enumerator_wrapped)
17177 << EnumVal.toString(10)
17178 << EltTy;
17179 else
17180 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17181 << EnumVal.toString(10);
17182 } else {
17183 EltTy = T;
17184 }
17185
17186 // Retrieve the last enumerator's value, extent that type to the
17187 // type that is supposed to be large enough to represent the incremented
17188 // value, then increment.
17189 EnumVal = LastEnumConst->getInitVal();
17190 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17191 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17192 ++EnumVal;
17193
17194 // If we're not in C++, diagnose the overflow of enumerator values,
17195 // which in C99 means that the enumerator value is not representable in
17196 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17197 // permits enumerator values that are representable in some larger
17198 // integral type.
17199 if (!getLangOpts().CPlusPlus && !T.isNull())
17200 Diag(IdLoc, diag::warn_enum_value_overflow);
17201 } else if (!getLangOpts().CPlusPlus &&
17202 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17203 // Enforce C99 6.7.2.2p2 even when we compute the next value.
17204 Diag(IdLoc, diag::ext_enum_value_not_int)
17205 << EnumVal.toString(10) << 1;
17206 }
17207 }
17208 }
17209
17210 if (!EltTy->isDependentType()) {
17211 // Make the enumerator value match the signedness and size of the
17212 // enumerator's type.
17213 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17214 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17215 }
17216
17217 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17218 Val, EnumVal);
17219 }
17220
shouldSkipAnonEnumBody(Scope * S,IdentifierInfo * II,SourceLocation IILoc)17221 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17222 SourceLocation IILoc) {
17223 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17224 !getLangOpts().CPlusPlus)
17225 return SkipBodyInfo();
17226
17227 // We have an anonymous enum definition. Look up the first enumerator to
17228 // determine if we should merge the definition with an existing one and
17229 // skip the body.
17230 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17231 forRedeclarationInCurContext());
17232 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17233 if (!PrevECD)
17234 return SkipBodyInfo();
17235
17236 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17237 NamedDecl *Hidden;
17238 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17239 SkipBodyInfo Skip;
17240 Skip.Previous = Hidden;
17241 return Skip;
17242 }
17243
17244 return SkipBodyInfo();
17245 }
17246
ActOnEnumConstant(Scope * S,Decl * theEnumDecl,Decl * lastEnumConst,SourceLocation IdLoc,IdentifierInfo * Id,const ParsedAttributesView & Attrs,SourceLocation EqualLoc,Expr * Val)17247 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17248 SourceLocation IdLoc, IdentifierInfo *Id,
17249 const ParsedAttributesView &Attrs,
17250 SourceLocation EqualLoc, Expr *Val) {
17251 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17252 EnumConstantDecl *LastEnumConst =
17253 cast_or_null<EnumConstantDecl>(lastEnumConst);
17254
17255 // The scope passed in may not be a decl scope. Zip up the scope tree until
17256 // we find one that is.
17257 S = getNonFieldDeclScope(S);
17258
17259 // Verify that there isn't already something declared with this name in this
17260 // scope.
17261 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17262 LookupName(R, S);
17263 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17264
17265 if (PrevDecl && PrevDecl->isTemplateParameter()) {
17266 // Maybe we will complain about the shadowed template parameter.
17267 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17268 // Just pretend that we didn't see the previous declaration.
17269 PrevDecl = nullptr;
17270 }
17271
17272 // C++ [class.mem]p15:
17273 // If T is the name of a class, then each of the following shall have a name
17274 // different from T:
17275 // - every enumerator of every member of class T that is an unscoped
17276 // enumerated type
17277 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17278 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17279 DeclarationNameInfo(Id, IdLoc));
17280
17281 EnumConstantDecl *New =
17282 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17283 if (!New)
17284 return nullptr;
17285
17286 if (PrevDecl) {
17287 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17288 // Check for other kinds of shadowing not already handled.
17289 CheckShadow(New, PrevDecl, R);
17290 }
17291
17292 // When in C++, we may get a TagDecl with the same name; in this case the
17293 // enum constant will 'hide' the tag.
17294 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17295 "Received TagDecl when not in C++!");
17296 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17297 if (isa<EnumConstantDecl>(PrevDecl))
17298 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17299 else
17300 Diag(IdLoc, diag::err_redefinition) << Id;
17301 notePreviousDefinition(PrevDecl, IdLoc);
17302 return nullptr;
17303 }
17304 }
17305
17306 // Process attributes.
17307 ProcessDeclAttributeList(S, New, Attrs);
17308 AddPragmaAttributes(S, New);
17309
17310 // Register this decl in the current scope stack.
17311 New->setAccess(TheEnumDecl->getAccess());
17312 PushOnScopeChains(New, S);
17313
17314 ActOnDocumentableDecl(New);
17315
17316 return New;
17317 }
17318
17319 // Returns true when the enum initial expression does not trigger the
17320 // duplicate enum warning. A few common cases are exempted as follows:
17321 // Element2 = Element1
17322 // Element2 = Element1 + 1
17323 // Element2 = Element1 - 1
17324 // Where Element2 and Element1 are from the same enum.
ValidDuplicateEnum(EnumConstantDecl * ECD,EnumDecl * Enum)17325 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17326 Expr *InitExpr = ECD->getInitExpr();
17327 if (!InitExpr)
17328 return true;
17329 InitExpr = InitExpr->IgnoreImpCasts();
17330
17331 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17332 if (!BO->isAdditiveOp())
17333 return true;
17334 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17335 if (!IL)
17336 return true;
17337 if (IL->getValue() != 1)
17338 return true;
17339
17340 InitExpr = BO->getLHS();
17341 }
17342
17343 // This checks if the elements are from the same enum.
17344 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17345 if (!DRE)
17346 return true;
17347
17348 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17349 if (!EnumConstant)
17350 return true;
17351
17352 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17353 Enum)
17354 return true;
17355
17356 return false;
17357 }
17358
17359 // Emits a warning when an element is implicitly set a value that
17360 // a previous element has already been set to.
CheckForDuplicateEnumValues(Sema & S,ArrayRef<Decl * > Elements,EnumDecl * Enum,QualType EnumType)17361 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17362 EnumDecl *Enum, QualType EnumType) {
17363 // Avoid anonymous enums
17364 if (!Enum->getIdentifier())
17365 return;
17366
17367 // Only check for small enums.
17368 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17369 return;
17370
17371 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17372 return;
17373
17374 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17375 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17376
17377 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17378 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17379
17380 // Use int64_t as a key to avoid needing special handling for DenseMap keys.
17381 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17382 llvm::APSInt Val = D->getInitVal();
17383 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17384 };
17385
17386 DuplicatesVector DupVector;
17387 ValueToVectorMap EnumMap;
17388
17389 // Populate the EnumMap with all values represented by enum constants without
17390 // an initializer.
17391 for (auto *Element : Elements) {
17392 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17393
17394 // Null EnumConstantDecl means a previous diagnostic has been emitted for
17395 // this constant. Skip this enum since it may be ill-formed.
17396 if (!ECD) {
17397 return;
17398 }
17399
17400 // Constants with initalizers are handled in the next loop.
17401 if (ECD->getInitExpr())
17402 continue;
17403
17404 // Duplicate values are handled in the next loop.
17405 EnumMap.insert({EnumConstantToKey(ECD), ECD});
17406 }
17407
17408 if (EnumMap.size() == 0)
17409 return;
17410
17411 // Create vectors for any values that has duplicates.
17412 for (auto *Element : Elements) {
17413 // The last loop returned if any constant was null.
17414 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17415 if (!ValidDuplicateEnum(ECD, Enum))
17416 continue;
17417
17418 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17419 if (Iter == EnumMap.end())
17420 continue;
17421
17422 DeclOrVector& Entry = Iter->second;
17423 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17424 // Ensure constants are different.
17425 if (D == ECD)
17426 continue;
17427
17428 // Create new vector and push values onto it.
17429 auto Vec = std::make_unique<ECDVector>();
17430 Vec->push_back(D);
17431 Vec->push_back(ECD);
17432
17433 // Update entry to point to the duplicates vector.
17434 Entry = Vec.get();
17435
17436 // Store the vector somewhere we can consult later for quick emission of
17437 // diagnostics.
17438 DupVector.emplace_back(std::move(Vec));
17439 continue;
17440 }
17441
17442 ECDVector *Vec = Entry.get<ECDVector*>();
17443 // Make sure constants are not added more than once.
17444 if (*Vec->begin() == ECD)
17445 continue;
17446
17447 Vec->push_back(ECD);
17448 }
17449
17450 // Emit diagnostics.
17451 for (const auto &Vec : DupVector) {
17452 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17453
17454 // Emit warning for one enum constant.
17455 auto *FirstECD = Vec->front();
17456 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17457 << FirstECD << FirstECD->getInitVal().toString(10)
17458 << FirstECD->getSourceRange();
17459
17460 // Emit one note for each of the remaining enum constants with
17461 // the same value.
17462 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17463 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17464 << ECD << ECD->getInitVal().toString(10)
17465 << ECD->getSourceRange();
17466 }
17467 }
17468
IsValueInFlagEnum(const EnumDecl * ED,const llvm::APInt & Val,bool AllowMask) const17469 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17470 bool AllowMask) const {
17471 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
17472 assert(ED->isCompleteDefinition() && "expected enum definition");
17473
17474 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17475 llvm::APInt &FlagBits = R.first->second;
17476
17477 if (R.second) {
17478 for (auto *E : ED->enumerators()) {
17479 const auto &EVal = E->getInitVal();
17480 // Only single-bit enumerators introduce new flag values.
17481 if (EVal.isPowerOf2())
17482 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17483 }
17484 }
17485
17486 // A value is in a flag enum if either its bits are a subset of the enum's
17487 // flag bits (the first condition) or we are allowing masks and the same is
17488 // true of its complement (the second condition). When masks are allowed, we
17489 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17490 //
17491 // While it's true that any value could be used as a mask, the assumption is
17492 // that a mask will have all of the insignificant bits set. Anything else is
17493 // likely a logic error.
17494 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17495 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17496 }
17497
ActOnEnumBody(SourceLocation EnumLoc,SourceRange BraceRange,Decl * EnumDeclX,ArrayRef<Decl * > Elements,Scope * S,const ParsedAttributesView & Attrs)17498 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17499 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17500 const ParsedAttributesView &Attrs) {
17501 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17502 QualType EnumType = Context.getTypeDeclType(Enum);
17503
17504 ProcessDeclAttributeList(S, Enum, Attrs);
17505
17506 if (Enum->isDependentType()) {
17507 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17508 EnumConstantDecl *ECD =
17509 cast_or_null<EnumConstantDecl>(Elements[i]);
17510 if (!ECD) continue;
17511
17512 ECD->setType(EnumType);
17513 }
17514
17515 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17516 return;
17517 }
17518
17519 // TODO: If the result value doesn't fit in an int, it must be a long or long
17520 // long value. ISO C does not support this, but GCC does as an extension,
17521 // emit a warning.
17522 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17523 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
17524 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
17525
17526 // Verify that all the values are okay, compute the size of the values, and
17527 // reverse the list.
17528 unsigned NumNegativeBits = 0;
17529 unsigned NumPositiveBits = 0;
17530
17531 // Keep track of whether all elements have type int.
17532 bool AllElementsInt = true;
17533
17534 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17535 EnumConstantDecl *ECD =
17536 cast_or_null<EnumConstantDecl>(Elements[i]);
17537 if (!ECD) continue; // Already issued a diagnostic.
17538
17539 const llvm::APSInt &InitVal = ECD->getInitVal();
17540
17541 // Keep track of the size of positive and negative values.
17542 if (InitVal.isUnsigned() || InitVal.isNonNegative())
17543 NumPositiveBits = std::max(NumPositiveBits,
17544 (unsigned)InitVal.getActiveBits());
17545 else
17546 NumNegativeBits = std::max(NumNegativeBits,
17547 (unsigned)InitVal.getMinSignedBits());
17548
17549 // Keep track of whether every enum element has type int (very common).
17550 if (AllElementsInt)
17551 AllElementsInt = ECD->getType() == Context.IntTy;
17552 }
17553
17554 // Figure out the type that should be used for this enum.
17555 QualType BestType;
17556 unsigned BestWidth;
17557
17558 // C++0x N3000 [conv.prom]p3:
17559 // An rvalue of an unscoped enumeration type whose underlying
17560 // type is not fixed can be converted to an rvalue of the first
17561 // of the following types that can represent all the values of
17562 // the enumeration: int, unsigned int, long int, unsigned long
17563 // int, long long int, or unsigned long long int.
17564 // C99 6.4.4.3p2:
17565 // An identifier declared as an enumeration constant has type int.
17566 // The C99 rule is modified by a gcc extension
17567 QualType BestPromotionType;
17568
17569 bool Packed = Enum->hasAttr<PackedAttr>();
17570 // -fshort-enums is the equivalent to specifying the packed attribute on all
17571 // enum definitions.
17572 if (LangOpts.ShortEnums)
17573 Packed = true;
17574
17575 // If the enum already has a type because it is fixed or dictated by the
17576 // target, promote that type instead of analyzing the enumerators.
17577 if (Enum->isComplete()) {
17578 BestType = Enum->getIntegerType();
17579 if (BestType->isPromotableIntegerType())
17580 BestPromotionType = Context.getPromotedIntegerType(BestType);
17581 else
17582 BestPromotionType = BestType;
17583
17584 BestWidth = Context.getIntWidth(BestType);
17585 }
17586 else if (NumNegativeBits) {
17587 // If there is a negative value, figure out the smallest integer type (of
17588 // int/long/longlong) that fits.
17589 // If it's packed, check also if it fits a char or a short.
17590 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
17591 BestType = Context.SignedCharTy;
17592 BestWidth = CharWidth;
17593 } else if (Packed && NumNegativeBits <= ShortWidth &&
17594 NumPositiveBits < ShortWidth) {
17595 BestType = Context.ShortTy;
17596 BestWidth = ShortWidth;
17597 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
17598 BestType = Context.IntTy;
17599 BestWidth = IntWidth;
17600 } else {
17601 BestWidth = Context.getTargetInfo().getLongWidth();
17602
17603 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
17604 BestType = Context.LongTy;
17605 } else {
17606 BestWidth = Context.getTargetInfo().getLongLongWidth();
17607
17608 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
17609 Diag(Enum->getLocation(), diag::ext_enum_too_large);
17610 BestType = Context.LongLongTy;
17611 }
17612 }
17613 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
17614 } else {
17615 // If there is no negative value, figure out the smallest type that fits
17616 // all of the enumerator values.
17617 // If it's packed, check also if it fits a char or a short.
17618 if (Packed && NumPositiveBits <= CharWidth) {
17619 BestType = Context.UnsignedCharTy;
17620 BestPromotionType = Context.IntTy;
17621 BestWidth = CharWidth;
17622 } else if (Packed && NumPositiveBits <= ShortWidth) {
17623 BestType = Context.UnsignedShortTy;
17624 BestPromotionType = Context.IntTy;
17625 BestWidth = ShortWidth;
17626 } else if (NumPositiveBits <= IntWidth) {
17627 BestType = Context.UnsignedIntTy;
17628 BestWidth = IntWidth;
17629 BestPromotionType
17630 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17631 ? Context.UnsignedIntTy : Context.IntTy;
17632 } else if (NumPositiveBits <=
17633 (BestWidth = Context.getTargetInfo().getLongWidth())) {
17634 BestType = Context.UnsignedLongTy;
17635 BestPromotionType
17636 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17637 ? Context.UnsignedLongTy : Context.LongTy;
17638 } else {
17639 BestWidth = Context.getTargetInfo().getLongLongWidth();
17640 assert(NumPositiveBits <= BestWidth &&
17641 "How could an initializer get larger than ULL?");
17642 BestType = Context.UnsignedLongLongTy;
17643 BestPromotionType
17644 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17645 ? Context.UnsignedLongLongTy : Context.LongLongTy;
17646 }
17647 }
17648
17649 // Loop over all of the enumerator constants, changing their types to match
17650 // the type of the enum if needed.
17651 for (auto *D : Elements) {
17652 auto *ECD = cast_or_null<EnumConstantDecl>(D);
17653 if (!ECD) continue; // Already issued a diagnostic.
17654
17655 // Standard C says the enumerators have int type, but we allow, as an
17656 // extension, the enumerators to be larger than int size. If each
17657 // enumerator value fits in an int, type it as an int, otherwise type it the
17658 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
17659 // that X has type 'int', not 'unsigned'.
17660
17661 // Determine whether the value fits into an int.
17662 llvm::APSInt InitVal = ECD->getInitVal();
17663
17664 // If it fits into an integer type, force it. Otherwise force it to match
17665 // the enum decl type.
17666 QualType NewTy;
17667 unsigned NewWidth;
17668 bool NewSign;
17669 if (!getLangOpts().CPlusPlus &&
17670 !Enum->isFixed() &&
17671 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
17672 NewTy = Context.IntTy;
17673 NewWidth = IntWidth;
17674 NewSign = true;
17675 } else if (ECD->getType() == BestType) {
17676 // Already the right type!
17677 if (getLangOpts().CPlusPlus)
17678 // C++ [dcl.enum]p4: Following the closing brace of an
17679 // enum-specifier, each enumerator has the type of its
17680 // enumeration.
17681 ECD->setType(EnumType);
17682 continue;
17683 } else {
17684 NewTy = BestType;
17685 NewWidth = BestWidth;
17686 NewSign = BestType->isSignedIntegerOrEnumerationType();
17687 }
17688
17689 // Adjust the APSInt value.
17690 InitVal = InitVal.extOrTrunc(NewWidth);
17691 InitVal.setIsSigned(NewSign);
17692 ECD->setInitVal(InitVal);
17693
17694 // Adjust the Expr initializer and type.
17695 if (ECD->getInitExpr() &&
17696 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
17697 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
17698 CK_IntegralCast,
17699 ECD->getInitExpr(),
17700 /*base paths*/ nullptr,
17701 VK_RValue));
17702 if (getLangOpts().CPlusPlus)
17703 // C++ [dcl.enum]p4: Following the closing brace of an
17704 // enum-specifier, each enumerator has the type of its
17705 // enumeration.
17706 ECD->setType(EnumType);
17707 else
17708 ECD->setType(NewTy);
17709 }
17710
17711 Enum->completeDefinition(BestType, BestPromotionType,
17712 NumPositiveBits, NumNegativeBits);
17713
17714 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
17715
17716 if (Enum->isClosedFlag()) {
17717 for (Decl *D : Elements) {
17718 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
17719 if (!ECD) continue; // Already issued a diagnostic.
17720
17721 llvm::APSInt InitVal = ECD->getInitVal();
17722 if (InitVal != 0 && !InitVal.isPowerOf2() &&
17723 !IsValueInFlagEnum(Enum, InitVal, true))
17724 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
17725 << ECD << Enum;
17726 }
17727 }
17728
17729 // Now that the enum type is defined, ensure it's not been underaligned.
17730 if (Enum->hasAttrs())
17731 CheckAlignasUnderalignment(Enum);
17732 }
17733
ActOnFileScopeAsmDecl(Expr * expr,SourceLocation StartLoc,SourceLocation EndLoc)17734 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
17735 SourceLocation StartLoc,
17736 SourceLocation EndLoc) {
17737 StringLiteral *AsmString = cast<StringLiteral>(expr);
17738
17739 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
17740 AsmString, StartLoc,
17741 EndLoc);
17742 CurContext->addDecl(New);
17743 return New;
17744 }
17745
ActOnPragmaRedefineExtname(IdentifierInfo * Name,IdentifierInfo * AliasName,SourceLocation PragmaLoc,SourceLocation NameLoc,SourceLocation AliasNameLoc)17746 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17747 IdentifierInfo* AliasName,
17748 SourceLocation PragmaLoc,
17749 SourceLocation NameLoc,
17750 SourceLocation AliasNameLoc) {
17751 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17752 LookupOrdinaryName);
17753 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
17754 AttributeCommonInfo::AS_Pragma);
17755 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
17756 Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
17757
17758 // If a declaration that:
17759 // 1) declares a function or a variable
17760 // 2) has external linkage
17761 // already exists, add a label attribute to it.
17762 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17763 if (isDeclExternC(PrevDecl))
17764 PrevDecl->addAttr(Attr);
17765 else
17766 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17767 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17768 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17769 } else
17770 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17771 }
17772
ActOnPragmaWeakID(IdentifierInfo * Name,SourceLocation PragmaLoc,SourceLocation NameLoc)17773 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17774 SourceLocation PragmaLoc,
17775 SourceLocation NameLoc) {
17776 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17777
17778 if (PrevDecl) {
17779 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
17780 } else {
17781 (void)WeakUndeclaredIdentifiers.insert(
17782 std::pair<IdentifierInfo*,WeakInfo>
17783 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17784 }
17785 }
17786
ActOnPragmaWeakAlias(IdentifierInfo * Name,IdentifierInfo * AliasName,SourceLocation PragmaLoc,SourceLocation NameLoc,SourceLocation AliasNameLoc)17787 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17788 IdentifierInfo* AliasName,
17789 SourceLocation PragmaLoc,
17790 SourceLocation NameLoc,
17791 SourceLocation AliasNameLoc) {
17792 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17793 LookupOrdinaryName);
17794 WeakInfo W = WeakInfo(Name, NameLoc);
17795
17796 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17797 if (!PrevDecl->hasAttr<AliasAttr>())
17798 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17799 DeclApplyPragmaWeak(TUScope, ND, W);
17800 } else {
17801 (void)WeakUndeclaredIdentifiers.insert(
17802 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17803 }
17804 }
17805
getObjCDeclContext() const17806 Decl *Sema::getObjCDeclContext() const {
17807 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17808 }
17809
getEmissionStatus(FunctionDecl * FD)17810 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD) {
17811 // Templates are emitted when they're instantiated.
17812 if (FD->isDependentContext())
17813 return FunctionEmissionStatus::TemplateDiscarded;
17814
17815 FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
17816 if (LangOpts.OpenMPIsDevice) {
17817 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17818 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
17819 if (DevTy.hasValue()) {
17820 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
17821 OMPES = FunctionEmissionStatus::OMPDiscarded;
17822 else if (DeviceKnownEmittedFns.count(FD) > 0)
17823 OMPES = FunctionEmissionStatus::Emitted;
17824 }
17825 } else if (LangOpts.OpenMP) {
17826 // In OpenMP 4.5 all the functions are host functions.
17827 if (LangOpts.OpenMP <= 45) {
17828 OMPES = FunctionEmissionStatus::Emitted;
17829 } else {
17830 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17831 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
17832 // In OpenMP 5.0 or above, DevTy may be changed later by
17833 // #pragma omp declare target to(*) device_type(*). Therefore DevTy
17834 // having no value does not imply host. The emission status will be
17835 // checked again at the end of compilation unit.
17836 if (DevTy.hasValue()) {
17837 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
17838 OMPES = FunctionEmissionStatus::OMPDiscarded;
17839 } else if (DeviceKnownEmittedFns.count(FD) > 0) {
17840 OMPES = FunctionEmissionStatus::Emitted;
17841 }
17842 }
17843 }
17844 }
17845 if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
17846 (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
17847 return OMPES;
17848
17849 if (LangOpts.CUDA) {
17850 // When compiling for device, host functions are never emitted. Similarly,
17851 // when compiling for host, device and global functions are never emitted.
17852 // (Technically, we do emit a host-side stub for global functions, but this
17853 // doesn't count for our purposes here.)
17854 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
17855 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
17856 return FunctionEmissionStatus::CUDADiscarded;
17857 if (!LangOpts.CUDAIsDevice &&
17858 (T == Sema::CFT_Device || T == Sema::CFT_Global))
17859 return FunctionEmissionStatus::CUDADiscarded;
17860
17861 // Check whether this function is externally visible -- if so, it's
17862 // known-emitted.
17863 //
17864 // We have to check the GVA linkage of the function's *definition* -- if we
17865 // only have a declaration, we don't know whether or not the function will
17866 // be emitted, because (say) the definition could include "inline".
17867 FunctionDecl *Def = FD->getDefinition();
17868
17869 if (Def &&
17870 !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
17871 && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
17872 return FunctionEmissionStatus::Emitted;
17873 }
17874
17875 // Otherwise, the function is known-emitted if it's in our set of
17876 // known-emitted functions.
17877 return (DeviceKnownEmittedFns.count(FD) > 0)
17878 ? FunctionEmissionStatus::Emitted
17879 : FunctionEmissionStatus::Unknown;
17880 }
17881
shouldIgnoreInHostDeviceCheck(FunctionDecl * Callee)17882 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
17883 // Host-side references to a __global__ function refer to the stub, so the
17884 // function itself is never emitted and therefore should not be marked.
17885 // If we have host fn calls kernel fn calls host+device, the HD function
17886 // does not get instantiated on the host. We model this by omitting at the
17887 // call to the kernel from the callgraph. This ensures that, when compiling
17888 // for host, only HD functions actually called from the host get marked as
17889 // known-emitted.
17890 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
17891 IdentifyCUDATarget(Callee) == CFT_Global;
17892 }
17893