1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for declarations.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/Initialization.h"
16 #include "clang/Sema/Lookup.h"
17 #include "clang/Sema/CXXFieldCollector.h"
18 #include "clang/Sema/Scope.h"
19 #include "clang/Sema/ScopeInfo.h"
20 #include "TypeLocBuilder.h"
21 #include "clang/AST/ASTConsumer.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/CXXInheritance.h"
24 #include "clang/AST/CommentDiagnostic.h"
25 #include "clang/AST/DeclCXX.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/DeclTemplate.h"
28 #include "clang/AST/EvaluatedExprVisitor.h"
29 #include "clang/AST/ExprCXX.h"
30 #include "clang/AST/StmtCXX.h"
31 #include "clang/AST/CharUnits.h"
32 #include "clang/Sema/DeclSpec.h"
33 #include "clang/Sema/ParsedTemplate.h"
34 #include "clang/Parse/ParseDiagnostic.h"
35 #include "clang/Basic/PartialDiagnostic.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Basic/SourceManager.h"
38 #include "clang/Basic/TargetInfo.h"
39 // FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
40 #include "clang/Lex/Preprocessor.h"
41 #include "clang/Lex/HeaderSearch.h"
42 #include "clang/Lex/ModuleLoader.h"
43 #include "llvm/ADT/SmallString.h"
44 #include "llvm/ADT/Triple.h"
48 using namespace clang;
51 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
53 Decl *Group[2] = { OwnedType, Ptr };
54 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
57 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
62 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
64 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false)
65 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) {
66 WantExpressionKeywords = false;
67 WantCXXNamedCasts = false;
68 WantRemainingKeywords = false;
71 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
72 if (NamedDecl *ND = candidate.getCorrectionDecl())
73 return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
74 (AllowInvalidDecl || !ND->isInvalidDecl());
76 return !WantClassName && candidate.isKeyword();
80 bool AllowInvalidDecl;
86 /// \brief Determine whether the token kind starts a simple-type-specifier.
87 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
89 // FIXME: Take into account the current language when deciding whether a
90 // token kind is a valid type specifier
94 case tok::kw___int128:
96 case tok::kw_unsigned:
103 case tok::kw_wchar_t:
105 case tok::kw___underlying_type:
108 case tok::annot_typename:
109 case tok::kw_char16_t:
110 case tok::kw_char32_t:
112 case tok::kw_decltype:
113 return getLangOpts().CPlusPlus;
122 /// \brief If the identifier refers to a type name within this scope,
123 /// return the declaration of that type.
125 /// This routine performs ordinary name lookup of the identifier II
126 /// within the given scope, with optional C++ scope specifier SS, to
127 /// determine whether the name refers to a type. If so, returns an
128 /// opaque pointer (actually a QualType) corresponding to that
129 /// type. Otherwise, returns NULL.
131 /// If name lookup results in an ambiguity, this routine will complain
132 /// and then return NULL.
133 ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
134 Scope *S, CXXScopeSpec *SS,
135 bool isClassName, bool HasTrailingDot,
136 ParsedType ObjectTypePtr,
137 bool IsCtorOrDtorName,
138 bool WantNontrivialTypeSourceInfo,
139 IdentifierInfo **CorrectedII) {
140 // Determine where we will perform name lookup.
141 DeclContext *LookupCtx = 0;
143 QualType ObjectType = ObjectTypePtr.get();
144 if (ObjectType->isRecordType())
145 LookupCtx = computeDeclContext(ObjectType);
146 } else if (SS && SS->isNotEmpty()) {
147 LookupCtx = computeDeclContext(*SS, false);
150 if (isDependentScopeSpecifier(*SS)) {
152 // A qualified-id that refers to a type and in which the
153 // nested-name-specifier depends on a template-parameter (14.6.2)
154 // shall be prefixed by the keyword typename to indicate that the
155 // qualified-id denotes a type, forming an
156 // elaborated-type-specifier (7.1.5.3).
158 // We therefore do not perform any name lookup if the result would
159 // refer to a member of an unknown specialization.
160 if (!isClassName && !IsCtorOrDtorName)
163 // We know from the grammar that this name refers to a type,
164 // so build a dependent node to describe the type.
165 if (WantNontrivialTypeSourceInfo)
166 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
168 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
170 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
173 return ParsedType::make(T);
179 if (!LookupCtx->isDependentContext() &&
180 RequireCompleteDeclContext(*SS, LookupCtx))
184 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
185 // lookup for class-names.
186 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
188 LookupResult Result(*this, &II, NameLoc, Kind);
190 // Perform "qualified" name lookup into the declaration context we
191 // computed, which is either the type of the base of a member access
192 // expression or the declaration context associated with a prior
193 // nested-name-specifier.
194 LookupQualifiedName(Result, LookupCtx);
196 if (ObjectTypePtr && Result.empty()) {
197 // C++ [basic.lookup.classref]p3:
198 // If the unqualified-id is ~type-name, the type-name is looked up
199 // in the context of the entire postfix-expression. If the type T of
200 // the object expression is of a class type C, the type-name is also
201 // looked up in the scope of class C. At least one of the lookups shall
202 // find a name that refers to (possibly cv-qualified) T.
203 LookupName(Result, S);
206 // Perform unqualified name lookup.
207 LookupName(Result, S);
210 NamedDecl *IIDecl = 0;
211 switch (Result.getResultKind()) {
212 case LookupResult::NotFound:
213 case LookupResult::NotFoundInCurrentInstantiation:
215 TypeNameValidatorCCC Validator(true, isClassName);
216 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
217 Kind, S, SS, Validator);
218 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
220 bool MemberOfUnknownSpecialization;
221 UnqualifiedId TemplateName;
222 TemplateName.setIdentifier(NewII, NameLoc);
223 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
224 CXXScopeSpec NewSS, *NewSSPtr = SS;
226 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
229 if (Correction && (NNS || NewII != &II) &&
230 // Ignore a correction to a template type as the to-be-corrected
231 // identifier is not a template (typo correction for template names
232 // is handled elsewhere).
233 !(getLangOpts().CPlusPlus && NewSSPtr &&
234 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
235 false, Template, MemberOfUnknownSpecialization))) {
236 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
237 isClassName, HasTrailingDot, ObjectTypePtr,
239 WantNontrivialTypeSourceInfo);
241 std::string CorrectedStr(Correction.getAsString(getLangOpts()));
242 std::string CorrectedQuotedStr(
243 Correction.getQuoted(getLangOpts()));
244 Diag(NameLoc, diag::err_unknown_type_or_class_name_suggest)
245 << Result.getLookupName() << CorrectedQuotedStr << isClassName
246 << FixItHint::CreateReplacement(SourceRange(NameLoc),
248 if (NamedDecl *FirstDecl = Correction.getCorrectionDecl())
249 Diag(FirstDecl->getLocation(), diag::note_previous_decl)
250 << CorrectedQuotedStr;
253 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
254 *CorrectedII = NewII;
259 // If typo correction failed or was not performed, fall through
260 case LookupResult::FoundOverloaded:
261 case LookupResult::FoundUnresolvedValue:
262 Result.suppressDiagnostics();
265 case LookupResult::Ambiguous:
266 // Recover from type-hiding ambiguities by hiding the type. We'll
267 // do the lookup again when looking for an object, and we can
268 // diagnose the error then. If we don't do this, then the error
269 // about hiding the type will be immediately followed by an error
270 // that only makes sense if the identifier was treated like a type.
271 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
272 Result.suppressDiagnostics();
276 // Look to see if we have a type anywhere in the list of results.
277 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
278 Res != ResEnd; ++Res) {
279 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
281 (*Res)->getLocation().getRawEncoding() <
282 IIDecl->getLocation().getRawEncoding())
288 // None of the entities we found is a type, so there is no way
289 // to even assume that the result is a type. In this case, don't
290 // complain about the ambiguity. The parser will either try to
291 // perform this lookup again (e.g., as an object name), which
292 // will produce the ambiguity, or will complain that it expected
294 Result.suppressDiagnostics();
298 // We found a type within the ambiguous lookup; diagnose the
299 // ambiguity and then return that type. This might be the right
300 // answer, or it might not be, but it suppresses any attempt to
301 // perform the name lookup again.
304 case LookupResult::Found:
305 IIDecl = Result.getFoundDecl();
309 assert(IIDecl && "Didn't find decl");
312 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
313 DiagnoseUseOfDecl(IIDecl, NameLoc);
316 T = Context.getTypeDeclType(TD);
318 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
319 // constructor or destructor name (in such a case, the scope specifier
320 // will be attached to the enclosing Expr or Decl node).
321 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
322 if (WantNontrivialTypeSourceInfo) {
323 // Construct a type with type-source information.
324 TypeLocBuilder Builder;
325 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
327 T = getElaboratedType(ETK_None, *SS, T);
328 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
329 ElabTL.setElaboratedKeywordLoc(SourceLocation());
330 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
331 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
333 T = getElaboratedType(ETK_None, *SS, T);
336 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
337 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
339 T = Context.getObjCInterfaceType(IDecl);
343 // If it's not plausibly a type, suppress diagnostics.
344 Result.suppressDiagnostics();
347 return ParsedType::make(T);
350 /// isTagName() - This method is called *for error recovery purposes only*
351 /// to determine if the specified name is a valid tag name ("struct foo"). If
352 /// so, this returns the TST for the tag corresponding to it (TST_enum,
353 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
354 /// cases in C where the user forgot to specify the tag.
355 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
356 // Do a tag name lookup in this scope.
357 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
358 LookupName(R, S, false);
359 R.suppressDiagnostics();
360 if (R.getResultKind() == LookupResult::Found)
361 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
362 switch (TD->getTagKind()) {
363 case TTK_Struct: return DeclSpec::TST_struct;
364 case TTK_Interface: return DeclSpec::TST_interface;
365 case TTK_Union: return DeclSpec::TST_union;
366 case TTK_Class: return DeclSpec::TST_class;
367 case TTK_Enum: return DeclSpec::TST_enum;
371 return DeclSpec::TST_unspecified;
374 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
375 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
376 /// then downgrade the missing typename error to a warning.
377 /// This is needed for MSVC compatibility; Example:
379 /// template<class T> class A {
381 /// typedef int TYPE;
383 /// template<class T> class B : public A<T> {
385 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
388 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
389 if (CurContext->isRecord()) {
390 const Type *Ty = SS->getScopeRep()->getAsType();
392 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
393 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
394 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
395 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
397 return S->isFunctionPrototypeScope();
399 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
402 bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
403 SourceLocation IILoc,
406 ParsedType &SuggestedType) {
407 // We don't have anything to suggest (yet).
408 SuggestedType = ParsedType();
410 // There may have been a typo in the name of the type. Look up typo
411 // results, in case we have something that we can suggest.
412 TypeNameValidatorCCC Validator(false);
413 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
414 LookupOrdinaryName, S, SS,
416 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
417 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
419 if (Corrected.isKeyword()) {
420 // We corrected to a keyword.
421 IdentifierInfo *NewII = Corrected.getCorrectionAsIdentifierInfo();
422 if (!isSimpleTypeSpecifier(NewII->getTokenID()))
423 CorrectedQuotedStr = "the keyword " + CorrectedQuotedStr;
424 Diag(IILoc, diag::err_unknown_typename_suggest)
425 << II << CorrectedQuotedStr
426 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
429 NamedDecl *Result = Corrected.getCorrectionDecl();
430 // We found a similarly-named type or interface; suggest that.
431 if (!SS || !SS->isSet())
432 Diag(IILoc, diag::err_unknown_typename_suggest)
433 << II << CorrectedQuotedStr
434 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
435 else if (DeclContext *DC = computeDeclContext(*SS, false))
436 Diag(IILoc, diag::err_unknown_nested_typename_suggest)
437 << II << DC << CorrectedQuotedStr << SS->getRange()
438 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
441 llvm_unreachable("could not have corrected a typo here");
443 Diag(Result->getLocation(), diag::note_previous_decl)
444 << CorrectedQuotedStr;
446 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS,
447 false, false, ParsedType(),
448 /*IsCtorOrDtorName=*/false,
449 /*NonTrivialTypeSourceInfo=*/true);
454 if (getLangOpts().CPlusPlus) {
455 // See if II is a class template that the user forgot to pass arguments to.
457 Name.setIdentifier(II, IILoc);
458 CXXScopeSpec EmptySS;
459 TemplateTy TemplateResult;
460 bool MemberOfUnknownSpecialization;
461 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
462 Name, ParsedType(), true, TemplateResult,
463 MemberOfUnknownSpecialization) == TNK_Type_template) {
464 TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
465 Diag(IILoc, diag::err_template_missing_args) << TplName;
466 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
467 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
468 << TplDecl->getTemplateParameters()->getSourceRange();
474 // FIXME: Should we move the logic that tries to recover from a missing tag
475 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
477 if (!SS || (!SS->isSet() && !SS->isInvalid()))
478 Diag(IILoc, diag::err_unknown_typename) << II;
479 else if (DeclContext *DC = computeDeclContext(*SS, false))
480 Diag(IILoc, diag::err_typename_nested_not_found)
481 << II << DC << SS->getRange();
482 else if (isDependentScopeSpecifier(*SS)) {
483 unsigned DiagID = diag::err_typename_missing;
484 if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
485 DiagID = diag::warn_typename_missing;
487 Diag(SS->getRange().getBegin(), DiagID)
488 << (NestedNameSpecifier *)SS->getScopeRep() << II->getName()
489 << SourceRange(SS->getRange().getBegin(), IILoc)
490 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
491 SuggestedType = ActOnTypenameType(S, SourceLocation(),
492 *SS, *II, IILoc).get();
494 assert(SS && SS->isInvalid() &&
495 "Invalid scope specifier has already been diagnosed");
501 /// \brief Determine whether the given result set contains either a type name
503 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
504 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
505 NextToken.is(tok::less);
507 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
508 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
511 if (CheckTemplate && isa<TemplateDecl>(*I))
518 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
519 Scope *S, CXXScopeSpec &SS,
520 IdentifierInfo *&Name,
521 SourceLocation NameLoc) {
522 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
523 SemaRef.LookupParsedName(R, S, &SS);
524 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
525 const char *TagName = 0;
526 const char *FixItTagName = 0;
527 switch (Tag->getTagKind()) {
530 FixItTagName = "class ";
535 FixItTagName = "enum ";
540 FixItTagName = "struct ";
544 TagName = "__interface";
545 FixItTagName = "__interface ";
550 FixItTagName = "union ";
554 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
555 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
556 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
558 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
560 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
563 // Replace lookup results with just the tag decl.
564 Result.clear(Sema::LookupTagName);
565 SemaRef.LookupParsedName(Result, S, &SS);
572 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
573 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
574 QualType T, SourceLocation NameLoc) {
575 ASTContext &Context = S.Context;
577 TypeLocBuilder Builder;
578 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
580 T = S.getElaboratedType(ETK_None, SS, T);
581 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
582 ElabTL.setElaboratedKeywordLoc(SourceLocation());
583 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
584 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
587 Sema::NameClassification Sema::ClassifyName(Scope *S,
589 IdentifierInfo *&Name,
590 SourceLocation NameLoc,
591 const Token &NextToken,
592 bool IsAddressOfOperand,
593 CorrectionCandidateCallback *CCC) {
594 DeclarationNameInfo NameInfo(Name, NameLoc);
595 ObjCMethodDecl *CurMethod = getCurMethodDecl();
597 if (NextToken.is(tok::coloncolon)) {
598 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
599 QualType(), false, SS, 0, false);
603 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
604 LookupParsedName(Result, S, &SS, !CurMethod);
606 // Perform lookup for Objective-C instance variables (including automatically
607 // synthesized instance variables), if we're in an Objective-C method.
608 // FIXME: This lookup really, really needs to be folded in to the normal
609 // unqualified lookup mechanism.
610 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
611 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
612 if (E.get() || E.isInvalid())
616 bool SecondTry = false;
617 bool IsFilteredTemplateName = false;
620 switch (Result.getResultKind()) {
621 case LookupResult::NotFound:
622 // If an unqualified-id is followed by a '(', then we have a function
624 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
625 // In C++, this is an ADL-only call.
627 if (getLangOpts().CPlusPlus)
628 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
631 // If the expression that precedes the parenthesized argument list in a
632 // function call consists solely of an identifier, and if no
633 // declaration is visible for this identifier, the identifier is
634 // implicitly declared exactly as if, in the innermost block containing
635 // the function call, the declaration
637 // extern int identifier ();
641 // We also allow this in C99 as an extension.
642 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
644 Result.resolveKind();
645 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
649 // In C, we first see whether there is a tag type by the same name, in
650 // which case it's likely that the user just forget to write "enum",
651 // "struct", or "union".
652 if (!getLangOpts().CPlusPlus && !SecondTry &&
653 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
657 // Perform typo correction to determine if there is another name that is
658 // close to this name.
659 if (!SecondTry && CCC) {
661 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
662 Result.getLookupKind(), S,
664 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
665 unsigned QualifiedDiag = diag::err_no_member_suggest;
666 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
667 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
669 NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
670 NamedDecl *UnderlyingFirstDecl
671 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
672 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
673 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
674 UnqualifiedDiag = diag::err_no_template_suggest;
675 QualifiedDiag = diag::err_no_member_template_suggest;
676 } else if (UnderlyingFirstDecl &&
677 (isa<TypeDecl>(UnderlyingFirstDecl) ||
678 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
679 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
680 UnqualifiedDiag = diag::err_unknown_typename_suggest;
681 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
685 Diag(NameLoc, UnqualifiedDiag)
686 << Name << CorrectedQuotedStr
687 << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
688 else // FIXME: is this even reachable? Test it.
689 Diag(NameLoc, QualifiedDiag)
690 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
692 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
695 // Update the name, so that the caller has the new name.
696 Name = Corrected.getCorrectionAsIdentifierInfo();
698 // Typo correction corrected to a keyword.
699 if (Corrected.isKeyword())
700 return Corrected.getCorrectionAsIdentifierInfo();
702 // Also update the LookupResult...
703 // FIXME: This should probably go away at some point
705 Result.setLookupName(Corrected.getCorrection());
707 Result.addDecl(FirstDecl);
708 Diag(FirstDecl->getLocation(), diag::note_previous_decl)
709 << CorrectedQuotedStr;
712 // If we found an Objective-C instance variable, let
713 // LookupInObjCMethod build the appropriate expression to
714 // reference the ivar.
715 // FIXME: This is a gross hack.
716 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
718 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
726 // We failed to correct; just fall through and let the parser deal with it.
727 Result.suppressDiagnostics();
728 return NameClassification::Unknown();
730 case LookupResult::NotFoundInCurrentInstantiation: {
731 // We performed name lookup into the current instantiation, and there were
732 // dependent bases, so we treat this result the same way as any other
733 // dependent nested-name-specifier.
736 // A name used in a template declaration or definition and that is
737 // dependent on a template-parameter is assumed not to name a type
738 // unless the applicable name lookup finds a type name or the name is
739 // qualified by the keyword typename.
741 // FIXME: If the next token is '<', we might want to ask the parser to
742 // perform some heroics to see if we actually have a
743 // template-argument-list, which would indicate a missing 'template'
745 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
746 NameInfo, IsAddressOfOperand,
750 case LookupResult::Found:
751 case LookupResult::FoundOverloaded:
752 case LookupResult::FoundUnresolvedValue:
755 case LookupResult::Ambiguous:
756 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
757 hasAnyAcceptableTemplateNames(Result)) {
758 // C++ [temp.local]p3:
759 // A lookup that finds an injected-class-name (10.2) can result in an
760 // ambiguity in certain cases (for example, if it is found in more than
761 // one base class). If all of the injected-class-names that are found
762 // refer to specializations of the same class template, and if the name
763 // is followed by a template-argument-list, the reference refers to the
764 // class template itself and not a specialization thereof, and is not
767 // This filtering can make an ambiguous result into an unambiguous one,
768 // so try again after filtering out template names.
769 FilterAcceptableTemplateNames(Result);
770 if (!Result.isAmbiguous()) {
771 IsFilteredTemplateName = true;
776 // Diagnose the ambiguity and return an error.
777 return NameClassification::Error();
780 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
781 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
782 // C++ [temp.names]p3:
783 // After name lookup (3.4) finds that a name is a template-name or that
784 // an operator-function-id or a literal- operator-id refers to a set of
785 // overloaded functions any member of which is a function template if
786 // this is followed by a <, the < is always taken as the delimiter of a
787 // template-argument-list and never as the less-than operator.
788 if (!IsFilteredTemplateName)
789 FilterAcceptableTemplateNames(Result);
791 if (!Result.empty()) {
792 bool IsFunctionTemplate;
793 TemplateName Template;
794 if (Result.end() - Result.begin() > 1) {
795 IsFunctionTemplate = true;
796 Template = Context.getOverloadedTemplateName(Result.begin(),
800 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
801 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
803 if (SS.isSet() && !SS.isInvalid())
804 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
805 /*TemplateKeyword=*/false,
808 Template = TemplateName(TD);
811 if (IsFunctionTemplate) {
812 // Function templates always go through overload resolution, at which
813 // point we'll perform the various checks (e.g., accessibility) we need
814 // to based on which function we selected.
815 Result.suppressDiagnostics();
817 return NameClassification::FunctionTemplate(Template);
820 return NameClassification::TypeTemplate(Template);
824 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
825 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
826 DiagnoseUseOfDecl(Type, NameLoc);
827 QualType T = Context.getTypeDeclType(Type);
829 return buildNestedType(*this, SS, T, NameLoc);
830 return ParsedType::make(T);
833 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
835 // FIXME: It's unfortunate that we don't have a Type node for handling this.
836 if (ObjCCompatibleAliasDecl *Alias
837 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
838 Class = Alias->getClassInterface();
842 DiagnoseUseOfDecl(Class, NameLoc);
844 if (NextToken.is(tok::period)) {
845 // Interface. <something> is parsed as a property reference expression.
846 // Just return "unknown" as a fall-through for now.
847 Result.suppressDiagnostics();
848 return NameClassification::Unknown();
851 QualType T = Context.getObjCInterfaceType(Class);
852 return ParsedType::make(T);
855 // We can have a type template here if we're classifying a template argument.
856 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
857 return NameClassification::TypeTemplate(
858 TemplateName(cast<TemplateDecl>(FirstDecl)));
860 // Check for a tag type hidden by a non-type decl in a few cases where it
861 // seems likely a type is wanted instead of the non-type that was found.
862 if (!getLangOpts().ObjC1) {
863 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
864 if ((NextToken.is(tok::identifier) ||
865 (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) &&
866 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
867 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
868 DiagnoseUseOfDecl(Type, NameLoc);
869 QualType T = Context.getTypeDeclType(Type);
871 return buildNestedType(*this, SS, T, NameLoc);
872 return ParsedType::make(T);
876 if (FirstDecl->isCXXClassMember())
877 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
879 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
880 return BuildDeclarationNameExpr(SS, Result, ADL);
883 // Determines the context to return to after temporarily entering a
884 // context. This depends in an unnecessarily complicated way on the
885 // exact ordering of callbacks from the parser.
886 DeclContext *Sema::getContainingDC(DeclContext *DC) {
888 // Functions defined inline within classes aren't parsed until we've
889 // finished parsing the top-level class, so the top-level class is
890 // the context we'll need to return to.
891 if (isa<FunctionDecl>(DC)) {
892 DC = DC->getLexicalParent();
894 // A function not defined within a class will always return to its
896 if (!isa<CXXRecordDecl>(DC))
899 // A C++ inline method/friend is parsed *after* the topmost class
900 // it was declared in is fully parsed ("complete"); the topmost
901 // class is the context we need to return to.
902 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
905 // Return the declaration context of the topmost class the inline method is
910 return DC->getLexicalParent();
913 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
914 assert(getContainingDC(DC) == CurContext &&
915 "The next DeclContext should be lexically contained in the current one.");
920 void Sema::PopDeclContext() {
921 assert(CurContext && "DeclContext imbalance!");
923 CurContext = getContainingDC(CurContext);
924 assert(CurContext && "Popped translation unit!");
927 /// EnterDeclaratorContext - Used when we must lookup names in the context
928 /// of a declarator's nested name specifier.
930 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
931 // C++0x [basic.lookup.unqual]p13:
932 // A name used in the definition of a static data member of class
933 // X (after the qualified-id of the static member) is looked up as
934 // if the name was used in a member function of X.
935 // C++0x [basic.lookup.unqual]p14:
936 // If a variable member of a namespace is defined outside of the
937 // scope of its namespace then any name used in the definition of
938 // the variable member (after the declarator-id) is looked up as
939 // if the definition of the variable member occurred in its
941 // Both of these imply that we should push a scope whose context
942 // is the semantic context of the declaration. We can't use
943 // PushDeclContext here because that context is not necessarily
944 // lexically contained in the current context. Fortunately,
945 // the containing scope should have the appropriate information.
947 assert(!S->getEntity() && "scope already has entity");
950 Scope *Ancestor = S->getParent();
951 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
952 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
959 void Sema::ExitDeclaratorContext(Scope *S) {
960 assert(S->getEntity() == CurContext && "Context imbalance!");
962 // Switch back to the lexical context. The safety of this is
963 // enforced by an assert in EnterDeclaratorContext.
964 Scope *Ancestor = S->getParent();
965 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
966 CurContext = (DeclContext*) Ancestor->getEntity();
968 // We don't need to do anything with the scope, which is going to
973 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
974 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
975 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
976 // We assume that the caller has already called
977 // ActOnReenterTemplateScope
978 FD = TFD->getTemplatedDecl();
983 // Same implementation as PushDeclContext, but enters the context
984 // from the lexical parent, rather than the top-level class.
985 assert(CurContext == FD->getLexicalParent() &&
986 "The next DeclContext should be lexically contained in the current one.");
988 S->setEntity(CurContext);
990 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
991 ParmVarDecl *Param = FD->getParamDecl(P);
992 // If the parameter has an identifier, then add it to the scope
993 if (Param->getIdentifier()) {
995 IdResolver.AddDecl(Param);
1001 void Sema::ActOnExitFunctionContext() {
1002 // Same implementation as PopDeclContext, but returns to the lexical parent,
1003 // rather than the top-level class.
1004 assert(CurContext && "DeclContext imbalance!");
1005 CurContext = CurContext->getLexicalParent();
1006 assert(CurContext && "Popped translation unit!");
1010 /// \brief Determine whether we allow overloading of the function
1011 /// PrevDecl with another declaration.
1013 /// This routine determines whether overloading is possible, not
1014 /// whether some new function is actually an overload. It will return
1015 /// true in C++ (where we can always provide overloads) or, as an
1016 /// extension, in C when the previous function is already an
1017 /// overloaded function declaration or has the "overloadable"
1019 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1020 ASTContext &Context) {
1021 if (Context.getLangOpts().CPlusPlus)
1024 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1027 return (Previous.getResultKind() == LookupResult::Found
1028 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1031 /// Add this decl to the scope shadowed decl chains.
1032 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1033 // Move up the scope chain until we find the nearest enclosing
1034 // non-transparent context. The declaration will be introduced into this
1036 while (S->getEntity() &&
1037 ((DeclContext *)S->getEntity())->isTransparentContext())
1040 // Add scoped declarations into their context, so that they can be
1041 // found later. Declarations without a context won't be inserted
1042 // into any context.
1044 CurContext->addDecl(D);
1046 // Out-of-line definitions shouldn't be pushed into scope in C++.
1047 // Out-of-line variable and function definitions shouldn't even in C.
1048 if ((getLangOpts().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
1050 !D->getDeclContext()->getRedeclContext()->Equals(
1051 D->getLexicalDeclContext()->getRedeclContext()))
1054 // Template instantiations should also not be pushed into scope.
1055 if (isa<FunctionDecl>(D) &&
1056 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1059 // If this replaces anything in the current scope,
1060 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1061 IEnd = IdResolver.end();
1062 for (; I != IEnd; ++I) {
1063 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1065 IdResolver.RemoveDecl(*I);
1067 // Should only need to replace one decl.
1074 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1075 // Implicitly-generated labels may end up getting generated in an order that
1076 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1077 // the label at the appropriate place in the identifier chain.
1078 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1079 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1080 if (IDC == CurContext) {
1081 if (!S->isDeclScope(*I))
1083 } else if (IDC->Encloses(CurContext))
1087 IdResolver.InsertDeclAfter(I, D);
1089 IdResolver.AddDecl(D);
1093 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1094 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1095 TUScope->AddDecl(D);
1098 bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S,
1099 bool ExplicitInstantiationOrSpecialization) {
1100 return IdResolver.isDeclInScope(D, Ctx, Context, S,
1101 ExplicitInstantiationOrSpecialization);
1104 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1105 DeclContext *TargetDC = DC->getPrimaryContext();
1107 if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
1108 if (ScopeDC->getPrimaryContext() == TargetDC)
1110 } while ((S = S->getParent()));
1115 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1119 /// Filters out lookup results that don't fall within the given scope
1120 /// as determined by isDeclInScope.
1121 void Sema::FilterLookupForScope(LookupResult &R,
1122 DeclContext *Ctx, Scope *S,
1123 bool ConsiderLinkage,
1124 bool ExplicitInstantiationOrSpecialization) {
1125 LookupResult::Filter F = R.makeFilter();
1126 while (F.hasNext()) {
1127 NamedDecl *D = F.next();
1129 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
1132 if (ConsiderLinkage &&
1133 isOutOfScopePreviousDeclaration(D, Ctx, Context))
1142 static bool isUsingDecl(NamedDecl *D) {
1143 return isa<UsingShadowDecl>(D) ||
1144 isa<UnresolvedUsingTypenameDecl>(D) ||
1145 isa<UnresolvedUsingValueDecl>(D);
1148 /// Removes using shadow declarations from the lookup results.
1149 static void RemoveUsingDecls(LookupResult &R) {
1150 LookupResult::Filter F = R.makeFilter();
1152 if (isUsingDecl(F.next()))
1158 /// \brief Check for this common pattern:
1161 /// S(const S&); // DO NOT IMPLEMENT
1162 /// void operator=(const S&); // DO NOT IMPLEMENT
1165 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1166 // FIXME: Should check for private access too but access is set after we get
1168 if (D->doesThisDeclarationHaveABody())
1171 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1172 return CD->isCopyConstructor();
1173 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1174 return Method->isCopyAssignmentOperator();
1178 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1181 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1184 // Ignore class templates.
1185 if (D->getDeclContext()->isDependentContext() ||
1186 D->getLexicalDeclContext()->isDependentContext())
1189 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1190 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1193 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1194 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1197 // 'static inline' functions are used in headers; don't warn.
1198 if (FD->getStorageClass() == SC_Static &&
1199 FD->isInlineSpecified())
1203 if (FD->doesThisDeclarationHaveABody() &&
1204 Context.DeclMustBeEmitted(FD))
1206 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1207 // Don't warn on variables of const-qualified or reference type, since their
1208 // values can be used even if though they're not odr-used, and because const
1209 // qualified variables can appear in headers in contexts where they're not
1210 // intended to be used.
1211 // FIXME: Use more principled rules for these exemptions.
1212 if (!VD->isFileVarDecl() ||
1213 VD->getType().isConstQualified() ||
1214 VD->getType()->isReferenceType() ||
1215 Context.DeclMustBeEmitted(VD))
1218 if (VD->isStaticDataMember() &&
1219 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1226 // Only warn for unused decls internal to the translation unit.
1227 if (D->getLinkage() == ExternalLinkage)
1233 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1237 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1238 const FunctionDecl *First = FD->getFirstDeclaration();
1239 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1240 return; // First should already be in the vector.
1243 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1244 const VarDecl *First = VD->getFirstDeclaration();
1245 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1246 return; // First should already be in the vector.
1249 if (ShouldWarnIfUnusedFileScopedDecl(D))
1250 UnusedFileScopedDecls.push_back(D);
1253 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1254 if (D->isInvalidDecl())
1257 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
1260 if (isa<LabelDecl>(D))
1263 // White-list anything that isn't a local variable.
1264 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1265 !D->getDeclContext()->isFunctionOrMethod())
1268 // Types of valid local variables should be complete, so this should succeed.
1269 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1271 // White-list anything with an __attribute__((unused)) type.
1272 QualType Ty = VD->getType();
1274 // Only look at the outermost level of typedef.
1275 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1276 if (TT->getDecl()->hasAttr<UnusedAttr>())
1280 // If we failed to complete the type for some reason, or if the type is
1281 // dependent, don't diagnose the variable.
1282 if (Ty->isIncompleteType() || Ty->isDependentType())
1285 if (const TagType *TT = Ty->getAs<TagType>()) {
1286 const TagDecl *Tag = TT->getDecl();
1287 if (Tag->hasAttr<UnusedAttr>())
1290 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1291 if (!RD->hasTrivialDestructor())
1294 if (const Expr *Init = VD->getInit()) {
1295 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1296 Init = Cleanups->getSubExpr();
1297 const CXXConstructExpr *Construct =
1298 dyn_cast<CXXConstructExpr>(Init);
1299 if (Construct && !Construct->isElidable()) {
1300 CXXConstructorDecl *CD = Construct->getConstructor();
1301 if (!CD->isTrivial())
1308 // TODO: __attribute__((unused)) templates?
1314 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1316 if (isa<LabelDecl>(D)) {
1317 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1318 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1319 if (AfterColon.isInvalid())
1321 Hint = FixItHint::CreateRemoval(CharSourceRange::
1322 getCharRange(D->getLocStart(), AfterColon));
1327 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1328 /// unless they are marked attr(unused).
1329 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1331 if (!ShouldDiagnoseUnusedDecl(D))
1334 GenerateFixForUnusedDecl(D, Context, Hint);
1337 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1338 DiagID = diag::warn_unused_exception_param;
1339 else if (isa<LabelDecl>(D))
1340 DiagID = diag::warn_unused_label;
1342 DiagID = diag::warn_unused_variable;
1344 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1347 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1348 // Verify that we have no forward references left. If so, there was a goto
1349 // or address of a label taken, but no definition of it. Label fwd
1350 // definitions are indicated with a null substmt.
1351 if (L->getStmt() == 0)
1352 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1355 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1356 if (S->decl_empty()) return;
1357 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1358 "Scope shouldn't contain decls!");
1360 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1363 assert(TmpD && "This decl didn't get pushed??");
1365 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1366 NamedDecl *D = cast<NamedDecl>(TmpD);
1368 if (!D->getDeclName()) continue;
1370 // Diagnose unused variables in this scope.
1371 if (!S->hasErrorOccurred())
1372 DiagnoseUnusedDecl(D);
1374 // If this was a forward reference to a label, verify it was defined.
1375 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1376 CheckPoppedLabel(LD, *this);
1378 // Remove this name from our lexical scope.
1379 IdResolver.RemoveDecl(D);
1383 void Sema::ActOnStartFunctionDeclarator() {
1384 ++InFunctionDeclarator;
1387 void Sema::ActOnEndFunctionDeclarator() {
1388 assert(InFunctionDeclarator);
1389 --InFunctionDeclarator;
1392 /// \brief Look for an Objective-C class in the translation unit.
1394 /// \param Id The name of the Objective-C class we're looking for. If
1395 /// typo-correction fixes this name, the Id will be updated
1396 /// to the fixed name.
1398 /// \param IdLoc The location of the name in the translation unit.
1400 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1401 /// if there is no class with the given name.
1403 /// \returns The declaration of the named Objective-C class, or NULL if the
1404 /// class could not be found.
1405 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1406 SourceLocation IdLoc,
1407 bool DoTypoCorrection) {
1408 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1409 // creation from this context.
1410 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1412 if (!IDecl && DoTypoCorrection) {
1413 // Perform typo correction at the given location, but only if we
1414 // find an Objective-C class name.
1415 DeclFilterCCC<ObjCInterfaceDecl> Validator;
1416 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1417 LookupOrdinaryName, TUScope, NULL,
1419 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1420 Diag(IdLoc, diag::err_undef_interface_suggest)
1421 << Id << IDecl->getDeclName()
1422 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
1423 Diag(IDecl->getLocation(), diag::note_previous_decl)
1424 << IDecl->getDeclName();
1426 Id = IDecl->getIdentifier();
1429 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1430 // This routine must always return a class definition, if any.
1431 if (Def && Def->getDefinition())
1432 Def = Def->getDefinition();
1436 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1437 /// from S, where a non-field would be declared. This routine copes
1438 /// with the difference between C and C++ scoping rules in structs and
1439 /// unions. For example, the following code is well-formed in C but
1440 /// ill-formed in C++:
1446 /// void test_S6() {
1451 /// For the declaration of BAR, this routine will return a different
1452 /// scope. The scope S will be the scope of the unnamed enumeration
1453 /// within S6. In C++, this routine will return the scope associated
1454 /// with S6, because the enumeration's scope is a transparent
1455 /// context but structures can contain non-field names. In C, this
1456 /// routine will return the translation unit scope, since the
1457 /// enumeration's scope is a transparent context and structures cannot
1458 /// contain non-field names.
1459 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1460 while (((S->getFlags() & Scope::DeclScope) == 0) ||
1462 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
1463 (S->isClassScope() && !getLangOpts().CPlusPlus))
1468 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1469 /// file scope. lazily create a decl for it. ForRedeclaration is true
1470 /// if we're creating this built-in in anticipation of redeclaring the
1472 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
1473 Scope *S, bool ForRedeclaration,
1474 SourceLocation Loc) {
1475 Builtin::ID BID = (Builtin::ID)bid;
1477 ASTContext::GetBuiltinTypeError Error;
1478 QualType R = Context.GetBuiltinType(BID, Error);
1480 case ASTContext::GE_None:
1484 case ASTContext::GE_Missing_stdio:
1485 if (ForRedeclaration)
1486 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
1487 << Context.BuiltinInfo.GetName(BID);
1490 case ASTContext::GE_Missing_setjmp:
1491 if (ForRedeclaration)
1492 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
1493 << Context.BuiltinInfo.GetName(BID);
1496 case ASTContext::GE_Missing_ucontext:
1497 if (ForRedeclaration)
1498 Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1499 << Context.BuiltinInfo.GetName(BID);
1503 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1504 Diag(Loc, diag::ext_implicit_lib_function_decl)
1505 << Context.BuiltinInfo.GetName(BID)
1507 if (Context.BuiltinInfo.getHeaderName(BID) &&
1508 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
1509 != DiagnosticsEngine::Ignored)
1510 Diag(Loc, diag::note_please_include_header)
1511 << Context.BuiltinInfo.getHeaderName(BID)
1512 << Context.BuiltinInfo.GetName(BID);
1515 FunctionDecl *New = FunctionDecl::Create(Context,
1516 Context.getTranslationUnitDecl(),
1517 Loc, Loc, II, R, /*TInfo=*/0,
1520 /*hasPrototype=*/true);
1523 // Create Decl objects for each parameter, adding them to the
1525 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1526 SmallVector<ParmVarDecl*, 16> Params;
1527 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1529 ParmVarDecl::Create(Context, New, SourceLocation(),
1530 SourceLocation(), 0,
1531 FT->getArgType(i), /*TInfo=*/0,
1532 SC_None, SC_None, 0);
1533 parm->setScopeInfo(0, i);
1534 Params.push_back(parm);
1536 New->setParams(Params);
1539 AddKnownFunctionAttributes(New);
1541 // TUScope is the translation-unit scope to insert this function into.
1542 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1543 // relate Scopes to DeclContexts, and probably eliminate CurContext
1544 // entirely, but we're not there yet.
1545 DeclContext *SavedContext = CurContext;
1546 CurContext = Context.getTranslationUnitDecl();
1547 PushOnScopeChains(New, TUScope);
1548 CurContext = SavedContext;
1552 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1554 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1555 OldType = OldTypedef->getUnderlyingType();
1557 OldType = Context.getTypeDeclType(Old);
1558 QualType NewType = New->getUnderlyingType();
1560 if (NewType->isVariablyModifiedType()) {
1561 // Must not redefine a typedef with a variably-modified type.
1562 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1563 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1565 if (Old->getLocation().isValid())
1566 Diag(Old->getLocation(), diag::note_previous_definition);
1567 New->setInvalidDecl();
1571 if (OldType != NewType &&
1572 !OldType->isDependentType() &&
1573 !NewType->isDependentType() &&
1574 !Context.hasSameType(OldType, NewType)) {
1575 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1576 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1577 << Kind << NewType << OldType;
1578 if (Old->getLocation().isValid())
1579 Diag(Old->getLocation(), diag::note_previous_definition);
1580 New->setInvalidDecl();
1586 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1587 /// same name and scope as a previous declaration 'Old'. Figure out
1588 /// how to resolve this situation, merging decls or emitting
1589 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1591 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
1592 // If the new decl is known invalid already, don't bother doing any
1594 if (New->isInvalidDecl()) return;
1596 // Allow multiple definitions for ObjC built-in typedefs.
1597 // FIXME: Verify the underlying types are equivalent!
1598 if (getLangOpts().ObjC1) {
1599 const IdentifierInfo *TypeID = New->getIdentifier();
1600 switch (TypeID->getLength()) {
1604 if (!TypeID->isStr("id"))
1606 QualType T = New->getUnderlyingType();
1607 if (!T->isPointerType())
1609 if (!T->isVoidPointerType()) {
1610 QualType PT = T->getAs<PointerType>()->getPointeeType();
1611 if (!PT->isStructureType())
1614 Context.setObjCIdRedefinitionType(T);
1615 // Install the built-in type for 'id', ignoring the current definition.
1616 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1620 if (!TypeID->isStr("Class"))
1622 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1623 // Install the built-in type for 'Class', ignoring the current definition.
1624 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1627 if (!TypeID->isStr("SEL"))
1629 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1630 // Install the built-in type for 'SEL', ignoring the current definition.
1631 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1634 // Fall through - the typedef name was not a builtin type.
1637 // Verify the old decl was also a type.
1638 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1640 Diag(New->getLocation(), diag::err_redefinition_different_kind)
1641 << New->getDeclName();
1643 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1644 if (OldD->getLocation().isValid())
1645 Diag(OldD->getLocation(), diag::note_previous_definition);
1647 return New->setInvalidDecl();
1650 // If the old declaration is invalid, just give up here.
1651 if (Old->isInvalidDecl())
1652 return New->setInvalidDecl();
1654 // If the typedef types are not identical, reject them in all languages and
1655 // with any extensions enabled.
1656 if (isIncompatibleTypedef(Old, New))
1659 // The types match. Link up the redeclaration chain if the old
1660 // declaration was a typedef.
1661 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old))
1662 New->setPreviousDeclaration(Typedef);
1664 if (getLangOpts().MicrosoftExt)
1667 if (getLangOpts().CPlusPlus) {
1668 // C++ [dcl.typedef]p2:
1669 // In a given non-class scope, a typedef specifier can be used to
1670 // redefine the name of any type declared in that scope to refer
1671 // to the type to which it already refers.
1672 if (!isa<CXXRecordDecl>(CurContext))
1675 // C++0x [dcl.typedef]p4:
1676 // In a given class scope, a typedef specifier can be used to redefine
1677 // any class-name declared in that scope that is not also a typedef-name
1678 // to refer to the type to which it already refers.
1680 // This wording came in via DR424, which was a correction to the
1681 // wording in DR56, which accidentally banned code like:
1684 // typedef struct A { } A;
1687 // in the C++03 standard. We implement the C++0x semantics, which
1688 // allow the above but disallow
1695 // since that was the intent of DR56.
1696 if (!isa<TypedefNameDecl>(Old))
1699 Diag(New->getLocation(), diag::err_redefinition)
1700 << New->getDeclName();
1701 Diag(Old->getLocation(), diag::note_previous_definition);
1702 return New->setInvalidDecl();
1705 // Modules always permit redefinition of typedefs, as does C11.
1706 if (getLangOpts().Modules || getLangOpts().C11)
1709 // If we have a redefinition of a typedef in C, emit a warning. This warning
1710 // is normally mapped to an error, but can be controlled with
1711 // -Wtypedef-redefinition. If either the original or the redefinition is
1712 // in a system header, don't emit this for compatibility with GCC.
1713 if (getDiagnostics().getSuppressSystemWarnings() &&
1714 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1715 Context.getSourceManager().isInSystemHeader(New->getLocation())))
1718 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1719 << New->getDeclName();
1720 Diag(Old->getLocation(), diag::note_previous_definition);
1724 /// DeclhasAttr - returns true if decl Declaration already has the target
1727 DeclHasAttr(const Decl *D, const Attr *A) {
1728 // There can be multiple AvailabilityAttr in a Decl. Make sure we copy
1729 // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is
1730 // responsible for making sure they are consistent.
1731 const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A);
1735 // The following thread safety attributes can also be duplicated.
1736 switch (A->getKind()) {
1737 case attr::ExclusiveLocksRequired:
1738 case attr::SharedLocksRequired:
1739 case attr::LocksExcluded:
1740 case attr::ExclusiveLockFunction:
1741 case attr::SharedLockFunction:
1742 case attr::UnlockFunction:
1743 case attr::ExclusiveTrylockFunction:
1744 case attr::SharedTrylockFunction:
1745 case attr::GuardedBy:
1746 case attr::PtGuardedBy:
1747 case attr::AcquiredBefore:
1748 case attr::AcquiredAfter:
1754 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1755 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
1756 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1757 if ((*i)->getKind() == A->getKind()) {
1759 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1763 // FIXME: Don't hardcode this check
1764 if (OA && isa<OwnershipAttr>(*i))
1765 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
1772 bool Sema::mergeDeclAttribute(Decl *D, InheritableAttr *Attr) {
1773 InheritableAttr *NewAttr = NULL;
1774 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
1775 NewAttr = mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1776 AA->getIntroduced(), AA->getDeprecated(),
1777 AA->getObsoleted(), AA->getUnavailable(),
1779 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1780 NewAttr = mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility());
1781 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
1782 NewAttr = mergeDLLImportAttr(D, ImportA->getRange());
1783 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
1784 NewAttr = mergeDLLExportAttr(D, ExportA->getRange());
1785 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
1786 NewAttr = mergeFormatAttr(D, FA->getRange(), FA->getType(),
1787 FA->getFormatIdx(), FA->getFirstArg());
1788 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
1789 NewAttr = mergeSectionAttr(D, SA->getRange(), SA->getName());
1790 else if (!DeclHasAttr(D, Attr))
1791 NewAttr = cast<InheritableAttr>(Attr->clone(Context));
1794 NewAttr->setInherited(true);
1795 D->addAttr(NewAttr);
1802 static const Decl *getDefinition(const Decl *D) {
1803 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
1804 return TD->getDefinition();
1805 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1806 return VD->getDefinition();
1807 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1808 const FunctionDecl* Def;
1809 if (FD->hasBody(Def))
1815 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
1816 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
1818 Attr *Attribute = *I;
1819 if (Attribute->getKind() == Kind)
1825 /// checkNewAttributesAfterDef - If we already have a definition, check that
1826 /// there are no new attributes in this declaration.
1827 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
1828 if (!New->hasAttrs())
1831 const Decl *Def = getDefinition(Old);
1832 if (!Def || Def == New)
1835 AttrVec &NewAttributes = New->getAttrs();
1836 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
1837 const Attr *NewAttribute = NewAttributes[I];
1838 if (hasAttribute(Def, NewAttribute->getKind())) {
1840 continue; // regular attr merging will take care of validating this.
1842 S.Diag(NewAttribute->getLocation(),
1843 diag::warn_attribute_precede_definition);
1844 S.Diag(Def->getLocation(), diag::note_previous_definition);
1845 NewAttributes.erase(NewAttributes.begin() + I);
1850 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
1851 void Sema::mergeDeclAttributes(Decl *New, Decl *Old,
1852 bool MergeDeprecation) {
1853 // attributes declared post-definition are currently ignored
1854 checkNewAttributesAfterDef(*this, New, Old);
1856 if (!Old->hasAttrs())
1859 bool foundAny = New->hasAttrs();
1861 // Ensure that any moving of objects within the allocated map is done before
1863 if (!foundAny) New->setAttrs(AttrVec());
1865 for (specific_attr_iterator<InheritableAttr>
1866 i = Old->specific_attr_begin<InheritableAttr>(),
1867 e = Old->specific_attr_end<InheritableAttr>();
1869 // Ignore deprecated/unavailable/availability attributes if requested.
1870 if (!MergeDeprecation &&
1871 (isa<DeprecatedAttr>(*i) ||
1872 isa<UnavailableAttr>(*i) ||
1873 isa<AvailabilityAttr>(*i)))
1876 if (mergeDeclAttribute(New, *i))
1880 if (!foundAny) New->dropAttrs();
1883 /// mergeParamDeclAttributes - Copy attributes from the old parameter
1885 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
1886 const ParmVarDecl *oldDecl,
1888 if (!oldDecl->hasAttrs())
1891 bool foundAny = newDecl->hasAttrs();
1893 // Ensure that any moving of objects within the allocated map is
1894 // done before we process them.
1895 if (!foundAny) newDecl->setAttrs(AttrVec());
1897 for (specific_attr_iterator<InheritableParamAttr>
1898 i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
1899 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
1900 if (!DeclHasAttr(newDecl, *i)) {
1901 InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C));
1902 newAttr->setInherited(true);
1903 newDecl->addAttr(newAttr);
1908 if (!foundAny) newDecl->dropAttrs();
1913 /// Used in MergeFunctionDecl to keep track of function parameters in
1915 struct GNUCompatibleParamWarning {
1916 ParmVarDecl *OldParm;
1917 ParmVarDecl *NewParm;
1918 QualType PromotedType;
1923 /// getSpecialMember - get the special member enum for a method.
1924 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
1925 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
1926 if (Ctor->isDefaultConstructor())
1927 return Sema::CXXDefaultConstructor;
1929 if (Ctor->isCopyConstructor())
1930 return Sema::CXXCopyConstructor;
1932 if (Ctor->isMoveConstructor())
1933 return Sema::CXXMoveConstructor;
1934 } else if (isa<CXXDestructorDecl>(MD)) {
1935 return Sema::CXXDestructor;
1936 } else if (MD->isCopyAssignmentOperator()) {
1937 return Sema::CXXCopyAssignment;
1938 } else if (MD->isMoveAssignmentOperator()) {
1939 return Sema::CXXMoveAssignment;
1942 return Sema::CXXInvalid;
1945 /// canRedefineFunction - checks if a function can be redefined. Currently,
1946 /// only extern inline functions can be redefined, and even then only in
1948 static bool canRedefineFunction(const FunctionDecl *FD,
1949 const LangOptions& LangOpts) {
1950 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
1951 !LangOpts.CPlusPlus &&
1952 FD->isInlineSpecified() &&
1953 FD->getStorageClass() == SC_Extern);
1956 /// Is the given calling convention the ABI default for the given
1958 static bool isABIDefaultCC(Sema &S, CallingConv CC, FunctionDecl *D) {
1959 CallingConv ABIDefaultCC;
1960 if (isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
1961 ABIDefaultCC = S.Context.getDefaultCXXMethodCallConv(D->isVariadic());
1963 // Free C function or a static method.
1964 ABIDefaultCC = (S.Context.getLangOpts().MRTD ? CC_X86StdCall : CC_C);
1966 return ABIDefaultCC == CC;
1969 /// MergeFunctionDecl - We just parsed a function 'New' from
1970 /// declarator D which has the same name and scope as a previous
1971 /// declaration 'Old'. Figure out how to resolve this situation,
1972 /// merging decls or emitting diagnostics as appropriate.
1974 /// In C++, New and Old must be declarations that are not
1975 /// overloaded. Use IsOverload to determine whether New and Old are
1976 /// overloaded, and to select the Old declaration that New should be
1979 /// Returns true if there was an error, false otherwise.
1980 bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S) {
1981 // Verify the old decl was also a function.
1982 FunctionDecl *Old = 0;
1983 if (FunctionTemplateDecl *OldFunctionTemplate
1984 = dyn_cast<FunctionTemplateDecl>(OldD))
1985 Old = OldFunctionTemplate->getTemplatedDecl();
1987 Old = dyn_cast<FunctionDecl>(OldD);
1989 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
1990 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
1991 Diag(Shadow->getTargetDecl()->getLocation(),
1992 diag::note_using_decl_target);
1993 Diag(Shadow->getUsingDecl()->getLocation(),
1994 diag::note_using_decl) << 0;
1998 Diag(New->getLocation(), diag::err_redefinition_different_kind)
1999 << New->getDeclName();
2000 Diag(OldD->getLocation(), diag::note_previous_definition);
2004 // Determine whether the previous declaration was a definition,
2005 // implicit declaration, or a declaration.
2006 diag::kind PrevDiag;
2007 if (Old->isThisDeclarationADefinition())
2008 PrevDiag = diag::note_previous_definition;
2009 else if (Old->isImplicit())
2010 PrevDiag = diag::note_previous_implicit_declaration;
2012 PrevDiag = diag::note_previous_declaration;
2014 QualType OldQType = Context.getCanonicalType(Old->getType());
2015 QualType NewQType = Context.getCanonicalType(New->getType());
2017 // Don't complain about this if we're in GNU89 mode and the old function
2018 // is an extern inline function.
2019 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2020 New->getStorageClass() == SC_Static &&
2021 Old->getStorageClass() != SC_Static &&
2022 !canRedefineFunction(Old, getLangOpts())) {
2023 if (getLangOpts().MicrosoftExt) {
2024 Diag(New->getLocation(), diag::warn_static_non_static) << New;
2025 Diag(Old->getLocation(), PrevDiag);
2027 Diag(New->getLocation(), diag::err_static_non_static) << New;
2028 Diag(Old->getLocation(), PrevDiag);
2033 // If a function is first declared with a calling convention, but is
2034 // later declared or defined without one, the second decl assumes the
2035 // calling convention of the first.
2037 // It's OK if a function is first declared without a calling convention,
2038 // but is later declared or defined with the default calling convention.
2040 // For the new decl, we have to look at the NON-canonical type to tell the
2041 // difference between a function that really doesn't have a calling
2042 // convention and one that is declared cdecl. That's because in
2043 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
2044 // because it is the default calling convention.
2046 // Note also that we DO NOT return at this point, because we still have
2047 // other tests to run.
2048 const FunctionType *OldType = cast<FunctionType>(OldQType);
2049 const FunctionType *NewType = New->getType()->getAs<FunctionType>();
2050 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2051 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2052 bool RequiresAdjustment = false;
2053 if (OldTypeInfo.getCC() == NewTypeInfo.getCC()) {
2054 // Fast path: nothing to do.
2056 // Inherit the CC from the previous declaration if it was specified
2057 // there but not here.
2058 } else if (NewTypeInfo.getCC() == CC_Default) {
2059 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2060 RequiresAdjustment = true;
2062 // Don't complain about mismatches when the default CC is
2063 // effectively the same as the explict one.
2064 } else if (OldTypeInfo.getCC() == CC_Default &&
2065 isABIDefaultCC(*this, NewTypeInfo.getCC(), New)) {
2066 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2067 RequiresAdjustment = true;
2069 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
2070 NewTypeInfo.getCC())) {
2071 // Calling conventions really aren't compatible, so complain.
2072 Diag(New->getLocation(), diag::err_cconv_change)
2073 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2074 << (OldTypeInfo.getCC() == CC_Default)
2075 << (OldTypeInfo.getCC() == CC_Default ? "" :
2076 FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
2077 Diag(Old->getLocation(), diag::note_previous_declaration);
2081 // FIXME: diagnose the other way around?
2082 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2083 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2084 RequiresAdjustment = true;
2087 // Merge regparm attribute.
2088 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2089 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2090 if (NewTypeInfo.getHasRegParm()) {
2091 Diag(New->getLocation(), diag::err_regparm_mismatch)
2092 << NewType->getRegParmType()
2093 << OldType->getRegParmType();
2094 Diag(Old->getLocation(), diag::note_previous_declaration);
2098 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2099 RequiresAdjustment = true;
2102 // Merge ns_returns_retained attribute.
2103 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2104 if (NewTypeInfo.getProducesResult()) {
2105 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2106 Diag(Old->getLocation(), diag::note_previous_declaration);
2110 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2111 RequiresAdjustment = true;
2114 if (RequiresAdjustment) {
2115 NewType = Context.adjustFunctionType(NewType, NewTypeInfo);
2116 New->setType(QualType(NewType, 0));
2117 NewQType = Context.getCanonicalType(New->getType());
2120 if (getLangOpts().CPlusPlus) {
2122 // Certain function declarations cannot be overloaded:
2123 // -- Function declarations that differ only in the return type
2124 // cannot be overloaded.
2125 QualType OldReturnType = OldType->getResultType();
2126 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
2128 if (OldReturnType != NewReturnType) {
2129 if (NewReturnType->isObjCObjectPointerType()
2130 && OldReturnType->isObjCObjectPointerType())
2131 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2132 if (ResQT.isNull()) {
2133 if (New->isCXXClassMember() && New->isOutOfLine())
2134 Diag(New->getLocation(),
2135 diag::err_member_def_does_not_match_ret_type) << New;
2137 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
2138 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2145 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
2146 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
2147 if (OldMethod && NewMethod) {
2148 // Preserve triviality.
2149 NewMethod->setTrivial(OldMethod->isTrivial());
2151 // MSVC allows explicit template specialization at class scope:
2152 // 2 CXMethodDecls referring to the same function will be injected.
2153 // We don't want a redeclartion error.
2154 bool IsClassScopeExplicitSpecialization =
2155 OldMethod->isFunctionTemplateSpecialization() &&
2156 NewMethod->isFunctionTemplateSpecialization();
2157 bool isFriend = NewMethod->getFriendObjectKind();
2159 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2160 !IsClassScopeExplicitSpecialization) {
2161 // -- Member function declarations with the same name and the
2162 // same parameter types cannot be overloaded if any of them
2163 // is a static member function declaration.
2164 if (OldMethod->isStatic() || NewMethod->isStatic()) {
2165 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2166 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2170 // C++ [class.mem]p1:
2171 // [...] A member shall not be declared twice in the
2172 // member-specification, except that a nested class or member
2173 // class template can be declared and then later defined.
2174 if (ActiveTemplateInstantiations.empty()) {
2176 if (isa<CXXConstructorDecl>(OldMethod))
2177 NewDiag = diag::err_constructor_redeclared;
2178 else if (isa<CXXDestructorDecl>(NewMethod))
2179 NewDiag = diag::err_destructor_redeclared;
2180 else if (isa<CXXConversionDecl>(NewMethod))
2181 NewDiag = diag::err_conv_function_redeclared;
2183 NewDiag = diag::err_member_redeclared;
2185 Diag(New->getLocation(), NewDiag);
2187 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2188 << New << New->getType();
2190 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2192 // Complain if this is an explicit declaration of a special
2193 // member that was initially declared implicitly.
2195 // As an exception, it's okay to befriend such methods in order
2196 // to permit the implicit constructor/destructor/operator calls.
2197 } else if (OldMethod->isImplicit()) {
2199 NewMethod->setImplicit();
2201 Diag(NewMethod->getLocation(),
2202 diag::err_definition_of_implicitly_declared_member)
2203 << New << getSpecialMember(OldMethod);
2206 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2207 Diag(NewMethod->getLocation(),
2208 diag::err_definition_of_explicitly_defaulted_member)
2209 << getSpecialMember(OldMethod);
2215 // All declarations for a function shall agree exactly in both the
2216 // return type and the parameter-type-list.
2217 // We also want to respect all the extended bits except noreturn.
2219 // noreturn should now match unless the old type info didn't have it.
2220 QualType OldQTypeForComparison = OldQType;
2221 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2222 assert(OldQType == QualType(OldType, 0));
2223 const FunctionType *OldTypeForComparison
2224 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2225 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2226 assert(OldQTypeForComparison.isCanonical());
2229 if (OldQTypeForComparison == NewQType)
2230 return MergeCompatibleFunctionDecls(New, Old, S);
2232 // Fall through for conflicting redeclarations and redefinitions.
2235 // C: Function types need to be compatible, not identical. This handles
2236 // duplicate function decls like "void f(int); void f(enum X);" properly.
2237 if (!getLangOpts().CPlusPlus &&
2238 Context.typesAreCompatible(OldQType, NewQType)) {
2239 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2240 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
2241 const FunctionProtoType *OldProto = 0;
2242 if (isa<FunctionNoProtoType>(NewFuncType) &&
2243 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
2244 // The old declaration provided a function prototype, but the
2245 // new declaration does not. Merge in the prototype.
2246 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
2247 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
2248 OldProto->arg_type_end());
2249 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
2250 ParamTypes.data(), ParamTypes.size(),
2251 OldProto->getExtProtoInfo());
2252 New->setType(NewQType);
2253 New->setHasInheritedPrototype();
2255 // Synthesize a parameter for each argument type.
2256 SmallVector<ParmVarDecl*, 16> Params;
2257 for (FunctionProtoType::arg_type_iterator
2258 ParamType = OldProto->arg_type_begin(),
2259 ParamEnd = OldProto->arg_type_end();
2260 ParamType != ParamEnd; ++ParamType) {
2261 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
2263 SourceLocation(), 0,
2264 *ParamType, /*TInfo=*/0,
2267 Param->setScopeInfo(0, Params.size());
2268 Param->setImplicit();
2269 Params.push_back(Param);
2272 New->setParams(Params);
2275 return MergeCompatibleFunctionDecls(New, Old, S);
2278 // GNU C permits a K&R definition to follow a prototype declaration
2279 // if the declared types of the parameters in the K&R definition
2280 // match the types in the prototype declaration, even when the
2281 // promoted types of the parameters from the K&R definition differ
2282 // from the types in the prototype. GCC then keeps the types from
2285 // If a variadic prototype is followed by a non-variadic K&R definition,
2286 // the K&R definition becomes variadic. This is sort of an edge case, but
2287 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2289 if (!getLangOpts().CPlusPlus &&
2290 Old->hasPrototype() && !New->hasPrototype() &&
2291 New->getType()->getAs<FunctionProtoType>() &&
2292 Old->getNumParams() == New->getNumParams()) {
2293 SmallVector<QualType, 16> ArgTypes;
2294 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
2295 const FunctionProtoType *OldProto
2296 = Old->getType()->getAs<FunctionProtoType>();
2297 const FunctionProtoType *NewProto
2298 = New->getType()->getAs<FunctionProtoType>();
2300 // Determine whether this is the GNU C extension.
2301 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2302 NewProto->getResultType());
2303 bool LooseCompatible = !MergedReturn.isNull();
2304 for (unsigned Idx = 0, End = Old->getNumParams();
2305 LooseCompatible && Idx != End; ++Idx) {
2306 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2307 ParmVarDecl *NewParm = New->getParamDecl(Idx);
2308 if (Context.typesAreCompatible(OldParm->getType(),
2309 NewProto->getArgType(Idx))) {
2310 ArgTypes.push_back(NewParm->getType());
2311 } else if (Context.typesAreCompatible(OldParm->getType(),
2313 /*CompareUnqualified=*/true)) {
2314 GNUCompatibleParamWarning Warn
2315 = { OldParm, NewParm, NewProto->getArgType(Idx) };
2316 Warnings.push_back(Warn);
2317 ArgTypes.push_back(NewParm->getType());
2319 LooseCompatible = false;
2322 if (LooseCompatible) {
2323 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2324 Diag(Warnings[Warn].NewParm->getLocation(),
2325 diag::ext_param_promoted_not_compatible_with_prototype)
2326 << Warnings[Warn].PromotedType
2327 << Warnings[Warn].OldParm->getType();
2328 if (Warnings[Warn].OldParm->getLocation().isValid())
2329 Diag(Warnings[Warn].OldParm->getLocation(),
2330 diag::note_previous_declaration);
2333 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
2335 OldProto->getExtProtoInfo()));
2336 return MergeCompatibleFunctionDecls(New, Old, S);
2339 // Fall through to diagnose conflicting types.
2342 // A function that has already been declared has been redeclared or defined
2343 // with a different type- show appropriate diagnostic
2344 if (unsigned BuiltinID = Old->getBuiltinID()) {
2345 // The user has declared a builtin function with an incompatible
2347 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2348 // The function the user is redeclaring is a library-defined
2349 // function like 'malloc' or 'printf'. Warn about the
2350 // redeclaration, then pretend that we don't know about this
2351 // library built-in.
2352 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2353 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2354 << Old << Old->getType();
2355 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2356 Old->setInvalidDecl();
2360 PrevDiag = diag::note_previous_builtin_declaration;
2363 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
2364 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2368 /// \brief Completes the merge of two function declarations that are
2369 /// known to be compatible.
2371 /// This routine handles the merging of attributes and other
2372 /// properties of function declarations form the old declaration to
2373 /// the new declaration, once we know that New is in fact a
2374 /// redeclaration of Old.
2377 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2379 // Merge the attributes
2380 mergeDeclAttributes(New, Old);
2382 // Merge the storage class.
2383 if (Old->getStorageClass() != SC_Extern &&
2384 Old->getStorageClass() != SC_None)
2385 New->setStorageClass(Old->getStorageClass());
2387 // Merge "pure" flag.
2391 // Merge attributes from the parameters. These can mismatch with K&R
2393 if (New->getNumParams() == Old->getNumParams())
2394 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2395 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
2398 if (getLangOpts().CPlusPlus)
2399 return MergeCXXFunctionDecl(New, Old, S);
2405 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
2406 ObjCMethodDecl *oldMethod) {
2408 // Merge the attributes, including deprecated/unavailable
2409 mergeDeclAttributes(newMethod, oldMethod, /* mergeDeprecation */true);
2411 // Merge attributes from the parameters.
2412 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2413 oe = oldMethod->param_end();
2414 for (ObjCMethodDecl::param_iterator
2415 ni = newMethod->param_begin(), ne = newMethod->param_end();
2416 ni != ne && oi != oe; ++ni, ++oi)
2417 mergeParamDeclAttributes(*ni, *oi, Context);
2419 CheckObjCMethodOverride(newMethod, oldMethod, true);
2422 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2423 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
2424 /// emitting diagnostics as appropriate.
2426 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
2427 /// to here in AddInitializerToDecl. We can't check them before the initializer
2429 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) {
2430 if (New->isInvalidDecl() || Old->isInvalidDecl())
2434 if (getLangOpts().CPlusPlus) {
2435 AutoType *AT = New->getType()->getContainedAutoType();
2436 if (AT && !AT->isDeduced()) {
2437 // We don't know what the new type is until the initializer is attached.
2439 } else if (Context.hasSameType(New->getType(), Old->getType())) {
2440 // These could still be something that needs exception specs checked.
2441 return MergeVarDeclExceptionSpecs(New, Old);
2443 // C++ [basic.link]p10:
2444 // [...] the types specified by all declarations referring to a given
2445 // object or function shall be identical, except that declarations for an
2446 // array object can specify array types that differ by the presence or
2447 // absence of a major array bound (8.3.4).
2448 else if (Old->getType()->isIncompleteArrayType() &&
2449 New->getType()->isArrayType()) {
2450 CanQual<ArrayType> OldArray
2451 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2452 CanQual<ArrayType> NewArray
2453 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2454 if (OldArray->getElementType() == NewArray->getElementType())
2455 MergedT = New->getType();
2456 } else if (Old->getType()->isArrayType() &&
2457 New->getType()->isIncompleteArrayType()) {
2458 CanQual<ArrayType> OldArray
2459 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2460 CanQual<ArrayType> NewArray
2461 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2462 if (OldArray->getElementType() == NewArray->getElementType())
2463 MergedT = Old->getType();
2464 } else if (New->getType()->isObjCObjectPointerType()
2465 && Old->getType()->isObjCObjectPointerType()) {
2466 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2470 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2472 if (MergedT.isNull()) {
2473 Diag(New->getLocation(), diag::err_redefinition_different_type)
2474 << New->getDeclName() << New->getType() << Old->getType();
2475 Diag(Old->getLocation(), diag::note_previous_definition);
2476 return New->setInvalidDecl();
2478 New->setType(MergedT);
2481 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
2482 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
2483 /// situation, merging decls or emitting diagnostics as appropriate.
2485 /// Tentative definition rules (C99 6.9.2p2) are checked by
2486 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
2487 /// definitions here, since the initializer hasn't been attached.
2489 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
2490 // If the new decl is already invalid, don't do any other checking.
2491 if (New->isInvalidDecl())
2494 // Verify the old decl was also a variable.
2496 if (!Previous.isSingleResult() ||
2497 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
2498 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2499 << New->getDeclName();
2500 Diag(Previous.getRepresentativeDecl()->getLocation(),
2501 diag::note_previous_definition);
2502 return New->setInvalidDecl();
2505 // C++ [class.mem]p1:
2506 // A member shall not be declared twice in the member-specification [...]
2508 // Here, we need only consider static data members.
2509 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
2510 Diag(New->getLocation(), diag::err_duplicate_member)
2511 << New->getIdentifier();
2512 Diag(Old->getLocation(), diag::note_previous_declaration);
2513 New->setInvalidDecl();
2516 mergeDeclAttributes(New, Old);
2517 // Warn if an already-declared variable is made a weak_import in a subsequent
2519 if (New->getAttr<WeakImportAttr>() &&
2520 Old->getStorageClass() == SC_None &&
2521 !Old->getAttr<WeakImportAttr>()) {
2522 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
2523 Diag(Old->getLocation(), diag::note_previous_definition);
2524 // Remove weak_import attribute on new declaration.
2525 New->dropAttr<WeakImportAttr>();
2529 MergeVarDeclTypes(New, Old);
2530 if (New->isInvalidDecl())
2533 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
2534 if (New->getStorageClass() == SC_Static &&
2535 (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) {
2536 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
2537 Diag(Old->getLocation(), diag::note_previous_definition);
2538 return New->setInvalidDecl();
2541 // For an identifier declared with the storage-class specifier
2542 // extern in a scope in which a prior declaration of that
2543 // identifier is visible,23) if the prior declaration specifies
2544 // internal or external linkage, the linkage of the identifier at
2545 // the later declaration is the same as the linkage specified at
2546 // the prior declaration. If no prior declaration is visible, or
2547 // if the prior declaration specifies no linkage, then the
2548 // identifier has external linkage.
2549 if (New->hasExternalStorage() && Old->hasLinkage())
2551 else if (New->getStorageClass() != SC_Static &&
2552 Old->getStorageClass() == SC_Static) {
2553 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
2554 Diag(Old->getLocation(), diag::note_previous_definition);
2555 return New->setInvalidDecl();
2558 // Check if extern is followed by non-extern and vice-versa.
2559 if (New->hasExternalStorage() &&
2560 !Old->hasLinkage() && Old->isLocalVarDecl()) {
2561 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
2562 Diag(Old->getLocation(), diag::note_previous_definition);
2563 return New->setInvalidDecl();
2565 if (Old->hasExternalStorage() &&
2566 !New->hasLinkage() && New->isLocalVarDecl()) {
2567 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
2568 Diag(Old->getLocation(), diag::note_previous_definition);
2569 return New->setInvalidDecl();
2572 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
2574 // FIXME: The test for external storage here seems wrong? We still
2575 // need to check for mismatches.
2576 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
2577 // Don't complain about out-of-line definitions of static members.
2578 !(Old->getLexicalDeclContext()->isRecord() &&
2579 !New->getLexicalDeclContext()->isRecord())) {
2580 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
2581 Diag(Old->getLocation(), diag::note_previous_definition);
2582 return New->setInvalidDecl();
2585 if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
2586 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
2587 Diag(Old->getLocation(), diag::note_previous_definition);
2588 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
2589 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
2590 Diag(Old->getLocation(), diag::note_previous_definition);
2593 // C++ doesn't have tentative definitions, so go right ahead and check here.
2595 if (getLangOpts().CPlusPlus &&
2596 New->isThisDeclarationADefinition() == VarDecl::Definition &&
2597 (Def = Old->getDefinition())) {
2598 Diag(New->getLocation(), diag::err_redefinition)
2599 << New->getDeclName();
2600 Diag(Def->getLocation(), diag::note_previous_definition);
2601 New->setInvalidDecl();
2605 // For an identifier declared with the storage-class specifier extern in a
2606 // scope in which a prior declaration of that identifier is visible, if
2607 // the prior declaration specifies internal or external linkage, the linkage
2608 // of the identifier at the later declaration is the same as the linkage
2609 // specified at the prior declaration.
2610 // FIXME. revisit this code.
2611 if (New->hasExternalStorage() &&
2612 Old->getLinkage() == InternalLinkage &&
2613 New->getDeclContext() == Old->getDeclContext())
2614 New->setStorageClass(Old->getStorageClass());
2616 // Keep a chain of previous declarations.
2617 New->setPreviousDeclaration(Old);
2619 // Inherit access appropriately.
2620 New->setAccess(Old->getAccess());
2623 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2624 /// no declarator (e.g. "struct foo;") is parsed.
2625 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2627 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
2630 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2631 /// no declarator (e.g. "struct foo;") is parsed. It also accopts template
2632 /// parameters to cope with template friend declarations.
2633 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2635 MultiTemplateParamsArg TemplateParams) {
2638 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
2639 DS.getTypeSpecType() == DeclSpec::TST_struct ||
2640 DS.getTypeSpecType() == DeclSpec::TST_interface ||
2641 DS.getTypeSpecType() == DeclSpec::TST_union ||
2642 DS.getTypeSpecType() == DeclSpec::TST_enum) {
2643 TagD = DS.getRepAsDecl();
2645 if (!TagD) // We probably had an error
2648 // Note that the above type specs guarantee that the
2649 // type rep is a Decl, whereas in many of the others
2651 if (isa<TagDecl>(TagD))
2652 Tag = cast<TagDecl>(TagD);
2653 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
2654 Tag = CTD->getTemplatedDecl();
2658 Tag->setFreeStanding();
2659 if (Tag->isInvalidDecl())
2663 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
2664 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
2665 // or incomplete types shall not be restrict-qualified."
2666 if (TypeQuals & DeclSpec::TQ_restrict)
2667 Diag(DS.getRestrictSpecLoc(),
2668 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
2669 << DS.getSourceRange();
2672 if (DS.isConstexprSpecified()) {
2673 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
2674 // and definitions of functions and variables.
2676 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
2677 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
2678 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
2679 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
2680 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
2682 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
2683 // Don't emit warnings after this error.
2687 if (DS.isFriendSpecified()) {
2688 // If we're dealing with a decl but not a TagDecl, assume that
2689 // whatever routines created it handled the friendship aspect.
2692 return ActOnFriendTypeDecl(S, DS, TemplateParams);
2695 // Track whether we warned about the fact that there aren't any
2697 bool emittedWarning = false;
2699 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
2700 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
2701 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
2702 if (getLangOpts().CPlusPlus ||
2703 Record->getDeclContext()->isRecord())
2704 return BuildAnonymousStructOrUnion(S, DS, AS, Record);
2706 Diag(DS.getLocStart(), diag::ext_no_declarators)
2707 << DS.getSourceRange();
2708 emittedWarning = true;
2712 // Check for Microsoft C extension: anonymous struct.
2713 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
2714 CurContext->isRecord() &&
2715 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
2716 // Handle 2 kinds of anonymous struct:
2719 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
2720 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
2721 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
2722 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
2723 DS.getRepAsType().get()->isStructureType())) {
2724 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
2725 << DS.getSourceRange();
2726 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
2730 if (getLangOpts().CPlusPlus &&
2731 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
2732 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
2733 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
2734 !Enum->getIdentifier() && !Enum->isInvalidDecl()) {
2735 Diag(Enum->getLocation(), diag::ext_no_declarators)
2736 << DS.getSourceRange();
2737 emittedWarning = true;
2740 // Skip all the checks below if we have a type error.
2741 if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD;
2743 if (!DS.isMissingDeclaratorOk()) {
2744 // Warn about typedefs of enums without names, since this is an
2745 // extension in both Microsoft and GNU.
2746 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
2747 Tag && isa<EnumDecl>(Tag)) {
2748 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
2749 << DS.getSourceRange();
2753 Diag(DS.getLocStart(), diag::ext_no_declarators)
2754 << DS.getSourceRange();
2755 emittedWarning = true;
2758 // We're going to complain about a bunch of spurious specifiers;
2759 // only do this if we're declaring a tag, because otherwise we
2760 // should be getting diag::ext_no_declarators.
2761 if (emittedWarning || (TagD && TagD->isInvalidDecl()))
2764 // Note that a linkage-specification sets a storage class, but
2765 // 'extern "C" struct foo;' is actually valid and not theoretically
2767 if (DeclSpec::SCS scs = DS.getStorageClassSpec())
2768 if (!DS.isExternInLinkageSpec())
2769 Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier)
2770 << DeclSpec::getSpecifierName(scs);
2772 if (DS.isThreadSpecified())
2773 Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread";
2774 if (DS.getTypeQualifiers()) {
2775 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2776 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const";
2777 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2778 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile";
2779 // Restrict is covered above.
2781 if (DS.isInlineSpecified())
2782 Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline";
2783 if (DS.isVirtualSpecified())
2784 Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual";
2785 if (DS.isExplicitSpecified())
2786 Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit";
2788 if (DS.isModulePrivateSpecified() &&
2789 Tag && Tag->getDeclContext()->isFunctionOrMethod())
2790 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
2791 << Tag->getTagKind()
2792 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
2794 // Warn about ignored type attributes, for example:
2795 // __attribute__((aligned)) struct A;
2796 // Attributes should be placed after tag to apply to type declaration.
2797 if (!DS.getAttributes().empty()) {
2798 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
2799 if (TypeSpecType == DeclSpec::TST_class ||
2800 TypeSpecType == DeclSpec::TST_struct ||
2801 TypeSpecType == DeclSpec::TST_interface ||
2802 TypeSpecType == DeclSpec::TST_union ||
2803 TypeSpecType == DeclSpec::TST_enum) {
2804 AttributeList* attrs = DS.getAttributes().getList();
2806 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
2808 << (TypeSpecType == DeclSpec::TST_class ? 0 :
2809 TypeSpecType == DeclSpec::TST_struct ? 1 :
2810 TypeSpecType == DeclSpec::TST_union ? 2 :
2811 TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
2812 attrs = attrs->getNext();
2817 ActOnDocumentableDecl(TagD);
2822 /// We are trying to inject an anonymous member into the given scope;
2823 /// check if there's an existing declaration that can't be overloaded.
2825 /// \return true if this is a forbidden redeclaration
2826 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
2829 DeclarationName Name,
2830 SourceLocation NameLoc,
2831 unsigned diagnostic) {
2832 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
2833 Sema::ForRedeclaration);
2834 if (!SemaRef.LookupName(R, S)) return false;
2836 if (R.getAsSingle<TagDecl>())
2839 // Pick a representative declaration.
2840 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
2841 assert(PrevDecl && "Expected a non-null Decl");
2843 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
2846 SemaRef.Diag(NameLoc, diagnostic) << Name;
2847 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
2852 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
2853 /// anonymous struct or union AnonRecord into the owning context Owner
2854 /// and scope S. This routine will be invoked just after we realize
2855 /// that an unnamed union or struct is actually an anonymous union or
2862 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
2863 /// // f into the surrounding scope.x
2866 /// This routine is recursive, injecting the names of nested anonymous
2867 /// structs/unions into the owning context and scope as well.
2868 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
2870 RecordDecl *AnonRecord,
2872 SmallVector<NamedDecl*, 2> &Chaining,
2873 bool MSAnonStruct) {
2875 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
2876 : diag::err_anonymous_struct_member_redecl;
2878 bool Invalid = false;
2880 // Look every FieldDecl and IndirectFieldDecl with a name.
2881 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
2882 DEnd = AnonRecord->decls_end();
2884 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
2885 cast<NamedDecl>(*D)->getDeclName()) {
2886 ValueDecl *VD = cast<ValueDecl>(*D);
2887 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
2888 VD->getLocation(), diagKind)) {
2889 // C++ [class.union]p2:
2890 // The names of the members of an anonymous union shall be
2891 // distinct from the names of any other entity in the
2892 // scope in which the anonymous union is declared.
2895 // C++ [class.union]p2:
2896 // For the purpose of name lookup, after the anonymous union
2897 // definition, the members of the anonymous union are
2898 // considered to have been defined in the scope in which the
2899 // anonymous union is declared.
2900 unsigned OldChainingSize = Chaining.size();
2901 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
2902 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
2903 PE = IF->chain_end(); PI != PE; ++PI)
2904 Chaining.push_back(*PI);
2906 Chaining.push_back(VD);
2908 assert(Chaining.size() >= 2);
2909 NamedDecl **NamedChain =
2910 new (SemaRef.Context)NamedDecl*[Chaining.size()];
2911 for (unsigned i = 0; i < Chaining.size(); i++)
2912 NamedChain[i] = Chaining[i];
2914 IndirectFieldDecl* IndirectField =
2915 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
2916 VD->getIdentifier(), VD->getType(),
2917 NamedChain, Chaining.size());
2919 IndirectField->setAccess(AS);
2920 IndirectField->setImplicit();
2921 SemaRef.PushOnScopeChains(IndirectField, S);
2923 // That includes picking up the appropriate access specifier.
2924 if (AS != AS_none) IndirectField->setAccess(AS);
2926 Chaining.resize(OldChainingSize);
2934 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
2935 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
2936 /// illegal input values are mapped to SC_None.
2938 StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
2939 switch (StorageClassSpec) {
2940 case DeclSpec::SCS_unspecified: return SC_None;
2941 case DeclSpec::SCS_extern: return SC_Extern;
2942 case DeclSpec::SCS_static: return SC_Static;
2943 case DeclSpec::SCS_auto: return SC_Auto;
2944 case DeclSpec::SCS_register: return SC_Register;
2945 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
2946 // Illegal SCSs map to None: error reporting is up to the caller.
2947 case DeclSpec::SCS_mutable: // Fall through.
2948 case DeclSpec::SCS_typedef: return SC_None;
2950 llvm_unreachable("unknown storage class specifier");
2953 /// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
2954 /// a StorageClass. Any error reporting is up to the caller:
2955 /// illegal input values are mapped to SC_None.
2957 StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
2958 switch (StorageClassSpec) {
2959 case DeclSpec::SCS_unspecified: return SC_None;
2960 case DeclSpec::SCS_extern: return SC_Extern;
2961 case DeclSpec::SCS_static: return SC_Static;
2962 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
2963 // Illegal SCSs map to None: error reporting is up to the caller.
2964 case DeclSpec::SCS_auto: // Fall through.
2965 case DeclSpec::SCS_mutable: // Fall through.
2966 case DeclSpec::SCS_register: // Fall through.
2967 case DeclSpec::SCS_typedef: return SC_None;
2969 llvm_unreachable("unknown storage class specifier");
2972 /// BuildAnonymousStructOrUnion - Handle the declaration of an
2973 /// anonymous structure or union. Anonymous unions are a C++ feature
2974 /// (C++ [class.union]) and a C11 feature; anonymous structures
2975 /// are a C11 feature and GNU C++ extension.
2976 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2978 RecordDecl *Record) {
2979 DeclContext *Owner = Record->getDeclContext();
2981 // Diagnose whether this anonymous struct/union is an extension.
2982 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
2983 Diag(Record->getLocation(), diag::ext_anonymous_union);
2984 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
2985 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
2986 else if (!Record->isUnion() && !getLangOpts().C11)
2987 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
2989 // C and C++ require different kinds of checks for anonymous
2991 bool Invalid = false;
2992 if (getLangOpts().CPlusPlus) {
2993 const char* PrevSpec = 0;
2995 if (Record->isUnion()) {
2996 // C++ [class.union]p6:
2997 // Anonymous unions declared in a named namespace or in the
2998 // global namespace shall be declared static.
2999 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3000 (isa<TranslationUnitDecl>(Owner) ||
3001 (isa<NamespaceDecl>(Owner) &&
3002 cast<NamespaceDecl>(Owner)->getDeclName()))) {
3003 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3004 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
3006 // Recover by adding 'static'.
3007 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3010 // C++ [class.union]p6:
3011 // A storage class is not allowed in a declaration of an
3012 // anonymous union in a class scope.
3013 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3014 isa<RecordDecl>(Owner)) {
3015 Diag(DS.getStorageClassSpecLoc(),
3016 diag::err_anonymous_union_with_storage_spec)
3017 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3019 // Recover by removing the storage specifier.
3020 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3026 // Ignore const/volatile/restrict qualifiers.
3027 if (DS.getTypeQualifiers()) {
3028 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3029 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
3030 << Record->isUnion() << 0
3031 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3032 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3033 Diag(DS.getVolatileSpecLoc(),
3034 diag::ext_anonymous_struct_union_qualified)
3035 << Record->isUnion() << 1
3036 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3037 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
3038 Diag(DS.getRestrictSpecLoc(),
3039 diag::ext_anonymous_struct_union_qualified)
3040 << Record->isUnion() << 2
3041 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
3043 DS.ClearTypeQualifiers();
3046 // C++ [class.union]p2:
3047 // The member-specification of an anonymous union shall only
3048 // define non-static data members. [Note: nested types and
3049 // functions cannot be declared within an anonymous union. ]
3050 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
3051 MemEnd = Record->decls_end();
3052 Mem != MemEnd; ++Mem) {
3053 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
3054 // C++ [class.union]p3:
3055 // An anonymous union shall not have private or protected
3056 // members (clause 11).
3057 assert(FD->getAccess() != AS_none);
3058 if (FD->getAccess() != AS_public) {
3059 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3060 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3064 // C++ [class.union]p1
3065 // An object of a class with a non-trivial constructor, a non-trivial
3066 // copy constructor, a non-trivial destructor, or a non-trivial copy
3067 // assignment operator cannot be a member of a union, nor can an
3068 // array of such objects.
3069 if (CheckNontrivialField(FD))
3071 } else if ((*Mem)->isImplicit()) {
3072 // Any implicit members are fine.
3073 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
3074 // This is a type that showed up in an
3075 // elaborated-type-specifier inside the anonymous struct or
3076 // union, but which actually declares a type outside of the
3077 // anonymous struct or union. It's okay.
3078 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
3079 if (!MemRecord->isAnonymousStructOrUnion() &&
3080 MemRecord->getDeclName()) {
3081 // Visual C++ allows type definition in anonymous struct or union.
3082 if (getLangOpts().MicrosoftExt)
3083 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3084 << (int)Record->isUnion();
3086 // This is a nested type declaration.
3087 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3088 << (int)Record->isUnion();
3092 } else if (isa<AccessSpecDecl>(*Mem)) {
3093 // Any access specifier is fine.
3095 // We have something that isn't a non-static data
3096 // member. Complain about it.
3097 unsigned DK = diag::err_anonymous_record_bad_member;
3098 if (isa<TypeDecl>(*Mem))
3099 DK = diag::err_anonymous_record_with_type;
3100 else if (isa<FunctionDecl>(*Mem))
3101 DK = diag::err_anonymous_record_with_function;
3102 else if (isa<VarDecl>(*Mem))
3103 DK = diag::err_anonymous_record_with_static;
3105 // Visual C++ allows type definition in anonymous struct or union.
3106 if (getLangOpts().MicrosoftExt &&
3107 DK == diag::err_anonymous_record_with_type)
3108 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
3109 << (int)Record->isUnion();
3111 Diag((*Mem)->getLocation(), DK)
3112 << (int)Record->isUnion();
3119 if (!Record->isUnion() && !Owner->isRecord()) {
3120 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
3121 << (int)getLangOpts().CPlusPlus;
3125 // Mock up a declarator.
3126 Declarator Dc(DS, Declarator::MemberContext);
3127 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3128 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
3130 // Create a declaration for this anonymous struct/union.
3131 NamedDecl *Anon = 0;
3132 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
3133 Anon = FieldDecl::Create(Context, OwningClass,
3135 Record->getLocation(),
3136 /*IdentifierInfo=*/0,
3137 Context.getTypeDeclType(Record),
3139 /*BitWidth=*/0, /*Mutable=*/false,
3140 /*InitStyle=*/ICIS_NoInit);
3141 Anon->setAccess(AS);
3142 if (getLangOpts().CPlusPlus)
3143 FieldCollector->Add(cast<FieldDecl>(Anon));
3145 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
3146 assert(SCSpec != DeclSpec::SCS_typedef &&
3147 "Parser allowed 'typedef' as storage class VarDecl.");
3148 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
3149 if (SCSpec == DeclSpec::SCS_mutable) {
3150 // mutable can only appear on non-static class members, so it's always
3152 Diag(Record->getLocation(), diag::err_mutable_nonmember);
3156 SCSpec = DS.getStorageClassSpecAsWritten();
3157 VarDecl::StorageClass SCAsWritten
3158 = StorageClassSpecToVarDeclStorageClass(SCSpec);
3160 Anon = VarDecl::Create(Context, Owner,
3162 Record->getLocation(), /*IdentifierInfo=*/0,
3163 Context.getTypeDeclType(Record),
3164 TInfo, SC, SCAsWritten);
3166 // Default-initialize the implicit variable. This initialization will be
3167 // trivial in almost all cases, except if a union member has an in-class
3169 // union { int n = 0; };
3170 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
3172 Anon->setImplicit();
3174 // Add the anonymous struct/union object to the current
3175 // context. We'll be referencing this object when we refer to one of
3177 Owner->addDecl(Anon);
3179 // Inject the members of the anonymous struct/union into the owning
3180 // context and into the identifier resolver chain for name lookup
3182 SmallVector<NamedDecl*, 2> Chain;
3183 Chain.push_back(Anon);
3185 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3189 // Mark this as an anonymous struct/union type. Note that we do not
3190 // do this until after we have already checked and injected the
3191 // members of this anonymous struct/union type, because otherwise
3192 // the members could be injected twice: once by DeclContext when it
3193 // builds its lookup table, and once by
3194 // InjectAnonymousStructOrUnionMembers.
3195 Record->setAnonymousStructOrUnion(true);
3198 Anon->setInvalidDecl();
3203 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3204 /// Microsoft C anonymous structure.
3205 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3208 /// struct A { int a; };
3209 /// struct B { struct A; int b; };
3216 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3217 RecordDecl *Record) {
3219 // If there is no Record, get the record via the typedef.
3221 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3223 // Mock up a declarator.
3224 Declarator Dc(DS, Declarator::TypeNameContext);
3225 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3226 assert(TInfo && "couldn't build declarator info for anonymous struct");
3228 // Create a declaration for this anonymous struct.
3229 NamedDecl* Anon = FieldDecl::Create(Context,
3230 cast<RecordDecl>(CurContext),
3233 /*IdentifierInfo=*/0,
3234 Context.getTypeDeclType(Record),
3236 /*BitWidth=*/0, /*Mutable=*/false,
3237 /*InitStyle=*/ICIS_NoInit);
3238 Anon->setImplicit();
3240 // Add the anonymous struct object to the current context.
3241 CurContext->addDecl(Anon);
3243 // Inject the members of the anonymous struct into the current
3244 // context and into the identifier resolver chain for name lookup
3246 SmallVector<NamedDecl*, 2> Chain;
3247 Chain.push_back(Anon);
3249 RecordDecl *RecordDef = Record->getDefinition();
3250 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3253 Anon->setInvalidDecl();
3258 /// GetNameForDeclarator - Determine the full declaration name for the
3259 /// given Declarator.
3260 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
3261 return GetNameFromUnqualifiedId(D.getName());
3264 /// \brief Retrieves the declaration name from a parsed unqualified-id.
3266 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3267 DeclarationNameInfo NameInfo;
3268 NameInfo.setLoc(Name.StartLocation);
3270 switch (Name.getKind()) {
3272 case UnqualifiedId::IK_ImplicitSelfParam:
3273 case UnqualifiedId::IK_Identifier:
3274 NameInfo.setName(Name.Identifier);
3275 NameInfo.setLoc(Name.StartLocation);
3278 case UnqualifiedId::IK_OperatorFunctionId:
3279 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3280 Name.OperatorFunctionId.Operator));
3281 NameInfo.setLoc(Name.StartLocation);
3282 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3283 = Name.OperatorFunctionId.SymbolLocations[0];
3284 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3285 = Name.EndLocation.getRawEncoding();
3288 case UnqualifiedId::IK_LiteralOperatorId:
3289 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3291 NameInfo.setLoc(Name.StartLocation);
3292 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3295 case UnqualifiedId::IK_ConversionFunctionId: {
3296 TypeSourceInfo *TInfo;
3297 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3299 return DeclarationNameInfo();
3300 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3301 Context.getCanonicalType(Ty)));
3302 NameInfo.setLoc(Name.StartLocation);
3303 NameInfo.setNamedTypeInfo(TInfo);
3307 case UnqualifiedId::IK_ConstructorName: {
3308 TypeSourceInfo *TInfo;
3309 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3311 return DeclarationNameInfo();
3312 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3313 Context.getCanonicalType(Ty)));
3314 NameInfo.setLoc(Name.StartLocation);
3315 NameInfo.setNamedTypeInfo(TInfo);
3319 case UnqualifiedId::IK_ConstructorTemplateId: {
3320 // In well-formed code, we can only have a constructor
3321 // template-id that refers to the current context, so go there
3322 // to find the actual type being constructed.
3323 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3324 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3325 return DeclarationNameInfo();
3327 // Determine the type of the class being constructed.
3328 QualType CurClassType = Context.getTypeDeclType(CurClass);
3330 // FIXME: Check two things: that the template-id names the same type as
3331 // CurClassType, and that the template-id does not occur when the name
3334 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3335 Context.getCanonicalType(CurClassType)));
3336 NameInfo.setLoc(Name.StartLocation);
3337 // FIXME: should we retrieve TypeSourceInfo?
3338 NameInfo.setNamedTypeInfo(0);
3342 case UnqualifiedId::IK_DestructorName: {
3343 TypeSourceInfo *TInfo;
3344 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3346 return DeclarationNameInfo();
3347 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3348 Context.getCanonicalType(Ty)));
3349 NameInfo.setLoc(Name.StartLocation);
3350 NameInfo.setNamedTypeInfo(TInfo);
3354 case UnqualifiedId::IK_TemplateId: {
3355 TemplateName TName = Name.TemplateId->Template.get();
3356 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3357 return Context.getNameForTemplate(TName, TNameLoc);
3360 } // switch (Name.getKind())
3362 llvm_unreachable("Unknown name kind");
3365 static QualType getCoreType(QualType Ty) {
3367 if (Ty->isPointerType() || Ty->isReferenceType())
3368 Ty = Ty->getPointeeType();
3369 else if (Ty->isArrayType())
3370 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3372 return Ty.withoutLocalFastQualifiers();
3376 /// hasSimilarParameters - Determine whether the C++ functions Declaration
3377 /// and Definition have "nearly" matching parameters. This heuristic is
3378 /// used to improve diagnostics in the case where an out-of-line function
3379 /// definition doesn't match any declaration within the class or namespace.
3380 /// Also sets Params to the list of indices to the parameters that differ
3381 /// between the declaration and the definition. If hasSimilarParameters
3382 /// returns true and Params is empty, then all of the parameters match.
3383 static bool hasSimilarParameters(ASTContext &Context,
3384 FunctionDecl *Declaration,
3385 FunctionDecl *Definition,
3386 llvm::SmallVectorImpl<unsigned> &Params) {
3388 if (Declaration->param_size() != Definition->param_size())
3390 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3391 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3392 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3394 // The parameter types are identical
3395 if (Context.hasSameType(DefParamTy, DeclParamTy))
3398 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3399 QualType DefParamBaseTy = getCoreType(DefParamTy);
3400 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
3401 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
3403 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
3404 (DeclTyName && DeclTyName == DefTyName))
3405 Params.push_back(Idx);
3406 else // The two parameters aren't even close
3413 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
3414 /// declarator needs to be rebuilt in the current instantiation.
3415 /// Any bits of declarator which appear before the name are valid for
3416 /// consideration here. That's specifically the type in the decl spec
3417 /// and the base type in any member-pointer chunks.
3418 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
3419 DeclarationName Name) {
3420 // The types we specifically need to rebuild are:
3421 // - typenames, typeofs, and decltypes
3422 // - types which will become injected class names
3423 // Of course, we also need to rebuild any type referencing such a
3424 // type. It's safest to just say "dependent", but we call out a
3427 DeclSpec &DS = D.getMutableDeclSpec();
3428 switch (DS.getTypeSpecType()) {
3429 case DeclSpec::TST_typename:
3430 case DeclSpec::TST_typeofType:
3431 case DeclSpec::TST_underlyingType:
3432 case DeclSpec::TST_atomic: {
3433 // Grab the type from the parser.
3434 TypeSourceInfo *TSI = 0;
3435 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
3436 if (T.isNull() || !T->isDependentType()) break;
3438 // Make sure there's a type source info. This isn't really much
3439 // of a waste; most dependent types should have type source info
3440 // attached already.
3442 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
3444 // Rebuild the type in the current instantiation.
3445 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
3446 if (!TSI) return true;
3448 // Store the new type back in the decl spec.
3449 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
3450 DS.UpdateTypeRep(LocType);
3454 case DeclSpec::TST_decltype:
3455 case DeclSpec::TST_typeofExpr: {
3456 Expr *E = DS.getRepAsExpr();
3457 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
3458 if (Result.isInvalid()) return true;
3459 DS.UpdateExprRep(Result.get());
3464 // Nothing to do for these decl specs.
3468 // It doesn't matter what order we do this in.
3469 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3470 DeclaratorChunk &Chunk = D.getTypeObject(I);
3472 // The only type information in the declarator which can come
3473 // before the declaration name is the base type of a member
3475 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
3478 // Rebuild the scope specifier in-place.
3479 CXXScopeSpec &SS = Chunk.Mem.Scope();
3480 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
3487 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
3488 D.setFunctionDefinitionKind(FDK_Declaration);
3489 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
3491 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
3492 Dcl && Dcl->getDeclContext()->isFileContext())
3493 Dcl->setTopLevelDeclInObjCContainer();
3498 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3499 /// If T is the name of a class, then each of the following shall have a
3500 /// name different from T:
3501 /// - every static data member of class T;
3502 /// - every member function of class T
3503 /// - every member of class T that is itself a type;
3504 /// \returns true if the declaration name violates these rules.
3505 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
3506 DeclarationNameInfo NameInfo) {
3507 DeclarationName Name = NameInfo.getName();
3509 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
3510 if (Record->getIdentifier() && Record->getDeclName() == Name) {
3511 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
3518 /// \brief Diagnose a declaration whose declarator-id has the given
3519 /// nested-name-specifier.
3521 /// \param SS The nested-name-specifier of the declarator-id.
3523 /// \param DC The declaration context to which the nested-name-specifier
3526 /// \param Name The name of the entity being declared.
3528 /// \param Loc The location of the name of the entity being declared.
3530 /// \returns true if we cannot safely recover from this error, false otherwise.
3531 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
3532 DeclarationName Name,
3533 SourceLocation Loc) {
3534 DeclContext *Cur = CurContext;
3535 while (isa<LinkageSpecDecl>(Cur))
3536 Cur = Cur->getParent();
3538 // C++ [dcl.meaning]p1:
3539 // A declarator-id shall not be qualified except for the definition
3540 // of a member function (9.3) or static data member (9.4) outside of
3541 // its class, the definition or explicit instantiation of a function
3542 // or variable member of a namespace outside of its namespace, or the
3543 // definition of an explicit specialization outside of its namespace,
3544 // or the declaration of a friend function that is a member of
3545 // another class or namespace (11.3). [...]
3547 // The user provided a superfluous scope specifier that refers back to the
3548 // class or namespaces in which the entity is already declared.
3553 if (Cur->Equals(DC)) {
3554 Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification
3555 : diag::err_member_extra_qualification)
3556 << Name << FixItHint::CreateRemoval(SS.getRange());
3561 // Check whether the qualifying scope encloses the scope of the original
3563 if (!Cur->Encloses(DC)) {
3564 if (Cur->isRecord())
3565 Diag(Loc, diag::err_member_qualification)
3566 << Name << SS.getRange();
3567 else if (isa<TranslationUnitDecl>(DC))
3568 Diag(Loc, diag::err_invalid_declarator_global_scope)
3569 << Name << SS.getRange();
3570 else if (isa<FunctionDecl>(Cur))
3571 Diag(Loc, diag::err_invalid_declarator_in_function)
3572 << Name << SS.getRange();
3574 Diag(Loc, diag::err_invalid_declarator_scope)
3575 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
3580 if (Cur->isRecord()) {
3581 // Cannot qualify members within a class.
3582 Diag(Loc, diag::err_member_qualification)
3583 << Name << SS.getRange();
3586 // C++ constructors and destructors with incorrect scopes can break
3587 // our AST invariants by having the wrong underlying types. If
3588 // that's the case, then drop this declaration entirely.
3589 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
3590 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
3591 !Context.hasSameType(Name.getCXXNameType(),
3592 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
3598 // C++11 [dcl.meaning]p1:
3599 // [...] "The nested-name-specifier of the qualified declarator-id shall
3600 // not begin with a decltype-specifer"
3601 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
3602 while (SpecLoc.getPrefix())
3603 SpecLoc = SpecLoc.getPrefix();
3604 if (dyn_cast_or_null<DecltypeType>(
3605 SpecLoc.getNestedNameSpecifier()->getAsType()))
3606 Diag(Loc, diag::err_decltype_in_declarator)
3607 << SpecLoc.getTypeLoc().getSourceRange();
3612 Decl *Sema::HandleDeclarator(Scope *S, Declarator &D,
3613 MultiTemplateParamsArg TemplateParamLists) {
3614 // TODO: consider using NameInfo for diagnostic.
3615 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3616 DeclarationName Name = NameInfo.getName();
3618 // All of these full declarators require an identifier. If it doesn't have
3619 // one, the ParsedFreeStandingDeclSpec action should be used.
3621 if (!D.isInvalidType()) // Reject this if we think it is valid.
3622 Diag(D.getDeclSpec().getLocStart(),
3623 diag::err_declarator_need_ident)
3624 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
3626 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
3629 // The scope passed in may not be a decl scope. Zip up the scope tree until
3630 // we find one that is.
3631 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3632 (S->getFlags() & Scope::TemplateParamScope) != 0)
3635 DeclContext *DC = CurContext;
3636 if (D.getCXXScopeSpec().isInvalid())
3638 else if (D.getCXXScopeSpec().isSet()) {
3639 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
3640 UPPC_DeclarationQualifier))
3643 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
3644 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
3646 // If we could not compute the declaration context, it's because the
3647 // declaration context is dependent but does not refer to a class,
3648 // class template, or class template partial specialization. Complain
3649 // and return early, to avoid the coming semantic disaster.
3650 Diag(D.getIdentifierLoc(),
3651 diag::err_template_qualified_declarator_no_match)
3652 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
3653 << D.getCXXScopeSpec().getRange();
3656 bool IsDependentContext = DC->isDependentContext();
3658 if (!IsDependentContext &&
3659 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
3662 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
3663 Diag(D.getIdentifierLoc(),
3664 diag::err_member_def_undefined_record)
3665 << Name << DC << D.getCXXScopeSpec().getRange();
3667 } else if (!D.getDeclSpec().isFriendSpecified()) {
3668 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
3669 Name, D.getIdentifierLoc())) {
3677 // Check whether we need to rebuild the type of the given
3678 // declaration in the current instantiation.
3679 if (EnteringContext && IsDependentContext &&
3680 TemplateParamLists.size() != 0) {
3681 ContextRAII SavedContext(*this, DC);
3682 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
3687 if (DiagnoseClassNameShadow(DC, NameInfo))
3688 // If this is a typedef, we'll end up spewing multiple diagnostics.
3689 // Just return early; it's safer.
3690 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3695 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3696 QualType R = TInfo->getType();
3698 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
3699 UPPC_DeclarationType))
3702 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
3705 // See if this is a redefinition of a variable in the same scope.
3706 if (!D.getCXXScopeSpec().isSet()) {
3707 bool IsLinkageLookup = false;
3709 // If the declaration we're planning to build will be a function
3710 // or object with linkage, then look for another declaration with
3711 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
3712 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3714 else if (R->isFunctionType()) {
3715 if (CurContext->isFunctionOrMethod() ||
3716 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
3717 IsLinkageLookup = true;
3718 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
3719 IsLinkageLookup = true;
3720 else if (CurContext->getRedeclContext()->isTranslationUnit() &&
3721 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
3722 IsLinkageLookup = true;
3724 if (IsLinkageLookup)
3725 Previous.clear(LookupRedeclarationWithLinkage);
3727 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
3728 } else { // Something like "int foo::x;"
3729 LookupQualifiedName(Previous, DC);
3731 // C++ [dcl.meaning]p1:
3732 // When the declarator-id is qualified, the declaration shall refer to a
3733 // previously declared member of the class or namespace to which the
3734 // qualifier refers (or, in the case of a namespace, of an element of the
3735 // inline namespace set of that namespace (7.3.1)) or to a specialization
3738 // Note that we already checked the context above, and that we do not have
3739 // enough information to make sure that Previous contains the declaration
3740 // we want to match. For example, given:
3747 // void X::f(int) { } // ill-formed
3749 // In this case, Previous will point to the overload set
3750 // containing the two f's declared in X, but neither of them
3753 // C++ [dcl.meaning]p1:
3754 // [...] the member shall not merely have been introduced by a
3755 // using-declaration in the scope of the class or namespace nominated by
3756 // the nested-name-specifier of the declarator-id.
3757 RemoveUsingDecls(Previous);
3760 if (Previous.isSingleResult() &&
3761 Previous.getFoundDecl()->isTemplateParameter()) {
3762 // Maybe we will complain about the shadowed template parameter.
3763 if (!D.isInvalidType())
3764 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
3765 Previous.getFoundDecl());
3767 // Just pretend that we didn't see the previous declaration.
3771 // In C++, the previous declaration we find might be a tag type
3772 // (class or enum). In this case, the new declaration will hide the
3773 // tag type. Note that this does does not apply if we're declaring a
3774 // typedef (C++ [dcl.typedef]p4).
3775 if (Previous.isSingleTagDecl() &&
3776 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
3779 bool AddToScope = true;
3780 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
3781 if (TemplateParamLists.size()) {
3782 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
3786 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
3787 } else if (R->isFunctionType()) {
3788 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
3792 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
3793 TemplateParamLists);
3799 // If this has an identifier and is not an invalid redeclaration or
3800 // function template specialization, add it to the scope stack.
3801 if (New->getDeclName() && AddToScope &&
3802 !(D.isRedeclaration() && New->isInvalidDecl()))
3803 PushOnScopeChains(New, S);
3808 /// Helper method to turn variable array types into constant array
3809 /// types in certain situations which would otherwise be errors (for
3810 /// GCC compatibility).
3811 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3812 ASTContext &Context,
3813 bool &SizeIsNegative,
3814 llvm::APSInt &Oversized) {
3815 // This method tries to turn a variable array into a constant
3816 // array even when the size isn't an ICE. This is necessary
3817 // for compatibility with code that depends on gcc's buggy
3818 // constant expression folding, like struct {char x[(int)(char*)2];}
3819 SizeIsNegative = false;
3822 if (T->isDependentType())
3825 QualifierCollector Qs;
3826 const Type *Ty = Qs.strip(T);
3828 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
3829 QualType Pointee = PTy->getPointeeType();
3830 QualType FixedType =
3831 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
3833 if (FixedType.isNull()) return FixedType;
3834 FixedType = Context.getPointerType(FixedType);
3835 return Qs.apply(Context, FixedType);
3837 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
3838 QualType Inner = PTy->getInnerType();
3839 QualType FixedType =
3840 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
3842 if (FixedType.isNull()) return FixedType;
3843 FixedType = Context.getParenType(FixedType);
3844 return Qs.apply(Context, FixedType);
3847 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3850 // FIXME: We should probably handle this case
3851 if (VLATy->getElementType()->isVariablyModifiedType())
3855 if (!VLATy->getSizeExpr() ||
3856 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
3859 // Check whether the array size is negative.
3860 if (Res.isSigned() && Res.isNegative()) {
3861 SizeIsNegative = true;
3865 // Check whether the array is too large to be addressed.
3866 unsigned ActiveSizeBits
3867 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
3869 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
3874 return Context.getConstantArrayType(VLATy->getElementType(),
3875 Res, ArrayType::Normal, 0);
3879 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
3880 if (PointerTypeLoc* SrcPTL = dyn_cast<PointerTypeLoc>(&SrcTL)) {
3881 PointerTypeLoc* DstPTL = cast<PointerTypeLoc>(&DstTL);
3882 FixInvalidVariablyModifiedTypeLoc(SrcPTL->getPointeeLoc(),
3883 DstPTL->getPointeeLoc());
3884 DstPTL->setStarLoc(SrcPTL->getStarLoc());
3887 if (ParenTypeLoc* SrcPTL = dyn_cast<ParenTypeLoc>(&SrcTL)) {
3888 ParenTypeLoc* DstPTL = cast<ParenTypeLoc>(&DstTL);
3889 FixInvalidVariablyModifiedTypeLoc(SrcPTL->getInnerLoc(),
3890 DstPTL->getInnerLoc());
3891 DstPTL->setLParenLoc(SrcPTL->getLParenLoc());
3892 DstPTL->setRParenLoc(SrcPTL->getRParenLoc());
3895 ArrayTypeLoc* SrcATL = cast<ArrayTypeLoc>(&SrcTL);
3896 ArrayTypeLoc* DstATL = cast<ArrayTypeLoc>(&DstTL);
3897 TypeLoc SrcElemTL = SrcATL->getElementLoc();
3898 TypeLoc DstElemTL = DstATL->getElementLoc();
3899 DstElemTL.initializeFullCopy(SrcElemTL);
3900 DstATL->setLBracketLoc(SrcATL->getLBracketLoc());
3901 DstATL->setSizeExpr(SrcATL->getSizeExpr());
3902 DstATL->setRBracketLoc(SrcATL->getRBracketLoc());
3905 /// Helper method to turn variable array types into constant array
3906 /// types in certain situations which would otherwise be errors (for
3907 /// GCC compatibility).
3908 static TypeSourceInfo*
3909 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
3910 ASTContext &Context,
3911 bool &SizeIsNegative,
3912 llvm::APSInt &Oversized) {
3914 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
3915 SizeIsNegative, Oversized);
3916 if (FixedTy.isNull())
3918 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
3919 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
3920 FixedTInfo->getTypeLoc());
3924 /// \brief Register the given locally-scoped external C declaration so
3925 /// that it can be found later for redeclarations
3927 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
3928 const LookupResult &Previous,
3930 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
3931 "Decl is not a locally-scoped decl!");
3932 // Note that we have a locally-scoped external with this name.
3933 LocallyScopedExternalDecls[ND->getDeclName()] = ND;
3935 if (!Previous.isSingleResult())
3938 NamedDecl *PrevDecl = Previous.getFoundDecl();
3940 // If there was a previous declaration of this variable, it may be
3941 // in our identifier chain. Update the identifier chain with the new
3943 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
3944 // The previous declaration was found on the identifer resolver
3945 // chain, so remove it from its scope.
3947 if (S->isDeclScope(PrevDecl)) {
3948 // Special case for redeclarations in the SAME scope.
3949 // Because this declaration is going to be added to the identifier chain
3950 // later, we should temporarily take it OFF the chain.
3951 IdResolver.RemoveDecl(ND);
3954 // Find the scope for the original declaration.
3955 while (S && !S->isDeclScope(PrevDecl))
3960 S->RemoveDecl(PrevDecl);
3964 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
3965 Sema::findLocallyScopedExternalDecl(DeclarationName Name) {
3966 if (ExternalSource) {
3967 // Load locally-scoped external decls from the external source.
3968 SmallVector<NamedDecl *, 4> Decls;
3969 ExternalSource->ReadLocallyScopedExternalDecls(Decls);
3970 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
3971 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3972 = LocallyScopedExternalDecls.find(Decls[I]->getDeclName());
3973 if (Pos == LocallyScopedExternalDecls.end())
3974 LocallyScopedExternalDecls[Decls[I]->getDeclName()] = Decls[I];
3978 return LocallyScopedExternalDecls.find(Name);
3981 /// \brief Diagnose function specifiers on a declaration of an identifier that
3982 /// does not identify a function.
3983 void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
3984 // FIXME: We should probably indicate the identifier in question to avoid
3985 // confusion for constructs like "inline int a(), b;"
3986 if (D.getDeclSpec().isInlineSpecified())
3987 Diag(D.getDeclSpec().getInlineSpecLoc(),
3988 diag::err_inline_non_function);
3990 if (D.getDeclSpec().isVirtualSpecified())
3991 Diag(D.getDeclSpec().getVirtualSpecLoc(),
3992 diag::err_virtual_non_function);
3994 if (D.getDeclSpec().isExplicitSpecified())
3995 Diag(D.getDeclSpec().getExplicitSpecLoc(),
3996 diag::err_explicit_non_function);
4000 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
4001 TypeSourceInfo *TInfo, LookupResult &Previous) {
4002 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4003 if (D.getCXXScopeSpec().isSet()) {
4004 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4005 << D.getCXXScopeSpec().getRange();
4007 // Pretend we didn't see the scope specifier.
4012 if (getLangOpts().CPlusPlus) {
4013 // Check that there are no default arguments (C++ only).
4014 CheckExtraCXXDefaultArguments(D);
4017 DiagnoseFunctionSpecifiers(D);
4019 if (D.getDeclSpec().isThreadSpecified())
4020 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4021 if (D.getDeclSpec().isConstexprSpecified())
4022 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4025 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4026 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4027 << D.getName().getSourceRange();
4031 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
4032 if (!NewTD) return 0;
4034 // Handle attributes prior to checking for duplicates in MergeVarDecl
4035 ProcessDeclAttributes(S, NewTD, D);
4037 CheckTypedefForVariablyModifiedType(S, NewTD);
4039 bool Redeclaration = D.isRedeclaration();
4040 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4041 D.setRedeclaration(Redeclaration);
4046 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
4047 // C99 6.7.7p2: If a typedef name specifies a variably modified type
4048 // then it shall have block scope.
4049 // Note that variably modified types must be fixed before merging the decl so
4050 // that redeclarations will match.
4051 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4052 QualType T = TInfo->getType();
4053 if (T->isVariablyModifiedType()) {
4054 getCurFunction()->setHasBranchProtectedScope();
4056 if (S->getFnParent() == 0) {
4057 bool SizeIsNegative;
4058 llvm::APSInt Oversized;
4059 TypeSourceInfo *FixedTInfo =
4060 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4064 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
4065 NewTD->setTypeSourceInfo(FixedTInfo);
4068 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
4069 else if (T->isVariableArrayType())
4070 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
4071 else if (Oversized.getBoolValue())
4072 Diag(NewTD->getLocation(), diag::err_array_too_large)
4073 << Oversized.toString(10);
4075 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
4076 NewTD->setInvalidDecl();
4083 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4084 /// declares a typedef-name, either using the 'typedef' type specifier or via
4085 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4087 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4088 LookupResult &Previous, bool &Redeclaration) {
4089 // Merge the decl with the existing one if appropriate. If the decl is
4090 // in an outer scope, it isn't the same thing.
4091 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
4092 /*ExplicitInstantiationOrSpecialization=*/false);
4093 if (!Previous.empty()) {
4094 Redeclaration = true;
4095 MergeTypedefNameDecl(NewTD, Previous);
4098 // If this is the C FILE type, notify the AST context.
4099 if (IdentifierInfo *II = NewTD->getIdentifier())
4100 if (!NewTD->isInvalidDecl() &&
4101 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
4102 if (II->isStr("FILE"))
4103 Context.setFILEDecl(NewTD);
4104 else if (II->isStr("jmp_buf"))
4105 Context.setjmp_bufDecl(NewTD);
4106 else if (II->isStr("sigjmp_buf"))
4107 Context.setsigjmp_bufDecl(NewTD);
4108 else if (II->isStr("ucontext_t"))
4109 Context.setucontext_tDecl(NewTD);
4115 /// \brief Determines whether the given declaration is an out-of-scope
4116 /// previous declaration.
4118 /// This routine should be invoked when name lookup has found a
4119 /// previous declaration (PrevDecl) that is not in the scope where a
4120 /// new declaration by the same name is being introduced. If the new
4121 /// declaration occurs in a local scope, previous declarations with
4122 /// linkage may still be considered previous declarations (C99
4123 /// 6.2.2p4-5, C++ [basic.link]p6).
4125 /// \param PrevDecl the previous declaration found by name
4128 /// \param DC the context in which the new declaration is being
4131 /// \returns true if PrevDecl is an out-of-scope previous declaration
4132 /// for a new delcaration with the same name.
4134 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4135 ASTContext &Context) {
4139 if (!PrevDecl->hasLinkage())
4142 if (Context.getLangOpts().CPlusPlus) {
4143 // C++ [basic.link]p6:
4144 // If there is a visible declaration of an entity with linkage
4145 // having the same name and type, ignoring entities declared
4146 // outside the innermost enclosing namespace scope, the block
4147 // scope declaration declares that same entity and receives the
4148 // linkage of the previous declaration.
4149 DeclContext *OuterContext = DC->getRedeclContext();
4150 if (!OuterContext->isFunctionOrMethod())
4151 // This rule only applies to block-scope declarations.
4154 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4155 if (PrevOuterContext->isRecord())
4156 // We found a member function: ignore it.
4159 // Find the innermost enclosing namespace for the new and
4160 // previous declarations.
4161 OuterContext = OuterContext->getEnclosingNamespaceContext();
4162 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
4164 // The previous declaration is in a different namespace, so it
4165 // isn't the same function.
4166 if (!OuterContext->Equals(PrevOuterContext))
4173 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4174 CXXScopeSpec &SS = D.getCXXScopeSpec();
4175 if (!SS.isSet()) return;
4176 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
4179 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4180 QualType type = decl->getType();
4181 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4182 if (lifetime == Qualifiers::OCL_Autoreleasing) {
4183 // Various kinds of declaration aren't allowed to be __autoreleasing.
4184 unsigned kind = -1U;
4185 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4186 if (var->hasAttr<BlocksAttr>())
4187 kind = 0; // __block
4188 else if (!var->hasLocalStorage())
4190 } else if (isa<ObjCIvarDecl>(decl)) {
4192 } else if (isa<FieldDecl>(decl)) {
4197 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4200 } else if (lifetime == Qualifiers::OCL_None) {
4201 // Try to infer lifetime.
4202 if (!type->isObjCLifetimeType())
4205 lifetime = type->getObjCARCImplicitLifetime();
4206 type = Context.getLifetimeQualifiedType(type, lifetime);
4207 decl->setType(type);
4210 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4211 // Thread-local variables cannot have lifetime.
4212 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
4213 var->isThreadSpecified()) {
4214 Diag(var->getLocation(), diag::err_arc_thread_ownership)
4224 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4225 TypeSourceInfo *TInfo, LookupResult &Previous,
4226 MultiTemplateParamsArg TemplateParamLists) {
4227 QualType R = TInfo->getType();
4228 DeclarationName Name = GetNameForDeclarator(D).getName();
4230 // Check that there are no default arguments (C++ only).
4231 if (getLangOpts().CPlusPlus)
4232 CheckExtraCXXDefaultArguments(D);
4234 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
4235 assert(SCSpec != DeclSpec::SCS_typedef &&
4236 "Parser allowed 'typedef' as storage class VarDecl.");
4237 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
4238 if (SCSpec == DeclSpec::SCS_mutable) {
4239 // mutable can only appear on non-static class members, so it's always
4241 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
4245 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
4246 VarDecl::StorageClass SCAsWritten
4247 = StorageClassSpecToVarDeclStorageClass(SCSpec);
4249 IdentifierInfo *II = Name.getAsIdentifierInfo();
4251 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
4256 DiagnoseFunctionSpecifiers(D);
4258 if (!DC->isRecord() && S->getFnParent() == 0) {
4259 // C99 6.9p2: The storage-class specifiers auto and register shall not
4260 // appear in the declaration specifiers in an external declaration.
4261 if (SC == SC_Auto || SC == SC_Register) {
4263 // If this is a register variable with an asm label specified, then this
4264 // is a GNU extension.
4265 if (SC == SC_Register && D.getAsmLabel())
4266 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
4268 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
4273 if (getLangOpts().OpenCL) {
4274 // Set up the special work-group-local storage class for variables in the
4275 // OpenCL __local address space.
4276 if (R.getAddressSpace() == LangAS::opencl_local)
4277 SC = SC_OpenCLWorkGroupLocal;
4280 bool isExplicitSpecialization = false;
4282 if (!getLangOpts().CPlusPlus) {
4283 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
4284 D.getIdentifierLoc(), II,
4285 R, TInfo, SC, SCAsWritten);
4287 if (D.isInvalidType())
4288 NewVD->setInvalidDecl();
4290 if (DC->isRecord() && !CurContext->isRecord()) {
4291 // This is an out-of-line definition of a static data member.
4292 if (SC == SC_Static) {
4293 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4294 diag::err_static_out_of_line)
4295 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4296 } else if (SC == SC_None)
4299 if (SC == SC_Static && CurContext->isRecord()) {
4300 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
4301 if (RD->isLocalClass())
4302 Diag(D.getIdentifierLoc(),
4303 diag::err_static_data_member_not_allowed_in_local_class)
4304 << Name << RD->getDeclName();
4306 // C++98 [class.union]p1: If a union contains a static data member,
4307 // the program is ill-formed. C++11 drops this restriction.
4309 Diag(D.getIdentifierLoc(),
4310 getLangOpts().CPlusPlus0x
4311 ? diag::warn_cxx98_compat_static_data_member_in_union
4312 : diag::ext_static_data_member_in_union) << Name;
4313 // We conservatively disallow static data members in anonymous structs.
4314 else if (!RD->getDeclName())
4315 Diag(D.getIdentifierLoc(),
4316 diag::err_static_data_member_not_allowed_in_anon_struct)
4317 << Name << RD->isUnion();
4321 // Match up the template parameter lists with the scope specifier, then
4322 // determine whether we have a template or a template specialization.
4323 isExplicitSpecialization = false;
4324 bool Invalid = false;
4325 if (TemplateParameterList *TemplateParams
4326 = MatchTemplateParametersToScopeSpecifier(
4327 D.getDeclSpec().getLocStart(),
4328 D.getIdentifierLoc(),
4329 D.getCXXScopeSpec(),
4330 TemplateParamLists.data(),
4331 TemplateParamLists.size(),
4332 /*never a friend*/ false,
4333 isExplicitSpecialization,
4335 if (TemplateParams->size() > 0) {
4336 // There is no such thing as a variable template.
4337 Diag(D.getIdentifierLoc(), diag::err_template_variable)
4339 << SourceRange(TemplateParams->getTemplateLoc(),
4340 TemplateParams->getRAngleLoc());
4343 // There is an extraneous 'template<>' for this variable. Complain
4344 // about it, but allow the declaration of the variable.
4345 Diag(TemplateParams->getTemplateLoc(),
4346 diag::err_template_variable_noparams)
4348 << SourceRange(TemplateParams->getTemplateLoc(),
4349 TemplateParams->getRAngleLoc());
4353 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
4354 D.getIdentifierLoc(), II,
4355 R, TInfo, SC, SCAsWritten);
4357 // If this decl has an auto type in need of deduction, make a note of the
4358 // Decl so we can diagnose uses of it in its own initializer.
4359 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
4360 R->getContainedAutoType())
4361 ParsingInitForAutoVars.insert(NewVD);
4363 if (D.isInvalidType() || Invalid)
4364 NewVD->setInvalidDecl();
4366 SetNestedNameSpecifier(NewVD, D);
4368 if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) {
4369 NewVD->setTemplateParameterListsInfo(Context,
4370 TemplateParamLists.size(),
4371 TemplateParamLists.data());
4374 if (D.getDeclSpec().isConstexprSpecified())
4375 NewVD->setConstexpr(true);
4378 // Set the lexical context. If the declarator has a C++ scope specifier, the
4379 // lexical context will be different from the semantic context.
4380 NewVD->setLexicalDeclContext(CurContext);
4382 if (D.getDeclSpec().isThreadSpecified()) {
4383 if (NewVD->hasLocalStorage())
4384 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
4385 else if (!Context.getTargetInfo().isTLSSupported())
4386 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
4388 NewVD->setThreadSpecified(true);
4391 if (D.getDeclSpec().isModulePrivateSpecified()) {
4392 if (isExplicitSpecialization)
4393 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
4395 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
4396 else if (NewVD->hasLocalStorage())
4397 Diag(NewVD->getLocation(), diag::err_module_private_local)
4398 << 0 << NewVD->getDeclName()
4399 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
4400 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
4402 NewVD->setModulePrivate();
4405 // Handle attributes prior to checking for duplicates in MergeVarDecl
4406 ProcessDeclAttributes(S, NewVD, D);
4408 if (getLangOpts().CUDA) {
4409 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
4410 // storage [duration]."
4411 if (SC == SC_None && S->getFnParent() != 0 &&
4412 (NewVD->hasAttr<CUDASharedAttr>() || NewVD->hasAttr<CUDAConstantAttr>()))
4413 NewVD->setStorageClass(SC_Static);
4416 // In auto-retain/release, infer strong retension for variables of
4418 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
4419 NewVD->setInvalidDecl();
4421 // Handle GNU asm-label extension (encoded as an attribute).
4422 if (Expr *E = (Expr*)D.getAsmLabel()) {
4423 // The parser guarantees this is a string.
4424 StringLiteral *SE = cast<StringLiteral>(E);
4425 StringRef Label = SE->getString();
4426 if (S->getFnParent() != 0) {
4430 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
4433 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
4434 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
4438 case SC_PrivateExtern:
4439 case SC_OpenCLWorkGroupLocal:
4444 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
4446 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
4447 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
4448 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
4449 if (I != ExtnameUndeclaredIdentifiers.end()) {
4450 NewVD->addAttr(I->second);
4451 ExtnameUndeclaredIdentifiers.erase(I);
4455 // Diagnose shadowed variables before filtering for scope.
4456 if (!D.getCXXScopeSpec().isSet())
4457 CheckShadow(S, NewVD, Previous);
4459 // Don't consider existing declarations that are in a different
4460 // scope and are out-of-semantic-context declarations (if the new
4461 // declaration has linkage).
4462 FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(),
4463 isExplicitSpecialization);
4465 if (!getLangOpts().CPlusPlus) {
4466 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
4468 // Merge the decl with the existing one if appropriate.
4469 if (!Previous.empty()) {
4470 if (Previous.isSingleResult() &&
4471 isa<FieldDecl>(Previous.getFoundDecl()) &&
4472 D.getCXXScopeSpec().isSet()) {
4473 // The user tried to define a non-static data member
4474 // out-of-line (C++ [dcl.meaning]p1).
4475 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
4476 << D.getCXXScopeSpec().getRange();
4478 NewVD->setInvalidDecl();
4480 } else if (D.getCXXScopeSpec().isSet()) {
4481 // No previous declaration in the qualifying scope.
4482 Diag(D.getIdentifierLoc(), diag::err_no_member)
4483 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
4484 << D.getCXXScopeSpec().getRange();
4485 NewVD->setInvalidDecl();
4488 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
4490 // This is an explicit specialization of a static data member. Check it.
4491 if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
4492 CheckMemberSpecialization(NewVD, Previous))
4493 NewVD->setInvalidDecl();
4496 // If this is a locally-scoped extern C variable, update the map of
4498 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
4499 !NewVD->isInvalidDecl())
4500 RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
4502 // If there's a #pragma GCC visibility in scope, and this isn't a class
4503 // member, set the visibility of this variable.
4504 if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord())
4505 AddPushedVisibilityAttribute(NewVD);
4507 MarkUnusedFileScopedDecl(NewVD);
4512 /// \brief Diagnose variable or built-in function shadowing. Implements
4515 /// This method is called whenever a VarDecl is added to a "useful"
4518 /// \param S the scope in which the shadowing name is being declared
4519 /// \param R the lookup of the name
4521 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
4522 // Return if warning is ignored.
4523 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
4524 DiagnosticsEngine::Ignored)
4527 // Don't diagnose declarations at file scope.
4528 if (D->hasGlobalStorage())
4531 DeclContext *NewDC = D->getDeclContext();
4533 // Only diagnose if we're shadowing an unambiguous field or variable.
4534 if (R.getResultKind() != LookupResult::Found)
4537 NamedDecl* ShadowedDecl = R.getFoundDecl();
4538 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
4541 // Fields are not shadowed by variables in C++ static methods.
4542 if (isa<FieldDecl>(ShadowedDecl))
4543 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
4547 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
4548 if (shadowedVar->isExternC()) {
4549 // For shadowing external vars, make sure that we point to the global
4550 // declaration, not a locally scoped extern declaration.
4551 for (VarDecl::redecl_iterator
4552 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
4554 if (I->isFileVarDecl()) {
4560 DeclContext *OldDC = ShadowedDecl->getDeclContext();
4562 // Only warn about certain kinds of shadowing for class members.
4563 if (NewDC && NewDC->isRecord()) {
4564 // In particular, don't warn about shadowing non-class members.
4565 if (!OldDC->isRecord())
4568 // TODO: should we warn about static data members shadowing
4569 // static data members from base classes?
4571 // TODO: don't diagnose for inaccessible shadowed members.
4572 // This is hard to do perfectly because we might friend the
4573 // shadowing context, but that's just a false negative.
4576 // Determine what kind of declaration we're shadowing.
4578 if (isa<RecordDecl>(OldDC)) {
4579 if (isa<FieldDecl>(ShadowedDecl))
4582 Kind = 2; // static data member
4583 } else if (OldDC->isFileContext())
4588 DeclarationName Name = R.getLookupName();
4590 // Emit warning and note.
4591 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
4592 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
4595 /// \brief Check -Wshadow without the advantage of a previous lookup.
4596 void Sema::CheckShadow(Scope *S, VarDecl *D) {
4597 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
4598 DiagnosticsEngine::Ignored)
4601 LookupResult R(*this, D->getDeclName(), D->getLocation(),
4602 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
4604 CheckShadow(S, D, R);
4607 /// \brief Perform semantic checking on a newly-created variable
4610 /// This routine performs all of the type-checking required for a
4611 /// variable declaration once it has been built. It is used both to
4612 /// check variables after they have been parsed and their declarators
4613 /// have been translated into a declaration, and to check variables
4614 /// that have been instantiated from a template.
4616 /// Sets NewVD->isInvalidDecl() if an error was encountered.
4618 /// Returns true if the variable declaration is a redeclaration.
4619 bool Sema::CheckVariableDeclaration(VarDecl *NewVD,
4620 LookupResult &Previous) {
4621 // If the decl is already known invalid, don't check it.
4622 if (NewVD->isInvalidDecl())
4625 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
4626 QualType T = TInfo->getType();
4628 if (T->isObjCObjectType()) {
4629 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
4630 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
4631 T = Context.getObjCObjectPointerType(T);
4635 // Emit an error if an address space was applied to decl with local storage.
4636 // This includes arrays of objects with address space qualifiers, but not
4637 // automatic variables that point to other address spaces.
4638 // ISO/IEC TR 18037 S5.1.2
4639 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
4640 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
4641 NewVD->setInvalidDecl();
4645 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
4647 if ((getLangOpts().OpenCLVersion >= 120)
4648 && NewVD->isStaticLocal()) {
4649 Diag(NewVD->getLocation(), diag::err_static_function_scope);
4650 NewVD->setInvalidDecl();
4654 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
4655 && !NewVD->hasAttr<BlocksAttr>()) {
4656 if (getLangOpts().getGC() != LangOptions::NonGC)
4657 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
4659 assert(!getLangOpts().ObjCAutoRefCount);
4660 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
4664 bool isVM = T->isVariablyModifiedType();
4665 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
4666 NewVD->hasAttr<BlocksAttr>())
4667 getCurFunction()->setHasBranchProtectedScope();
4669 if ((isVM && NewVD->hasLinkage()) ||
4670 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
4671 bool SizeIsNegative;
4672 llvm::APSInt Oversized;
4673 TypeSourceInfo *FixedTInfo =
4674 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4675 SizeIsNegative, Oversized);
4676 if (FixedTInfo == 0 && T->isVariableArrayType()) {
4677 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
4678 // FIXME: This won't give the correct result for
4680 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
4682 if (NewVD->isFileVarDecl())
4683 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
4685 else if (NewVD->getStorageClass() == SC_Static)
4686 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
4689 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
4691 NewVD->setInvalidDecl();
4695 if (FixedTInfo == 0) {
4696 if (NewVD->isFileVarDecl())
4697 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
4699 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
4700 NewVD->setInvalidDecl();
4704 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
4705 NewVD->setType(FixedTInfo->getType());
4706 NewVD->setTypeSourceInfo(FixedTInfo);
4709 if (Previous.empty() && NewVD->isExternC()) {
4710 // Since we did not find anything by this name and we're declaring
4711 // an extern "C" variable, look for a non-visible extern "C"
4712 // declaration with the same name.
4713 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4714 = findLocallyScopedExternalDecl(NewVD->getDeclName());
4715 if (Pos != LocallyScopedExternalDecls.end())
4716 Previous.addDecl(Pos->second);
4719 if (T->isVoidType() && !NewVD->hasExternalStorage()) {
4720 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
4722 NewVD->setInvalidDecl();
4726 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
4727 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
4728 NewVD->setInvalidDecl();
4732 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
4733 Diag(NewVD->getLocation(), diag::err_block_on_vm);
4734 NewVD->setInvalidDecl();
4738 if (NewVD->isConstexpr() && !T->isDependentType() &&
4739 RequireLiteralType(NewVD->getLocation(), T,
4740 diag::err_constexpr_var_non_literal)) {
4741 NewVD->setInvalidDecl();
4745 if (!Previous.empty()) {
4746 MergeVarDecl(NewVD, Previous);
4752 /// \brief Data used with FindOverriddenMethod
4753 struct FindOverriddenMethodData {
4755 CXXMethodDecl *Method;
4758 /// \brief Member lookup function that determines whether a given C++
4759 /// method overrides a method in a base class, to be used with
4760 /// CXXRecordDecl::lookupInBases().
4761 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
4764 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4766 FindOverriddenMethodData *Data
4767 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
4769 DeclarationName Name = Data->Method->getDeclName();
4771 // FIXME: Do we care about other names here too?
4772 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4773 // We really want to find the base class destructor here.
4774 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
4775 CanQualType CT = Data->S->Context.getCanonicalType(T);
4777 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
4780 for (Path.Decls = BaseRecord->lookup(Name);
4781 Path.Decls.first != Path.Decls.second;
4782 ++Path.Decls.first) {
4783 NamedDecl *D = *Path.Decls.first;
4784 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4785 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
4794 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
4796 /// \brief Report an error regarding overriding, along with any relevant
4797 /// overriden methods.
4799 /// \param DiagID the primary error to report.
4800 /// \param MD the overriding method.
4801 /// \param OEK which overrides to include as notes.
4802 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
4803 OverrideErrorKind OEK = OEK_All) {
4804 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
4805 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4806 E = MD->end_overridden_methods();
4808 // This check (& the OEK parameter) could be replaced by a predicate, but
4809 // without lambdas that would be overkill. This is still nicer than writing
4810 // out the diag loop 3 times.
4811 if ((OEK == OEK_All) ||
4812 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
4813 (OEK == OEK_Deleted && (*I)->isDeleted()))
4814 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
4818 /// AddOverriddenMethods - See if a method overrides any in the base classes,
4819 /// and if so, check that it's a valid override and remember it.
4820 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4821 // Look for virtual methods in base classes that this method might override.
4823 FindOverriddenMethodData Data;
4826 bool hasDeletedOverridenMethods = false;
4827 bool hasNonDeletedOverridenMethods = false;
4828 bool AddedAny = false;
4829 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
4830 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
4831 E = Paths.found_decls_end(); I != E; ++I) {
4832 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
4833 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
4834 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
4835 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
4836 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
4837 hasDeletedOverridenMethods |= OldMD->isDeleted();
4838 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
4845 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
4846 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
4848 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
4849 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
4856 // Struct for holding all of the extra arguments needed by
4857 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
4858 struct ActOnFDArgs {
4861 MultiTemplateParamsArg TemplateParamLists;
4868 // Callback to only accept typo corrections that have a non-zero edit distance.
4869 // Also only accept corrections that have the same parent decl.
4870 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
4872 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
4873 CXXRecordDecl *Parent)
4874 : Context(Context), OriginalFD(TypoFD),
4875 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
4877 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
4878 if (candidate.getEditDistance() == 0)
4881 llvm::SmallVector<unsigned, 1> MismatchedParams;
4882 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
4883 CDeclEnd = candidate.end();
4884 CDecl != CDeclEnd; ++CDecl) {
4885 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
4887 if (FD && !FD->hasBody() &&
4888 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
4889 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
4890 CXXRecordDecl *Parent = MD->getParent();
4891 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
4893 } else if (!ExpectedParent) {
4903 ASTContext &Context;
4904 FunctionDecl *OriginalFD;
4905 CXXRecordDecl *ExpectedParent;
4910 /// \brief Generate diagnostics for an invalid function redeclaration.
4912 /// This routine handles generating the diagnostic messages for an invalid
4913 /// function redeclaration, including finding possible similar declarations
4914 /// or performing typo correction if there are no previous declarations with
4917 /// Returns a NamedDecl iff typo correction was performed and substituting in
4918 /// the new declaration name does not cause new errors.
4919 static NamedDecl* DiagnoseInvalidRedeclaration(
4920 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
4921 ActOnFDArgs &ExtraArgs) {
4922 NamedDecl *Result = NULL;
4923 DeclarationName Name = NewFD->getDeclName();
4924 DeclContext *NewDC = NewFD->getDeclContext();
4925 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
4926 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
4927 llvm::SmallVector<unsigned, 1> MismatchedParams;
4928 llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1> NearMatches;
4929 TypoCorrection Correction;
4930 bool isFriendDecl = (SemaRef.getLangOpts().CPlusPlus &&
4931 ExtraArgs.D.getDeclSpec().isFriendSpecified());
4932 unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend
4933 : diag::err_member_def_does_not_match;
4935 NewFD->setInvalidDecl();
4936 SemaRef.LookupQualifiedName(Prev, NewDC);
4937 assert(!Prev.isAmbiguous() &&
4938 "Cannot have an ambiguity in previous-declaration lookup");
4939 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
4940 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
4941 MD ? MD->getParent() : 0);
4942 if (!Prev.empty()) {
4943 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
4944 Func != FuncEnd; ++Func) {
4945 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
4947 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
4948 // Add 1 to the index so that 0 can mean the mismatch didn't
4949 // involve a parameter
4951 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
4952 NearMatches.push_back(std::make_pair(FD, ParamNum));
4955 // If the qualified name lookup yielded nothing, try typo correction
4956 } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(),
4957 Prev.getLookupKind(), 0, 0,
4958 Validator, NewDC))) {
4960 Sema::SFINAETrap Trap(SemaRef);
4962 // Set up everything for the call to ActOnFunctionDeclarator
4963 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
4964 ExtraArgs.D.getIdentifierLoc());
4966 Previous.setLookupName(Correction.getCorrection());
4967 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
4968 CDeclEnd = Correction.end();
4969 CDecl != CDeclEnd; ++CDecl) {
4970 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
4971 if (FD && !FD->hasBody() &&
4972 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
4973 Previous.addDecl(FD);
4976 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
4977 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
4978 // pieces need to verify the typo-corrected C++ declaraction and hopefully
4979 // eliminate the need for the parameter pack ExtraArgs.
4980 Result = SemaRef.ActOnFunctionDeclarator(
4981 ExtraArgs.S, ExtraArgs.D,
4982 Correction.getCorrectionDecl()->getDeclContext(),
4983 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
4984 ExtraArgs.AddToScope);
4985 if (Trap.hasErrorOccurred()) {
4986 // Pretend the typo correction never occurred
4987 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
4988 ExtraArgs.D.getIdentifierLoc());
4989 ExtraArgs.D.setRedeclaration(wasRedeclaration);
4991 Previous.setLookupName(Name);
4994 for (LookupResult::iterator Func = Previous.begin(),
4995 FuncEnd = Previous.end();
4996 Func != FuncEnd; ++Func) {
4997 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
4998 NearMatches.push_back(std::make_pair(FD, 0));
5001 if (NearMatches.empty()) {
5002 // Ignore the correction if it didn't yield any close FunctionDecl matches
5003 Correction = TypoCorrection();
5005 DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest
5006 : diag::err_member_def_does_not_match_suggest;
5011 // FIXME: use Correction.getCorrectionRange() instead of computing the range
5012 // here. This requires passing in the CXXScopeSpec to CorrectTypo which in
5013 // turn causes the correction to fully qualify the name. If we fix
5014 // CorrectTypo to minimally qualify then this change should be good.
5015 SourceRange FixItLoc(NewFD->getLocation());
5016 CXXScopeSpec &SS = ExtraArgs.D.getCXXScopeSpec();
5017 if (Correction.getCorrectionSpecifier() && SS.isValid())
5018 FixItLoc.setBegin(SS.getBeginLoc());
5019 SemaRef.Diag(NewFD->getLocStart(), DiagMsg)
5020 << Name << NewDC << Correction.getQuoted(SemaRef.getLangOpts())
5021 << FixItHint::CreateReplacement(
5022 FixItLoc, Correction.getAsString(SemaRef.getLangOpts()));
5024 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
5025 << Name << NewDC << NewFD->getLocation();
5028 bool NewFDisConst = false;
5029 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
5030 NewFDisConst = NewMD->isConst();
5032 for (llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1>::iterator
5033 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
5034 NearMatch != NearMatchEnd; ++NearMatch) {
5035 FunctionDecl *FD = NearMatch->first;
5036 bool FDisConst = false;
5037 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
5038 FDisConst = MD->isConst();
5040 if (unsigned Idx = NearMatch->second) {
5041 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
5042 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
5043 if (Loc.isInvalid()) Loc = FD->getLocation();
5044 SemaRef.Diag(Loc, diag::note_member_def_close_param_match)
5045 << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType();
5046 } else if (Correction) {
5047 SemaRef.Diag(FD->getLocation(), diag::note_previous_decl)
5048 << Correction.getQuoted(SemaRef.getLangOpts());
5049 } else if (FDisConst != NewFDisConst) {
5050 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
5051 << NewFDisConst << FD->getSourceRange().getEnd();
5053 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match);
5058 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
5060 switch (D.getDeclSpec().getStorageClassSpec()) {
5061 default: llvm_unreachable("Unknown storage class!");
5062 case DeclSpec::SCS_auto:
5063 case DeclSpec::SCS_register:
5064 case DeclSpec::SCS_mutable:
5065 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5066 diag::err_typecheck_sclass_func);
5069 case DeclSpec::SCS_unspecified: break;
5070 case DeclSpec::SCS_extern: return SC_Extern;
5071 case DeclSpec::SCS_static: {
5072 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
5074 // The declaration of an identifier for a function that has
5075 // block scope shall have no explicit storage-class specifier
5076 // other than extern
5077 // See also (C++ [dcl.stc]p4).
5078 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5079 diag::err_static_block_func);
5084 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5087 // No explicit storage class has already been returned
5091 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
5092 DeclContext *DC, QualType &R,
5093 TypeSourceInfo *TInfo,
5094 FunctionDecl::StorageClass SC,
5095 bool &IsVirtualOkay) {
5096 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
5097 DeclarationName Name = NameInfo.getName();
5099 FunctionDecl *NewFD = 0;
5100 bool isInline = D.getDeclSpec().isInlineSpecified();
5101 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
5102 FunctionDecl::StorageClass SCAsWritten
5103 = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
5105 if (!SemaRef.getLangOpts().CPlusPlus) {
5106 // Determine whether the function was written with a
5107 // prototype. This true when:
5108 // - there is a prototype in the declarator, or
5109 // - the type R of the function is some kind of typedef or other reference
5110 // to a type name (which eventually refers to a function type).
5112 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
5113 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
5115 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
5116 D.getLocStart(), NameInfo, R,
5117 TInfo, SC, SCAsWritten, isInline,
5119 if (D.isInvalidType())
5120 NewFD->setInvalidDecl();
5122 // Set the lexical context.
5123 NewFD->setLexicalDeclContext(SemaRef.CurContext);
5128 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
5129 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
5131 // Check that the return type is not an abstract class type.
5132 // For record types, this is done by the AbstractClassUsageDiagnoser once
5133 // the class has been completely parsed.
5134 if (!DC->isRecord() &&
5135 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
5136 R->getAs<FunctionType>()->getResultType(),
5137 diag::err_abstract_type_in_decl,
5138 SemaRef.AbstractReturnType))
5141 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
5142 // This is a C++ constructor declaration.
5143 assert(DC->isRecord() &&
5144 "Constructors can only be declared in a member context");
5146 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
5147 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
5148 D.getLocStart(), NameInfo,
5149 R, TInfo, isExplicit, isInline,
5150 /*isImplicitlyDeclared=*/false,
5153 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
5154 // This is a C++ destructor declaration.
5155 if (DC->isRecord()) {
5156 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
5157 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
5158 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
5159 SemaRef.Context, Record,
5161 NameInfo, R, TInfo, isInline,
5162 /*isImplicitlyDeclared=*/false);
5164 // If the class is complete, then we now create the implicit exception
5165 // specification. If the class is incomplete or dependent, we can't do
5167 if (SemaRef.getLangOpts().CPlusPlus0x && !Record->isDependentType() &&
5168 Record->getDefinition() && !Record->isBeingDefined() &&
5169 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
5170 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
5173 IsVirtualOkay = true;
5177 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
5180 // Create a FunctionDecl to satisfy the function definition parsing
5182 return FunctionDecl::Create(SemaRef.Context, DC,
5184 D.getIdentifierLoc(), Name, R, TInfo,
5185 SC, SCAsWritten, isInline,
5186 /*hasPrototype=*/true, isConstexpr);
5189 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
5190 if (!DC->isRecord()) {
5191 SemaRef.Diag(D.getIdentifierLoc(),
5192 diag::err_conv_function_not_member);
5196 SemaRef.CheckConversionDeclarator(D, R, SC);
5197 IsVirtualOkay = true;
5198 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
5199 D.getLocStart(), NameInfo,
5200 R, TInfo, isInline, isExplicit,
5201 isConstexpr, SourceLocation());
5203 } else if (DC->isRecord()) {
5204 // If the name of the function is the same as the name of the record,
5205 // then this must be an invalid constructor that has a return type.
5206 // (The parser checks for a return type and makes the declarator a
5207 // constructor if it has no return type).
5208 if (Name.getAsIdentifierInfo() &&
5209 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
5210 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
5211 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5212 << SourceRange(D.getIdentifierLoc());
5216 bool isStatic = SC == SC_Static;
5219 // Any allocation function for a class T is a static member
5220 // (even if not explicitly declared static).
5221 if (Name.getCXXOverloadedOperator() == OO_New ||
5222 Name.getCXXOverloadedOperator() == OO_Array_New)
5225 // [class.free]p6 Any deallocation function for a class X is a static member
5226 // (even if not explicitly declared static).
5227 if (Name.getCXXOverloadedOperator() == OO_Delete ||
5228 Name.getCXXOverloadedOperator() == OO_Array_Delete)
5231 IsVirtualOkay = !isStatic;
5233 // This is a C++ method declaration.
5234 return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
5235 D.getLocStart(), NameInfo, R,
5236 TInfo, isStatic, SCAsWritten, isInline,
5237 isConstexpr, SourceLocation());
5240 // Determine whether the function was written with a
5241 // prototype. This true when:
5242 // - we're in C++ (where every function has a prototype),
5243 return FunctionDecl::Create(SemaRef.Context, DC,
5245 NameInfo, R, TInfo, SC, SCAsWritten, isInline,
5246 true/*HasPrototype*/, isConstexpr);
5250 void Sema::checkVoidParamDecl(ParmVarDecl *Param) {
5251 // In C++, the empty parameter-type-list must be spelled "void"; a
5252 // typedef of void is not permitted.
5253 if (getLangOpts().CPlusPlus &&
5254 Param->getType().getUnqualifiedType() != Context.VoidTy) {
5255 bool IsTypeAlias = false;
5256 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
5257 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
5258 else if (const TemplateSpecializationType *TST =
5259 Param->getType()->getAs<TemplateSpecializationType>())
5260 IsTypeAlias = TST->isTypeAlias();
5261 Diag(Param->getLocation(), diag::err_param_typedef_of_void)
5267 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5268 TypeSourceInfo *TInfo, LookupResult &Previous,
5269 MultiTemplateParamsArg TemplateParamLists,
5271 QualType R = TInfo->getType();
5273 assert(R.getTypePtr()->isFunctionType());
5275 // TODO: consider using NameInfo for diagnostic.
5276 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5277 DeclarationName Name = NameInfo.getName();
5278 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
5280 if (D.getDeclSpec().isThreadSpecified())
5281 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
5283 // Do not allow returning a objc interface by-value.
5284 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
5285 Diag(D.getIdentifierLoc(),
5286 diag::err_object_cannot_be_passed_returned_by_value) << 0
5287 << R->getAs<FunctionType>()->getResultType()
5288 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
5290 QualType T = R->getAs<FunctionType>()->getResultType();
5291 T = Context.getObjCObjectPointerType(T);
5292 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) {
5293 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5294 R = Context.getFunctionType(T, FPT->arg_type_begin(),
5295 FPT->getNumArgs(), EPI);
5297 else if (isa<FunctionNoProtoType>(R))
5298 R = Context.getFunctionNoProtoType(T);
5301 bool isFriend = false;
5302 FunctionTemplateDecl *FunctionTemplate = 0;
5303 bool isExplicitSpecialization = false;
5304 bool isFunctionTemplateSpecialization = false;
5306 bool isDependentClassScopeExplicitSpecialization = false;
5307 bool HasExplicitTemplateArgs = false;
5308 TemplateArgumentListInfo TemplateArgs;
5310 bool isVirtualOkay = false;
5312 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
5314 if (!NewFD) return 0;
5316 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
5317 NewFD->setTopLevelDeclInObjCContainer();
5319 if (getLangOpts().CPlusPlus) {
5320 bool isInline = D.getDeclSpec().isInlineSpecified();
5321 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
5322 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
5323 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
5324 isFriend = D.getDeclSpec().isFriendSpecified();
5325 if (isFriend && !isInline && D.isFunctionDefinition()) {
5326 // C++ [class.friend]p5
5327 // A function can be defined in a friend declaration of a
5328 // class . . . . Such a function is implicitly inline.
5329 NewFD->setImplicitlyInline();
5332 // If this is a method defined in an __interface, and is not a constructor
5333 // or an overloaded operator, then set the pure flag (isVirtual will already
5335 if (const CXXRecordDecl *Parent =
5336 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
5337 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
5338 NewFD->setPure(true);
5341 SetNestedNameSpecifier(NewFD, D);
5342 isExplicitSpecialization = false;
5343 isFunctionTemplateSpecialization = false;
5344 if (D.isInvalidType())
5345 NewFD->setInvalidDecl();
5347 // Set the lexical context. If the declarator has a C++
5348 // scope specifier, or is the object of a friend declaration, the
5349 // lexical context will be different from the semantic context.
5350 NewFD->setLexicalDeclContext(CurContext);
5352 // Match up the template parameter lists with the scope specifier, then
5353 // determine whether we have a template or a template specialization.
5354 bool Invalid = false;
5355 if (TemplateParameterList *TemplateParams
5356 = MatchTemplateParametersToScopeSpecifier(
5357 D.getDeclSpec().getLocStart(),
5358 D.getIdentifierLoc(),
5359 D.getCXXScopeSpec(),
5360 TemplateParamLists.data(),
5361 TemplateParamLists.size(),
5363 isExplicitSpecialization,
5365 if (TemplateParams->size() > 0) {
5366 // This is a function template
5368 // Check that we can declare a template here.
5369 if (CheckTemplateDeclScope(S, TemplateParams))
5372 // A destructor cannot be a template.
5373 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
5374 Diag(NewFD->getLocation(), diag::err_destructor_template);
5378 // If we're adding a template to a dependent context, we may need to
5379 // rebuilding some of the types used within the template parameter list,
5380 // now that we know what the current instantiation is.
5381 if (DC->isDependentContext()) {
5382 ContextRAII SavedContext(*this, DC);
5383 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
5388 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
5389 NewFD->getLocation(),
5390 Name, TemplateParams,
5392 FunctionTemplate->setLexicalDeclContext(CurContext);
5393 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
5395 // For source fidelity, store the other template param lists.
5396 if (TemplateParamLists.size() > 1) {
5397 NewFD->setTemplateParameterListsInfo(Context,
5398 TemplateParamLists.size() - 1,
5399 TemplateParamLists.data());
5402 // This is a function template specialization.
5403 isFunctionTemplateSpecialization = true;
5404 // For source fidelity, store all the template param lists.
5405 NewFD->setTemplateParameterListsInfo(Context,
5406 TemplateParamLists.size(),
5407 TemplateParamLists.data());
5409 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
5411 // We want to remove the "template<>", found here.
5412 SourceRange RemoveRange = TemplateParams->getSourceRange();
5414 // If we remove the template<> and the name is not a
5415 // template-id, we're actually silently creating a problem:
5416 // the friend declaration will refer to an untemplated decl,
5417 // and clearly the user wants a template specialization. So
5418 // we need to insert '<>' after the name.
5419 SourceLocation InsertLoc;
5420 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5421 InsertLoc = D.getName().getSourceRange().getEnd();
5422 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
5425 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
5426 << Name << RemoveRange
5427 << FixItHint::CreateRemoval(RemoveRange)
5428 << FixItHint::CreateInsertion(InsertLoc, "<>");
5433 // All template param lists were matched against the scope specifier:
5434 // this is NOT (an explicit specialization of) a template.
5435 if (TemplateParamLists.size() > 0)
5436 // For source fidelity, store all the template param lists.
5437 NewFD->setTemplateParameterListsInfo(Context,
5438 TemplateParamLists.size(),
5439 TemplateParamLists.data());
5443 NewFD->setInvalidDecl();
5444 if (FunctionTemplate)
5445 FunctionTemplate->setInvalidDecl();
5448 // C++ [dcl.fct.spec]p5:
5449 // The virtual specifier shall only be used in declarations of
5450 // nonstatic class member functions that appear within a
5451 // member-specification of a class declaration; see 10.3.
5453 if (isVirtual && !NewFD->isInvalidDecl()) {
5454 if (!isVirtualOkay) {
5455 Diag(D.getDeclSpec().getVirtualSpecLoc(),
5456 diag::err_virtual_non_function);
5457 } else if (!CurContext->isRecord()) {
5458 // 'virtual' was specified outside of the class.
5459 Diag(D.getDeclSpec().getVirtualSpecLoc(),
5460 diag::err_virtual_out_of_class)
5461 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
5462 } else if (NewFD->getDescribedFunctionTemplate()) {
5463 // C++ [temp.mem]p3:
5464 // A member function template shall not be virtual.
5465 Diag(D.getDeclSpec().getVirtualSpecLoc(),
5466 diag::err_virtual_member_function_template)
5467 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
5469 // Okay: Add virtual to the method.
5470 NewFD->setVirtualAsWritten(true);
5474 // C++ [dcl.fct.spec]p3:
5475 // The inline specifier shall not appear on a block scope function
5477 if (isInline && !NewFD->isInvalidDecl()) {
5478 if (CurContext->isFunctionOrMethod()) {
5479 // 'inline' is not allowed on block scope function declaration.
5480 Diag(D.getDeclSpec().getInlineSpecLoc(),
5481 diag::err_inline_declaration_block_scope) << Name
5482 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
5486 // C++ [dcl.fct.spec]p6:
5487 // The explicit specifier shall be used only in the declaration of a
5488 // constructor or conversion function within its class definition;
5489 // see 12.3.1 and 12.3.2.
5490 if (isExplicit && !NewFD->isInvalidDecl()) {
5491 if (!CurContext->isRecord()) {
5492 // 'explicit' was specified outside of the class.
5493 Diag(D.getDeclSpec().getExplicitSpecLoc(),
5494 diag::err_explicit_out_of_class)
5495 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
5496 } else if (!isa<CXXConstructorDecl>(NewFD) &&
5497 !isa<CXXConversionDecl>(NewFD)) {
5498 // 'explicit' was specified on a function that wasn't a constructor
5499 // or conversion function.
5500 Diag(D.getDeclSpec().getExplicitSpecLoc(),
5501 diag::err_explicit_non_ctor_or_conv_function)
5502 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
5507 // C++0x [dcl.constexpr]p2: constexpr functions and constexpr constructors
5508 // are implicitly inline.
5509 NewFD->setImplicitlyInline();
5511 // C++0x [dcl.constexpr]p3: functions declared constexpr are required to
5512 // be either constructors or to return a literal type. Therefore,
5513 // destructors cannot be declared constexpr.
5514 if (isa<CXXDestructorDecl>(NewFD))
5515 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
5518 // If __module_private__ was specified, mark the function accordingly.
5519 if (D.getDeclSpec().isModulePrivateSpecified()) {
5520 if (isFunctionTemplateSpecialization) {
5521 SourceLocation ModulePrivateLoc
5522 = D.getDeclSpec().getModulePrivateSpecLoc();
5523 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
5525 << FixItHint::CreateRemoval(ModulePrivateLoc);
5527 NewFD->setModulePrivate();
5528 if (FunctionTemplate)
5529 FunctionTemplate->setModulePrivate();
5534 // For now, claim that the objects have no previous declaration.
5535 if (FunctionTemplate) {
5536 FunctionTemplate->setObjectOfFriendDecl(false);
5537 FunctionTemplate->setAccess(AS_public);
5539 NewFD->setObjectOfFriendDecl(false);
5540 NewFD->setAccess(AS_public);
5543 // If a function is defined as defaulted or deleted, mark it as such now.
5544 switch (D.getFunctionDefinitionKind()) {
5545 case FDK_Declaration:
5546 case FDK_Definition:
5550 NewFD->setDefaulted();
5554 NewFD->setDeletedAsWritten();
5558 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
5559 D.isFunctionDefinition()) {
5560 // C++ [class.mfct]p2:
5561 // A member function may be defined (8.4) in its class definition, in
5562 // which case it is an inline member function (7.1.2)
5563 NewFD->setImplicitlyInline();
5566 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
5567 !CurContext->isRecord()) {
5568 // C++ [class.static]p1:
5569 // A data or function member of a class may be declared static
5570 // in a class definition, in which case it is a static member of
5573 // Complain about the 'static' specifier if it's on an out-of-line
5574 // member function definition.
5575 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5576 diag::err_static_out_of_line)
5577 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5580 // C++11 [except.spec]p15:
5581 // A deallocation function with no exception-specification is treated
5582 // as if it were specified with noexcept(true).
5583 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
5584 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
5585 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
5586 getLangOpts().CPlusPlus0x && FPT && !FPT->hasExceptionSpec()) {
5587 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5588 EPI.ExceptionSpecType = EST_BasicNoexcept;
5589 NewFD->setType(Context.getFunctionType(FPT->getResultType(),
5590 FPT->arg_type_begin(),
5591 FPT->getNumArgs(), EPI));
5595 // Filter out previous declarations that don't match the scope.
5596 FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(),
5597 isExplicitSpecialization ||
5598 isFunctionTemplateSpecialization);
5600 // Handle GNU asm-label extension (encoded as an attribute).
5601 if (Expr *E = (Expr*) D.getAsmLabel()) {
5602 // The parser guarantees this is a string.
5603 StringLiteral *SE = cast<StringLiteral>(E);
5604 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
5606 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5607 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5608 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
5609 if (I != ExtnameUndeclaredIdentifiers.end()) {
5610 NewFD->addAttr(I->second);
5611 ExtnameUndeclaredIdentifiers.erase(I);
5615 // Copy the parameter declarations from the declarator D to the function
5616 // declaration NewFD, if they are available. First scavenge them into Params.
5617 SmallVector<ParmVarDecl*, 16> Params;
5618 if (D.isFunctionDeclarator()) {
5619 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5621 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
5622 // function that takes no arguments, not a function that takes a
5623 // single void argument.
5624 // We let through "const void" here because Sema::GetTypeForDeclarator
5625 // already checks for that case.
5626 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5627 FTI.ArgInfo[0].Param &&
5628 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
5629 // Empty arg list, don't push any params.
5630 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
5631 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
5632 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
5633 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
5634 assert(Param->getDeclContext() != NewFD && "Was set before ?");
5635 Param->setDeclContext(NewFD);
5636 Params.push_back(Param);
5638 if (Param->isInvalidDecl())
5639 NewFD->setInvalidDecl();
5643 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
5644 // When we're declaring a function with a typedef, typeof, etc as in the
5645 // following example, we'll need to synthesize (unnamed)
5646 // parameters for use in the declaration.
5649 // typedef void fn(int);
5653 // Synthesize a parameter for each argument type.
5654 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
5655 AE = FT->arg_type_end(); AI != AE; ++AI) {
5656 ParmVarDecl *Param =
5657 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
5658 Param->setScopeInfo(0, Params.size());
5659 Params.push_back(Param);
5662 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
5663 "Should not need args for typedef of non-prototype fn");
5666 // Finally, we know we have the right number of parameters, install them.
5667 NewFD->setParams(Params);
5669 // Find all anonymous symbols defined during the declaration of this function
5670 // and add to NewFD. This lets us track decls such 'enum Y' in:
5672 // void f(enum Y {AA} x) {}
5674 // which would otherwise incorrectly end up in the translation unit scope.
5675 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
5676 DeclsInPrototypeScope.clear();
5678 // Process the non-inheritable attributes on this declaration.
5679 ProcessDeclAttributes(S, NewFD, D,
5680 /*NonInheritable=*/true, /*Inheritable=*/false);
5682 // Functions returning a variably modified type violate C99 6.7.5.2p2
5683 // because all functions have linkage.
5684 if (!NewFD->isInvalidDecl() &&
5685 NewFD->getResultType()->isVariablyModifiedType()) {
5686 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
5687 NewFD->setInvalidDecl();
5690 // Handle attributes.
5691 ProcessDeclAttributes(S, NewFD, D,
5692 /*NonInheritable=*/false, /*Inheritable=*/true);
5694 if (!getLangOpts().CPlusPlus) {
5695 // Perform semantic checking on the function declaration.
5696 bool isExplicitSpecialization=false;
5697 if (!NewFD->isInvalidDecl()) {
5698 if (NewFD->isMain())
5699 CheckMain(NewFD, D.getDeclSpec());
5700 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5701 isExplicitSpecialization));
5703 // Make graceful recovery from an invalid redeclaration.
5704 else if (!Previous.empty())
5705 D.setRedeclaration(true);
5706 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
5707 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5708 "previous declaration set still overloaded");
5710 // If the declarator is a template-id, translate the parser's template
5711 // argument list into our AST format.
5712 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5713 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5714 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5715 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
5716 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
5717 TemplateId->NumArgs);
5718 translateTemplateArguments(TemplateArgsPtr,
5721 HasExplicitTemplateArgs = true;
5723 if (NewFD->isInvalidDecl()) {
5724 HasExplicitTemplateArgs = false;
5725 } else if (FunctionTemplate) {
5726 // Function template with explicit template arguments.
5727 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
5728 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
5730 HasExplicitTemplateArgs = false;
5731 } else if (!isFunctionTemplateSpecialization &&
5732 !D.getDeclSpec().isFriendSpecified()) {
5733 // We have encountered something that the user meant to be a
5734 // specialization (because it has explicitly-specified template
5735 // arguments) but that was not introduced with a "template<>" (or had
5736 // too few of them).
5737 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5738 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5739 << FixItHint::CreateInsertion(
5740 D.getDeclSpec().getLocStart(),
5742 isFunctionTemplateSpecialization = true;
5744 // "friend void foo<>(int);" is an implicit specialization decl.
5745 isFunctionTemplateSpecialization = true;
5747 } else if (isFriend && isFunctionTemplateSpecialization) {
5748 // This combination is only possible in a recovery case; the user
5749 // wrote something like:
5750 // template <> friend void foo(int);
5751 // which we're recovering from as if the user had written:
5752 // friend void foo<>(int);
5753 // Go ahead and fake up a template id.
5754 HasExplicitTemplateArgs = true;
5755 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
5756 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
5759 // If it's a friend (and only if it's a friend), it's possible
5760 // that either the specialized function type or the specialized
5761 // template is dependent, and therefore matching will fail. In
5762 // this case, don't check the specialization yet.
5763 bool InstantiationDependent = false;
5764 if (isFunctionTemplateSpecialization && isFriend &&
5765 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
5766 TemplateSpecializationType::anyDependentTemplateArguments(
5767 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
5768 InstantiationDependent))) {
5769 assert(HasExplicitTemplateArgs &&
5770 "friend function specialization without template args");
5771 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
5773 NewFD->setInvalidDecl();
5774 } else if (isFunctionTemplateSpecialization) {
5775 if (CurContext->isDependentContext() && CurContext->isRecord()
5777 isDependentClassScopeExplicitSpecialization = true;
5778 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
5779 diag::ext_function_specialization_in_class :
5780 diag::err_function_specialization_in_class)
5781 << NewFD->getDeclName();
5782 } else if (CheckFunctionTemplateSpecialization(NewFD,
5783 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
5785 NewFD->setInvalidDecl();
5788 // A storage-class-specifier shall not be specified in an explicit
5789 // specialization (14.7.3)
5790 if (SC != SC_None) {
5791 if (SC != NewFD->getStorageClass())
5792 Diag(NewFD->getLocation(),
5793 diag::err_explicit_specialization_inconsistent_storage_class)
5795 << FixItHint::CreateRemoval(
5796 D.getDeclSpec().getStorageClassSpecLoc());
5799 Diag(NewFD->getLocation(),
5800 diag::ext_explicit_specialization_storage_class)
5801 << FixItHint::CreateRemoval(
5802 D.getDeclSpec().getStorageClassSpecLoc());
5805 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
5806 if (CheckMemberSpecialization(NewFD, Previous))
5807 NewFD->setInvalidDecl();
5810 // Perform semantic checking on the function declaration.
5811 if (!isDependentClassScopeExplicitSpecialization) {
5812 if (NewFD->isInvalidDecl()) {
5813 // If this is a class member, mark the class invalid immediately.
5814 // This avoids some consistency errors later.
5815 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
5816 methodDecl->getParent()->setInvalidDecl();
5818 if (NewFD->isMain())
5819 CheckMain(NewFD, D.getDeclSpec());
5820 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5821 isExplicitSpecialization));
5825 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
5826 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5827 "previous declaration set still overloaded");
5829 NamedDecl *PrincipalDecl = (FunctionTemplate
5830 ? cast<NamedDecl>(FunctionTemplate)
5833 if (isFriend && D.isRedeclaration()) {
5834 AccessSpecifier Access = AS_public;
5835 if (!NewFD->isInvalidDecl())
5836 Access = NewFD->getPreviousDecl()->getAccess();
5838 NewFD->setAccess(Access);
5839 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
5841 PrincipalDecl->setObjectOfFriendDecl(true);
5844 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
5845 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
5846 PrincipalDecl->setNonMemberOperator();
5848 // If we have a function template, check the template parameter
5849 // list. This will check and merge default template arguments.
5850 if (FunctionTemplate) {
5851 FunctionTemplateDecl *PrevTemplate =
5852 FunctionTemplate->getPreviousDecl();
5853 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
5854 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
5855 D.getDeclSpec().isFriendSpecified()
5856 ? (D.isFunctionDefinition()
5857 ? TPC_FriendFunctionTemplateDefinition
5858 : TPC_FriendFunctionTemplate)
5859 : (D.getCXXScopeSpec().isSet() &&
5860 DC && DC->isRecord() &&
5861 DC->isDependentContext())
5862 ? TPC_ClassTemplateMember
5863 : TPC_FunctionTemplate);
5866 if (NewFD->isInvalidDecl()) {
5867 // Ignore all the rest of this.
5868 } else if (!D.isRedeclaration()) {
5869 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
5871 // Fake up an access specifier if it's supposed to be a class member.
5872 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
5873 NewFD->setAccess(AS_public);
5875 // Qualified decls generally require a previous declaration.
5876 if (D.getCXXScopeSpec().isSet()) {
5877 // ...with the major exception of templated-scope or
5878 // dependent-scope friend declarations.
5880 // TODO: we currently also suppress this check in dependent
5881 // contexts because (1) the parameter depth will be off when
5882 // matching friend templates and (2) we might actually be
5883 // selecting a friend based on a dependent factor. But there
5884 // are situations where these conditions don't apply and we
5885 // can actually do this check immediately.
5887 (TemplateParamLists.size() ||
5888 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
5889 CurContext->isDependentContext())) {
5892 // The user tried to provide an out-of-line definition for a
5893 // function that is a member of a class or namespace, but there
5894 // was no such member function declared (C++ [class.mfct]p2,
5895 // C++ [namespace.memdef]p2). For example:
5901 // void X::f() { } // ill-formed
5903 // Complain about this problem, and attempt to suggest close
5904 // matches (e.g., those that differ only in cv-qualifiers and
5905 // whether the parameter types are references).
5907 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
5910 AddToScope = ExtraArgs.AddToScope;
5915 // Unqualified local friend declarations are required to resolve
5917 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
5918 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
5921 AddToScope = ExtraArgs.AddToScope;
5926 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
5927 !isFriend && !isFunctionTemplateSpecialization &&
5928 !isExplicitSpecialization) {
5929 // An out-of-line member function declaration must also be a
5930 // definition (C++ [dcl.meaning]p1).
5931 // Note that this is not the case for explicit specializations of
5932 // function templates or member functions of class templates, per
5933 // C++ [temp.expl.spec]p2. We also allow these declarations as an
5934 // extension for compatibility with old SWIG code which likes to
5936 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
5937 << D.getCXXScopeSpec().getRange();
5941 AddKnownFunctionAttributes(NewFD);
5943 if (NewFD->hasAttr<OverloadableAttr>() &&
5944 !NewFD->getType()->getAs<FunctionProtoType>()) {
5945 Diag(NewFD->getLocation(),
5946 diag::err_attribute_overloadable_no_prototype)
5949 // Turn this into a variadic function with no parameters.
5950 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
5951 FunctionProtoType::ExtProtoInfo EPI;
5952 EPI.Variadic = true;
5953 EPI.ExtInfo = FT->getExtInfo();
5955 QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI);
5959 // If there's a #pragma GCC visibility in scope, and this isn't a class
5960 // member, set the visibility of this function.
5961 if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
5962 AddPushedVisibilityAttribute(NewFD);
5964 // If there's a #pragma clang arc_cf_code_audited in scope, consider
5965 // marking the function.
5966 AddCFAuditedAttribute(NewFD);
5968 // If this is a locally-scoped extern C function, update the
5969 // map of such names.
5970 if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
5971 && !NewFD->isInvalidDecl())
5972 RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
5974 // Set this FunctionDecl's range up to the right paren.
5975 NewFD->setRangeEnd(D.getSourceRange().getEnd());
5977 if (getLangOpts().CPlusPlus) {
5978 if (FunctionTemplate) {
5979 if (NewFD->isInvalidDecl())
5980 FunctionTemplate->setInvalidDecl();
5981 return FunctionTemplate;
5985 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
5986 if ((getLangOpts().OpenCLVersion >= 120)
5987 && NewFD->hasAttr<OpenCLKernelAttr>()
5988 && (SC == SC_Static)) {
5989 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
5993 MarkUnusedFileScopedDecl(NewFD);
5995 if (getLangOpts().CUDA)
5996 if (IdentifierInfo *II = NewFD->getIdentifier())
5997 if (!NewFD->isInvalidDecl() &&
5998 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5999 if (II->isStr("cudaConfigureCall")) {
6000 if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
6001 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
6003 Context.setcudaConfigureCallDecl(NewFD);
6007 // Here we have an function template explicit specialization at class scope.
6008 // The actually specialization will be postponed to template instatiation
6009 // time via the ClassScopeFunctionSpecializationDecl node.
6010 if (isDependentClassScopeExplicitSpecialization) {
6011 ClassScopeFunctionSpecializationDecl *NewSpec =
6012 ClassScopeFunctionSpecializationDecl::Create(
6013 Context, CurContext, SourceLocation(),
6014 cast<CXXMethodDecl>(NewFD),
6015 HasExplicitTemplateArgs, TemplateArgs);
6016 CurContext->addDecl(NewSpec);
6023 /// \brief Perform semantic checking of a new function declaration.
6025 /// Performs semantic analysis of the new function declaration
6026 /// NewFD. This routine performs all semantic checking that does not
6027 /// require the actual declarator involved in the declaration, and is
6028 /// used both for the declaration of functions as they are parsed
6029 /// (called via ActOnDeclarator) and for the declaration of functions
6030 /// that have been instantiated via C++ template instantiation (called
6031 /// via InstantiateDecl).
6033 /// \param IsExplicitSpecialization whether this new function declaration is
6034 /// an explicit specialization of the previous declaration.
6036 /// This sets NewFD->isInvalidDecl() to true if there was an error.
6038 /// \returns true if the function declaration is a redeclaration.
6039 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
6040 LookupResult &Previous,
6041 bool IsExplicitSpecialization) {
6042 assert(!NewFD->getResultType()->isVariablyModifiedType()
6043 && "Variably modified return types are not handled here");
6045 // Check for a previous declaration of this name.
6046 if (Previous.empty() && NewFD->isExternC()) {
6047 // Since we did not find anything by this name and we're declaring
6048 // an extern "C" function, look for a non-visible extern "C"
6049 // declaration with the same name.
6050 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
6051 = findLocallyScopedExternalDecl(NewFD->getDeclName());
6052 if (Pos != LocallyScopedExternalDecls.end())
6053 Previous.addDecl(Pos->second);
6056 bool Redeclaration = false;
6058 // Merge or overload the declaration with an existing declaration of
6059 // the same name, if appropriate.
6060 if (!Previous.empty()) {
6061 // Determine whether NewFD is an overload of PrevDecl or
6062 // a declaration that requires merging. If it's an overload,
6063 // there's no more work to do here; we'll just add the new
6064 // function to the scope.
6066 NamedDecl *OldDecl = 0;
6067 if (!AllowOverloadingOfFunction(Previous, Context)) {
6068 Redeclaration = true;
6069 OldDecl = Previous.getFoundDecl();
6071 switch (CheckOverload(S, NewFD, Previous, OldDecl,
6072 /*NewIsUsingDecl*/ false)) {
6074 Redeclaration = true;
6077 case Ovl_NonFunction:
6078 Redeclaration = true;
6082 Redeclaration = false;
6086 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
6087 // If a function name is overloadable in C, then every function
6088 // with that name must be marked "overloadable".
6089 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
6090 << Redeclaration << NewFD;
6091 NamedDecl *OverloadedDecl = 0;
6093 OverloadedDecl = OldDecl;
6094 else if (!Previous.empty())
6095 OverloadedDecl = Previous.getRepresentativeDecl();
6097 Diag(OverloadedDecl->getLocation(),
6098 diag::note_attribute_overloadable_prev_overload);
6099 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
6104 if (Redeclaration) {
6105 // NewFD and OldDecl represent declarations that need to be
6107 if (MergeFunctionDecl(NewFD, OldDecl, S)) {
6108 NewFD->setInvalidDecl();
6109 return Redeclaration;
6113 Previous.addDecl(OldDecl);
6115 if (FunctionTemplateDecl *OldTemplateDecl
6116 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
6117 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
6118 FunctionTemplateDecl *NewTemplateDecl
6119 = NewFD->getDescribedFunctionTemplate();
6120 assert(NewTemplateDecl && "Template/non-template mismatch");
6121 if (CXXMethodDecl *Method
6122 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
6123 Method->setAccess(OldTemplateDecl->getAccess());
6124 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
6127 // If this is an explicit specialization of a member that is a function
6128 // template, mark it as a member specialization.
6129 if (IsExplicitSpecialization &&
6130 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
6131 NewTemplateDecl->setMemberSpecialization();
6132 assert(OldTemplateDecl->isMemberSpecialization());
6136 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
6137 NewFD->setAccess(OldDecl->getAccess());
6138 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
6143 // Semantic checking for this function declaration (in isolation).
6144 if (getLangOpts().CPlusPlus) {
6145 // C++-specific checks.
6146 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
6147 CheckConstructor(Constructor);
6148 } else if (CXXDestructorDecl *Destructor =
6149 dyn_cast<CXXDestructorDecl>(NewFD)) {
6150 CXXRecordDecl *Record = Destructor->getParent();
6151 QualType ClassType = Context.getTypeDeclType(Record);
6153 // FIXME: Shouldn't we be able to perform this check even when the class
6154 // type is dependent? Both gcc and edg can handle that.
6155 if (!ClassType->isDependentType()) {
6156 DeclarationName Name
6157 = Context.DeclarationNames.getCXXDestructorName(
6158 Context.getCanonicalType(ClassType));
6159 if (NewFD->getDeclName() != Name) {
6160 Diag(NewFD->getLocation(), diag::err_destructor_name);
6161 NewFD->setInvalidDecl();
6162 return Redeclaration;
6165 } else if (CXXConversionDecl *Conversion
6166 = dyn_cast<CXXConversionDecl>(NewFD)) {
6167 ActOnConversionDeclarator(Conversion);
6170 // Find any virtual functions that this function overrides.
6171 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
6172 if (!Method->isFunctionTemplateSpecialization() &&
6173 !Method->getDescribedFunctionTemplate() &&
6174 Method->isCanonicalDecl()) {
6175 if (AddOverriddenMethods(Method->getParent(), Method)) {
6176 // If the function was marked as "static", we have a problem.
6177 if (NewFD->getStorageClass() == SC_Static) {
6178 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
6183 if (Method->isStatic())
6184 checkThisInStaticMemberFunctionType(Method);
6187 // Extra checking for C++ overloaded operators (C++ [over.oper]).
6188 if (NewFD->isOverloadedOperator() &&
6189 CheckOverloadedOperatorDeclaration(NewFD)) {
6190 NewFD->setInvalidDecl();
6191 return Redeclaration;
6194 // Extra checking for C++0x literal operators (C++0x [over.literal]).
6195 if (NewFD->getLiteralIdentifier() &&
6196 CheckLiteralOperatorDeclaration(NewFD)) {
6197 NewFD->setInvalidDecl();
6198 return Redeclaration;
6201 // In C++, check default arguments now that we have merged decls. Unless
6202 // the lexical context is the class, because in this case this is done
6203 // during delayed parsing anyway.
6204 if (!CurContext->isRecord())
6205 CheckCXXDefaultArguments(NewFD);
6207 // If this function declares a builtin function, check the type of this
6208 // declaration against the expected type for the builtin.
6209 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
6210 ASTContext::GetBuiltinTypeError Error;
6211 QualType T = Context.GetBuiltinType(BuiltinID, Error);
6212 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
6213 // The type of this function differs from the type of the builtin,
6214 // so forget about the builtin entirely.
6215 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
6219 // If this function is declared as being extern "C", then check to see if
6220 // the function returns a UDT (class, struct, or union type) that is not C
6221 // compatible, and if it does, warn the user.
6222 if (NewFD->isExternC()) {
6223 QualType R = NewFD->getResultType();
6224 if (R->isIncompleteType() && !R->isVoidType())
6225 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
6227 else if (!R.isPODType(Context) && !R->isVoidType() &&
6228 !R->isObjCObjectPointerType())
6229 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
6232 return Redeclaration;
6235 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
6236 // C++11 [basic.start.main]p3: A program that declares main to be inline,
6237 // static or constexpr is ill-formed.
6238 // C99 6.7.4p4: In a hosted environment, the inline function specifier
6239 // shall not appear in a declaration of main.
6240 // static main is not an error under C99, but we should warn about it.
6241 if (FD->getStorageClass() == SC_Static)
6242 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
6243 ? diag::err_static_main : diag::warn_static_main)
6244 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
6245 if (FD->isInlineSpecified())
6246 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
6247 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
6248 if (FD->isConstexpr()) {
6249 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
6250 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
6251 FD->setConstexpr(false);
6254 QualType T = FD->getType();
6255 assert(T->isFunctionType() && "function decl is not of function type");
6256 const FunctionType* FT = T->castAs<FunctionType>();
6258 // All the standards say that main() should should return 'int'.
6259 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
6260 // In C and C++, main magically returns 0 if you fall off the end;
6261 // set the flag which tells us that.
6262 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
6263 FD->setHasImplicitReturnZero(true);
6265 // In C with GNU extensions we allow main() to have non-integer return
6266 // type, but we should warn about the extension, and we disable the
6267 // implicit-return-zero rule.
6268 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
6269 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
6271 // Otherwise, this is just a flat-out error.
6273 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
6274 FD->setInvalidDecl(true);
6277 // Treat protoless main() as nullary.
6278 if (isa<FunctionNoProtoType>(FT)) return;
6280 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
6281 unsigned nparams = FTP->getNumArgs();
6282 assert(FD->getNumParams() == nparams);
6284 bool HasExtraParameters = (nparams > 3);
6286 // Darwin passes an undocumented fourth argument of type char**. If
6287 // other platforms start sprouting these, the logic below will start
6289 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
6290 HasExtraParameters = false;
6292 if (HasExtraParameters) {
6293 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
6294 FD->setInvalidDecl(true);
6298 // FIXME: a lot of the following diagnostics would be improved
6299 // if we had some location information about types.
6302 Context.getPointerType(Context.getPointerType(Context.CharTy));
6303 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
6305 for (unsigned i = 0; i < nparams; ++i) {
6306 QualType AT = FTP->getArgType(i);
6308 bool mismatch = true;
6310 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
6312 else if (Expected[i] == CharPP) {
6313 // As an extension, the following forms are okay:
6315 // char const * const *
6318 QualifierCollector qs;
6319 const PointerType* PT;
6320 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
6321 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
6322 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
6324 mismatch = !qs.empty();
6329 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
6330 // TODO: suggest replacing given type with expected type
6331 FD->setInvalidDecl(true);
6335 if (nparams == 1 && !FD->isInvalidDecl()) {
6336 Diag(FD->getLocation(), diag::warn_main_one_arg);
6339 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
6340 Diag(FD->getLocation(), diag::err_main_template_decl);
6341 FD->setInvalidDecl();
6345 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
6346 // FIXME: Need strict checking. In C89, we need to check for
6347 // any assignment, increment, decrement, function-calls, or
6348 // commas outside of a sizeof. In C99, it's the same list,
6349 // except that the aforementioned are allowed in unevaluated
6350 // expressions. Everything else falls under the
6351 // "may accept other forms of constant expressions" exception.
6352 // (We never end up here for C++, so the constant expression
6353 // rules there don't matter.)
6354 if (Init->isConstantInitializer(Context, false))
6356 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
6357 << Init->getSourceRange();
6362 // Visits an initialization expression to see if OrigDecl is evaluated in
6363 // its own initialization and throws a warning if it does.
6364 class SelfReferenceChecker
6365 : public EvaluatedExprVisitor<SelfReferenceChecker> {
6370 bool isReferenceType;
6373 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
6375 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
6376 S(S), OrigDecl(OrigDecl) {
6378 isRecordType = false;
6379 isReferenceType = false;
6380 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
6381 isPODType = VD->getType().isPODType(S.Context);
6382 isRecordType = VD->getType()->isRecordType();
6383 isReferenceType = VD->getType()->isReferenceType();
6387 // For most expressions, the cast is directly above the DeclRefExpr.
6388 // For conditional operators, the cast can be outside the conditional
6389 // operator if both expressions are DeclRefExpr's.
6390 void HandleValue(Expr *E) {
6391 if (isReferenceType)
6393 E = E->IgnoreParenImpCasts();
6394 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
6395 HandleDeclRefExpr(DRE);
6399 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6400 HandleValue(CO->getTrueExpr());
6401 HandleValue(CO->getFalseExpr());
6405 if (isa<MemberExpr>(E)) {
6406 Expr *Base = E->IgnoreParenImpCasts();
6407 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
6408 // Check for static member variables and don't warn on them.
6409 if (!isa<FieldDecl>(ME->getMemberDecl()))
6411 Base = ME->getBase()->IgnoreParenImpCasts();
6413 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
6414 HandleDeclRefExpr(DRE);
6419 // Reference types are handled here since all uses of references are
6420 // bad, not just r-value uses.
6421 void VisitDeclRefExpr(DeclRefExpr *E) {
6422 if (isReferenceType)
6423 HandleDeclRefExpr(E);
6426 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
6427 if (E->getCastKind() == CK_LValueToRValue ||
6428 (isRecordType && E->getCastKind() == CK_NoOp))
6429 HandleValue(E->getSubExpr());
6431 Inherited::VisitImplicitCastExpr(E);
6434 void VisitMemberExpr(MemberExpr *E) {
6435 // Don't warn on arrays since they can be treated as pointers.
6436 if (E->getType()->canDecayToPointerType()) return;
6438 // Warn when a non-static method call is followed by non-static member
6439 // field accesses, which is followed by a DeclRefExpr.
6440 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
6441 bool Warn = (MD && !MD->isStatic());
6442 Expr *Base = E->getBase()->IgnoreParenImpCasts();
6443 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
6444 if (!isa<FieldDecl>(ME->getMemberDecl()))
6446 Base = ME->getBase()->IgnoreParenImpCasts();
6449 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
6451 HandleDeclRefExpr(DRE);
6455 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
6456 // Visit that expression.
6460 void VisitUnaryOperator(UnaryOperator *E) {
6461 // For POD record types, addresses of its own members are well-defined.
6462 if (E->getOpcode() == UO_AddrOf && isRecordType &&
6463 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
6465 HandleValue(E->getSubExpr());
6468 Inherited::VisitUnaryOperator(E);
6471 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
6473 void HandleDeclRefExpr(DeclRefExpr *DRE) {
6474 Decl* ReferenceDecl = DRE->getDecl();
6475 if (OrigDecl != ReferenceDecl) return;
6476 unsigned diag = isReferenceType
6477 ? diag::warn_uninit_self_reference_in_reference_init
6478 : diag::warn_uninit_self_reference_in_init;
6479 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
6481 << DRE->getNameInfo().getName()
6482 << OrigDecl->getLocation()
6483 << DRE->getSourceRange());
6487 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
6488 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
6490 // Parameters arguments are occassionially constructed with itself,
6491 // for instance, in recursive functions. Skip them.
6492 if (isa<ParmVarDecl>(OrigDecl))
6495 E = E->IgnoreParens();
6497 // Skip checking T a = a where T is not a record or reference type.
6498 // Doing so is a way to silence uninitialized warnings.
6499 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
6500 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
6501 if (ICE->getCastKind() == CK_LValueToRValue)
6502 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
6503 if (DRE->getDecl() == OrigDecl)
6506 SelfReferenceChecker(S, OrigDecl).Visit(E);
6510 /// AddInitializerToDecl - Adds the initializer Init to the
6511 /// declaration dcl. If DirectInit is true, this is C++ direct
6512 /// initialization rather than copy initialization.
6513 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
6514 bool DirectInit, bool TypeMayContainAuto) {
6515 // If there is no declaration, there was an error parsing it. Just ignore
6517 if (RealDecl == 0 || RealDecl->isInvalidDecl())
6520 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
6521 // With declarators parsed the way they are, the parser cannot
6522 // distinguish between a normal initializer and a pure-specifier.
6523 // Thus this grotesque test.
6525 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
6526 Context.getCanonicalType(IL->getType()) == Context.IntTy)
6527 CheckPureMethod(Method, Init->getSourceRange());
6529 Diag(Method->getLocation(), diag::err_member_function_initialization)
6530 << Method->getDeclName() << Init->getSourceRange();
6531 Method->setInvalidDecl();
6536 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6538 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
6539 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
6540 RealDecl->setInvalidDecl();
6544 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
6546 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
6548 if (TypeMayContainAuto &&
6549 (Auto = VDecl->getType()->getContainedAutoType()) &&
6550 !Auto->isDeduced()) {
6551 Expr *DeduceInit = Init;
6552 // Initializer could be a C++ direct-initializer. Deduction only works if it
6553 // contains exactly one expression.
6554 if (CXXDirectInit) {
6555 if (CXXDirectInit->getNumExprs() == 0) {
6556 // It isn't possible to write this directly, but it is possible to
6557 // end up in this situation with "auto x(some_pack...);"
6558 Diag(CXXDirectInit->getLocStart(),
6559 diag::err_auto_var_init_no_expression)
6560 << VDecl->getDeclName() << VDecl->getType()
6561 << VDecl->getSourceRange();
6562 RealDecl->setInvalidDecl();
6564 } else if (CXXDirectInit->getNumExprs() > 1) {
6565 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
6566 diag::err_auto_var_init_multiple_expressions)
6567 << VDecl->getDeclName() << VDecl->getType()
6568 << VDecl->getSourceRange();
6569 RealDecl->setInvalidDecl();
6572 DeduceInit = CXXDirectInit->getExpr(0);
6575 TypeSourceInfo *DeducedType = 0;
6576 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
6578 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
6580 RealDecl->setInvalidDecl();
6583 VDecl->setTypeSourceInfo(DeducedType);
6584 VDecl->setType(DeducedType->getType());
6585 VDecl->ClearLinkageCache();
6587 // In ARC, infer lifetime.
6588 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
6589 VDecl->setInvalidDecl();
6591 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
6592 // 'id' instead of a specific object type prevents most of our usual checks.
6593 // We only want to warn outside of template instantiations, though:
6594 // inside a template, the 'id' could have come from a parameter.
6595 if (ActiveTemplateInstantiations.empty() &&
6596 DeducedType->getType()->isObjCIdType()) {
6597 SourceLocation Loc = DeducedType->getTypeLoc().getBeginLoc();
6598 Diag(Loc, diag::warn_auto_var_is_id)
6599 << VDecl->getDeclName() << DeduceInit->getSourceRange();
6602 // If this is a redeclaration, check that the type we just deduced matches
6603 // the previously declared type.
6604 if (VarDecl *Old = VDecl->getPreviousDecl())
6605 MergeVarDeclTypes(VDecl, Old);
6608 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
6609 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
6610 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
6611 VDecl->setInvalidDecl();
6615 if (!VDecl->getType()->isDependentType()) {
6616 // A definition must end up with a complete type, which means it must be
6617 // complete with the restriction that an array type might be completed by
6618 // the initializer; note that later code assumes this restriction.
6619 QualType BaseDeclType = VDecl->getType();
6620 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
6621 BaseDeclType = Array->getElementType();
6622 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
6623 diag::err_typecheck_decl_incomplete_type)) {
6624 RealDecl->setInvalidDecl();
6628 // The variable can not have an abstract class type.
6629 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6630 diag::err_abstract_type_in_decl,
6631 AbstractVariableType))
6632 VDecl->setInvalidDecl();
6636 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
6637 Diag(VDecl->getLocation(), diag::err_redefinition)
6638 << VDecl->getDeclName();
6639 Diag(Def->getLocation(), diag::note_previous_definition);
6640 VDecl->setInvalidDecl();
6644 const VarDecl* PrevInit = 0;
6645 if (getLangOpts().CPlusPlus) {
6646 // C++ [class.static.data]p4
6647 // If a static data member is of const integral or const
6648 // enumeration type, its declaration in the class definition can
6649 // specify a constant-initializer which shall be an integral
6650 // constant expression (5.19). In that case, the member can appear
6651 // in integral constant expressions. The member shall still be
6652 // defined in a namespace scope if it is used in the program and the
6653 // namespace scope definition shall not contain an initializer.
6655 // We already performed a redefinition check above, but for static
6656 // data members we also need to check whether there was an in-class
6657 // declaration with an initializer.
6658 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
6659 Diag(VDecl->getLocation(), diag::err_redefinition)
6660 << VDecl->getDeclName();
6661 Diag(PrevInit->getLocation(), diag::note_previous_definition);
6665 if (VDecl->hasLocalStorage())
6666 getCurFunction()->setHasBranchProtectedScope();
6668 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
6669 VDecl->setInvalidDecl();
6674 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
6675 // a kernel function cannot be initialized."
6676 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
6677 Diag(VDecl->getLocation(), diag::err_local_cant_init);
6678 VDecl->setInvalidDecl();
6682 // Get the decls type and save a reference for later, since
6683 // CheckInitializerTypes may change it.
6684 QualType DclT = VDecl->getType(), SavT = DclT;
6686 // Top-level message sends default to 'id' when we're in a debugger
6687 // and we are assigning it to a variable of 'id' type.
6688 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCIdType())
6689 if (Init->getType() == Context.UnknownAnyTy && isa<ObjCMessageExpr>(Init)) {
6690 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
6691 if (Result.isInvalid()) {
6692 VDecl->setInvalidDecl();
6695 Init = Result.take();
6698 // Perform the initialization.
6699 if (!VDecl->isInvalidDecl()) {
6700 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6701 InitializationKind Kind
6703 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
6704 Init->getLocStart(),
6706 : InitializationKind::CreateDirectList(
6707 VDecl->getLocation())
6708 : InitializationKind::CreateCopy(VDecl->getLocation(),
6709 Init->getLocStart());
6711 Expr **Args = &Init;
6712 unsigned NumArgs = 1;
6713 if (CXXDirectInit) {
6714 Args = CXXDirectInit->getExprs();
6715 NumArgs = CXXDirectInit->getNumExprs();
6717 InitializationSequence InitSeq(*this, Entity, Kind, Args, NumArgs);
6718 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
6719 MultiExprArg(Args, NumArgs), &DclT);
6720 if (Result.isInvalid()) {
6721 VDecl->setInvalidDecl();
6725 Init = Result.takeAs<Expr>();
6728 // Check for self-references within variable initializers.
6729 // Variables declared within a function/method body (except for references)
6730 // are handled by a dataflow analysis.
6731 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
6732 VDecl->getType()->isReferenceType()) {
6733 CheckSelfReference(*this, RealDecl, Init, DirectInit);
6736 // If the type changed, it means we had an incomplete type that was
6737 // completed by the initializer. For example:
6738 // int ary[] = { 1, 3, 5 };
6739 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
6740 if (!VDecl->isInvalidDecl() && (DclT != SavT))
6741 VDecl->setType(DclT);
6743 // Check any implicit conversions within the expression.
6744 CheckImplicitConversions(Init, VDecl->getLocation());
6746 if (!VDecl->isInvalidDecl()) {
6747 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
6749 if (VDecl->hasAttr<BlocksAttr>())
6750 checkRetainCycles(VDecl, Init);
6752 // It is safe to assign a weak reference into a strong variable.
6753 // Although this code can still have problems:
6754 // id x = self.weakProp;
6755 // id y = self.weakProp;
6756 // we do not warn to warn spuriously when 'x' and 'y' are on separate
6757 // paths through the function. This should be revisited if
6758 // -Wrepeated-use-of-weak is made flow-sensitive.
6759 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
6760 DiagnosticsEngine::Level Level =
6761 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
6762 Init->getLocStart());
6763 if (Level != DiagnosticsEngine::Ignored)
6764 getCurFunction()->markSafeWeakUse(Init);
6768 Init = MaybeCreateExprWithCleanups(Init);
6769 // Attach the initializer to the decl.
6770 VDecl->setInit(Init);
6772 if (VDecl->isLocalVarDecl()) {
6773 // C99 6.7.8p4: All the expressions in an initializer for an object that has
6774 // static storage duration shall be constant expressions or string literals.
6775 // C++ does not have this restriction.
6776 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
6777 VDecl->getStorageClass() == SC_Static)
6778 CheckForConstantInitializer(Init, DclT);
6779 } else if (VDecl->isStaticDataMember() &&
6780 VDecl->getLexicalDeclContext()->isRecord()) {
6781 // This is an in-class initialization for a static data member, e.g.,
6784 // static const int value = 17;
6787 // C++ [class.mem]p4:
6788 // A member-declarator can contain a constant-initializer only
6789 // if it declares a static member (9.4) of const integral or
6790 // const enumeration type, see 9.4.2.
6792 // C++11 [class.static.data]p3:
6793 // If a non-volatile const static data member is of integral or
6794 // enumeration type, its declaration in the class definition can
6795 // specify a brace-or-equal-initializer in which every initalizer-clause
6796 // that is an assignment-expression is a constant expression. A static
6797 // data member of literal type can be declared in the class definition
6798 // with the constexpr specifier; if so, its declaration shall specify a
6799 // brace-or-equal-initializer in which every initializer-clause that is
6800 // an assignment-expression is a constant expression.
6802 // Do nothing on dependent types.
6803 if (DclT->isDependentType()) {
6805 // Allow any 'static constexpr' members, whether or not they are of literal
6806 // type. We separately check that every constexpr variable is of literal
6808 } else if (VDecl->isConstexpr()) {
6810 // Require constness.
6811 } else if (!DclT.isConstQualified()) {
6812 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
6813 << Init->getSourceRange();
6814 VDecl->setInvalidDecl();
6816 // We allow integer constant expressions in all cases.
6817 } else if (DclT->isIntegralOrEnumerationType()) {
6818 // Check whether the expression is a constant expression.
6820 if (getLangOpts().CPlusPlus0x && DclT.isVolatileQualified())
6821 // In C++11, a non-constexpr const static data member with an
6822 // in-class initializer cannot be volatile.
6823 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
6824 else if (Init->isValueDependent())
6825 ; // Nothing to check.
6826 else if (Init->isIntegerConstantExpr(Context, &Loc))
6827 ; // Ok, it's an ICE!
6828 else if (Init->isEvaluatable(Context)) {
6829 // If we can constant fold the initializer through heroics, accept it,
6830 // but report this as a use of an extension for -pedantic.
6831 Diag(Loc, diag::ext_in_class_initializer_non_constant)
6832 << Init->getSourceRange();
6834 // Otherwise, this is some crazy unknown case. Report the issue at the
6835 // location provided by the isIntegerConstantExpr failed check.
6836 Diag(Loc, diag::err_in_class_initializer_non_constant)
6837 << Init->getSourceRange();
6838 VDecl->setInvalidDecl();
6841 // We allow foldable floating-point constants as an extension.
6842 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
6843 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
6844 << DclT << Init->getSourceRange();
6845 if (getLangOpts().CPlusPlus0x)
6846 Diag(VDecl->getLocation(),
6847 diag::note_in_class_initializer_float_type_constexpr)
6848 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
6850 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
6851 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
6852 << Init->getSourceRange();
6853 VDecl->setInvalidDecl();
6856 // Suggest adding 'constexpr' in C++11 for literal types.
6857 } else if (getLangOpts().CPlusPlus0x && DclT->isLiteralType()) {
6858 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
6859 << DclT << Init->getSourceRange()
6860 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
6861 VDecl->setConstexpr(true);
6864 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
6865 << DclT << Init->getSourceRange();
6866 VDecl->setInvalidDecl();
6868 } else if (VDecl->isFileVarDecl()) {
6869 if (VDecl->getStorageClassAsWritten() == SC_Extern &&
6870 (!getLangOpts().CPlusPlus ||
6871 !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
6872 Diag(VDecl->getLocation(), diag::warn_extern_init);
6874 // C99 6.7.8p4. All file scoped initializers need to be constant.
6875 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
6876 CheckForConstantInitializer(Init, DclT);
6879 // We will represent direct-initialization similarly to copy-initialization:
6880 // int x(1); -as-> int x = 1;
6881 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
6883 // Clients that want to distinguish between the two forms, can check for
6884 // direct initializer using VarDecl::getInitStyle().
6885 // A major benefit is that clients that don't particularly care about which
6886 // exactly form was it (like the CodeGen) can handle both cases without
6887 // special case code.
6890 // The form of initialization (using parentheses or '=') is generally
6891 // insignificant, but does matter when the entity being initialized has a
6893 if (CXXDirectInit) {
6894 assert(DirectInit && "Call-style initializer must be direct init.");
6895 VDecl->setInitStyle(VarDecl::CallInit);
6896 } else if (DirectInit) {
6897 // This must be list-initialization. No other way is direct-initialization.
6898 VDecl->setInitStyle(VarDecl::ListInit);
6901 CheckCompleteVariableDeclaration(VDecl);
6904 /// ActOnInitializerError - Given that there was an error parsing an
6905 /// initializer for the given declaration, try to return to some form
6907 void Sema::ActOnInitializerError(Decl *D) {
6908 // Our main concern here is re-establishing invariants like "a
6909 // variable's type is either dependent or complete".
6910 if (!D || D->isInvalidDecl()) return;
6912 VarDecl *VD = dyn_cast<VarDecl>(D);
6915 // Auto types are meaningless if we can't make sense of the initializer.
6916 if (ParsingInitForAutoVars.count(D)) {
6917 D->setInvalidDecl();
6921 QualType Ty = VD->getType();
6922 if (Ty->isDependentType()) return;
6924 // Require a complete type.
6925 if (RequireCompleteType(VD->getLocation(),
6926 Context.getBaseElementType(Ty),
6927 diag::err_typecheck_decl_incomplete_type)) {
6928 VD->setInvalidDecl();
6932 // Require an abstract type.
6933 if (RequireNonAbstractType(VD->getLocation(), Ty,
6934 diag::err_abstract_type_in_decl,
6935 AbstractVariableType)) {
6936 VD->setInvalidDecl();
6940 // Don't bother complaining about constructors or destructors,
6944 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
6945 bool TypeMayContainAuto) {
6946 // If there is no declaration, there was an error parsing it. Just ignore it.
6950 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
6951 QualType Type = Var->getType();
6953 // C++11 [dcl.spec.auto]p3
6954 if (TypeMayContainAuto && Type->getContainedAutoType()) {
6955 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
6956 << Var->getDeclName() << Type;
6957 Var->setInvalidDecl();
6961 // C++11 [class.static.data]p3: A static data member can be declared with
6962 // the constexpr specifier; if so, its declaration shall specify
6963 // a brace-or-equal-initializer.
6964 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
6965 // the definition of a variable [...] or the declaration of a static data
6967 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
6968 if (Var->isStaticDataMember())
6969 Diag(Var->getLocation(),
6970 diag::err_constexpr_static_mem_var_requires_init)
6971 << Var->getDeclName();
6973 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
6974 Var->setInvalidDecl();
6978 switch (Var->isThisDeclarationADefinition()) {
6979 case VarDecl::Definition:
6980 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
6983 // We have an out-of-line definition of a static data member
6984 // that has an in-class initializer, so we type-check this like
6989 case VarDecl::DeclarationOnly:
6990 // It's only a declaration.
6992 // Block scope. C99 6.7p7: If an identifier for an object is
6993 // declared with no linkage (C99 6.2.2p6), the type for the
6994 // object shall be complete.
6995 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
6996 !Var->getLinkage() && !Var->isInvalidDecl() &&
6997 RequireCompleteType(Var->getLocation(), Type,
6998 diag::err_typecheck_decl_incomplete_type))
6999 Var->setInvalidDecl();
7001 // Make sure that the type is not abstract.
7002 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
7003 RequireNonAbstractType(Var->getLocation(), Type,
7004 diag::err_abstract_type_in_decl,
7005 AbstractVariableType))
7006 Var->setInvalidDecl();
7007 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
7008 Var->getStorageClass() == SC_PrivateExtern) {
7009 Diag(Var->getLocation(), diag::warn_private_extern);
7010 Diag(Var->getLocation(), diag::note_private_extern);
7015 case VarDecl::TentativeDefinition:
7016 // File scope. C99 6.9.2p2: A declaration of an identifier for an
7017 // object that has file scope without an initializer, and without a
7018 // storage-class specifier or with the storage-class specifier "static",
7019 // constitutes a tentative definition. Note: A tentative definition with
7020 // external linkage is valid (C99 6.2.2p5).
7021 if (!Var->isInvalidDecl()) {
7022 if (const IncompleteArrayType *ArrayT
7023 = Context.getAsIncompleteArrayType(Type)) {
7024 if (RequireCompleteType(Var->getLocation(),
7025 ArrayT->getElementType(),
7026 diag::err_illegal_decl_array_incomplete_type))
7027 Var->setInvalidDecl();
7028 } else if (Var->getStorageClass() == SC_Static) {
7029 // C99 6.9.2p3: If the declaration of an identifier for an object is
7030 // a tentative definition and has internal linkage (C99 6.2.2p3), the
7031 // declared type shall not be an incomplete type.
7032 // NOTE: code such as the following
7034 // struct s { int a; };
7035 // is accepted by gcc. Hence here we issue a warning instead of
7036 // an error and we do not invalidate the static declaration.
7037 // NOTE: to avoid multiple warnings, only check the first declaration.
7038 if (Var->getPreviousDecl() == 0)
7039 RequireCompleteType(Var->getLocation(), Type,
7040 diag::ext_typecheck_decl_incomplete_type);
7044 // Record the tentative definition; we're done.
7045 if (!Var->isInvalidDecl())
7046 TentativeDefinitions.push_back(Var);
7050 // Provide a specific diagnostic for uninitialized variable
7051 // definitions with incomplete array type.
7052 if (Type->isIncompleteArrayType()) {
7053 Diag(Var->getLocation(),
7054 diag::err_typecheck_incomplete_array_needs_initializer);
7055 Var->setInvalidDecl();
7059 // Provide a specific diagnostic for uninitialized variable
7060 // definitions with reference type.
7061 if (Type->isReferenceType()) {
7062 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
7063 << Var->getDeclName()
7064 << SourceRange(Var->getLocation(), Var->getLocation());
7065 Var->setInvalidDecl();
7069 // Do not attempt to type-check the default initializer for a
7070 // variable with dependent type.
7071 if (Type->isDependentType())
7074 if (Var->isInvalidDecl())
7077 if (RequireCompleteType(Var->getLocation(),
7078 Context.getBaseElementType(Type),
7079 diag::err_typecheck_decl_incomplete_type)) {
7080 Var->setInvalidDecl();
7084 // The variable can not have an abstract class type.
7085 if (RequireNonAbstractType(Var->getLocation(), Type,
7086 diag::err_abstract_type_in_decl,
7087 AbstractVariableType)) {
7088 Var->setInvalidDecl();
7092 // Check for jumps past the implicit initializer. C++0x
7093 // clarifies that this applies to a "variable with automatic
7094 // storage duration", not a "local variable".
7095 // C++11 [stmt.dcl]p3
7096 // A program that jumps from a point where a variable with automatic
7097 // storage duration is not in scope to a point where it is in scope is
7098 // ill-formed unless the variable has scalar type, class type with a
7099 // trivial default constructor and a trivial destructor, a cv-qualified
7100 // version of one of these types, or an array of one of the preceding
7101 // types and is declared without an initializer.
7102 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
7103 if (const RecordType *Record
7104 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
7105 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
7106 // Mark the function for further checking even if the looser rules of
7107 // C++11 do not require such checks, so that we can diagnose
7108 // incompatibilities with C++98.
7109 if (!CXXRecord->isPOD())
7110 getCurFunction()->setHasBranchProtectedScope();
7114 // C++03 [dcl.init]p9:
7115 // If no initializer is specified for an object, and the
7116 // object is of (possibly cv-qualified) non-POD class type (or
7117 // array thereof), the object shall be default-initialized; if
7118 // the object is of const-qualified type, the underlying class
7119 // type shall have a user-declared default
7120 // constructor. Otherwise, if no initializer is specified for
7121 // a non- static object, the object and its subobjects, if
7122 // any, have an indeterminate initial value); if the object
7123 // or any of its subobjects are of const-qualified type, the
7124 // program is ill-formed.
7125 // C++0x [dcl.init]p11:
7126 // If no initializer is specified for an object, the object is
7127 // default-initialized; [...].
7128 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
7129 InitializationKind Kind
7130 = InitializationKind::CreateDefault(Var->getLocation());
7132 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
7133 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, MultiExprArg());
7134 if (Init.isInvalid())
7135 Var->setInvalidDecl();
7136 else if (Init.get()) {
7137 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
7138 // This is important for template substitution.
7139 Var->setInitStyle(VarDecl::CallInit);
7142 CheckCompleteVariableDeclaration(Var);
7146 void Sema::ActOnCXXForRangeDecl(Decl *D) {
7147 VarDecl *VD = dyn_cast<VarDecl>(D);
7149 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
7150 D->setInvalidDecl();
7154 VD->setCXXForRangeDecl(true);
7156 // for-range-declaration cannot be given a storage class specifier.
7158 switch (VD->getStorageClassAsWritten()) {
7167 case SC_PrivateExtern:
7176 case SC_OpenCLWorkGroupLocal:
7177 llvm_unreachable("Unexpected storage class");
7179 if (VD->isConstexpr())
7182 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
7183 << VD->getDeclName() << Error;
7184 D->setInvalidDecl();
7188 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
7189 if (var->isInvalidDecl()) return;
7191 // In ARC, don't allow jumps past the implicit initialization of a
7192 // local retaining variable.
7193 if (getLangOpts().ObjCAutoRefCount &&
7194 var->hasLocalStorage()) {
7195 switch (var->getType().getObjCLifetime()) {
7196 case Qualifiers::OCL_None:
7197 case Qualifiers::OCL_ExplicitNone:
7198 case Qualifiers::OCL_Autoreleasing:
7201 case Qualifiers::OCL_Weak:
7202 case Qualifiers::OCL_Strong:
7203 getCurFunction()->setHasBranchProtectedScope();
7208 if (var->isThisDeclarationADefinition() &&
7209 var->getLinkage() == ExternalLinkage) {
7210 // Find a previous declaration that's not a definition.
7211 VarDecl *prev = var->getPreviousDecl();
7212 while (prev && prev->isThisDeclarationADefinition())
7213 prev = prev->getPreviousDecl();
7216 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
7219 // All the following checks are C++ only.
7220 if (!getLangOpts().CPlusPlus) return;
7222 QualType type = var->getType();
7223 if (type->isDependentType()) return;
7225 // __block variables might require us to capture a copy-initializer.
7226 if (var->hasAttr<BlocksAttr>()) {
7227 // It's currently invalid to ever have a __block variable with an
7228 // array type; should we diagnose that here?
7230 // Regardless, we don't want to ignore array nesting when
7231 // constructing this copy.
7232 if (type->isStructureOrClassType()) {
7233 SourceLocation poi = var->getLocation();
7234 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
7236 PerformCopyInitialization(
7237 InitializedEntity::InitializeBlock(poi, type, false),
7238 poi, Owned(varRef));
7239 if (!result.isInvalid()) {
7240 result = MaybeCreateExprWithCleanups(result);
7241 Expr *init = result.takeAs<Expr>();
7242 Context.setBlockVarCopyInits(var, init);
7247 Expr *Init = var->getInit();
7248 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
7249 QualType baseType = Context.getBaseElementType(type);
7251 if (!var->getDeclContext()->isDependentContext() &&
7252 Init && !Init->isValueDependent()) {
7253 if (IsGlobal && !var->isConstexpr() &&
7254 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
7256 != DiagnosticsEngine::Ignored &&
7257 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
7258 Diag(var->getLocation(), diag::warn_global_constructor)
7259 << Init->getSourceRange();
7261 if (var->isConstexpr()) {
7262 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
7263 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
7264 SourceLocation DiagLoc = var->getLocation();
7265 // If the note doesn't add any useful information other than a source
7266 // location, fold it into the primary diagnostic.
7267 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
7268 diag::note_invalid_subexpr_in_const_expr) {
7269 DiagLoc = Notes[0].first;
7272 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
7273 << var << Init->getSourceRange();
7274 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
7275 Diag(Notes[I].first, Notes[I].second);
7277 } else if (var->isUsableInConstantExpressions(Context)) {
7278 // Check whether the initializer of a const variable of integral or
7279 // enumeration type is an ICE now, since we can't tell whether it was
7280 // initialized by a constant expression if we check later.
7281 var->checkInitIsICE();
7285 // Require the destructor.
7286 if (const RecordType *recordType = baseType->getAs<RecordType>())
7287 FinalizeVarWithDestructor(var, recordType);
7290 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
7291 /// any semantic actions necessary after any initializer has been attached.
7293 Sema::FinalizeDeclaration(Decl *ThisDecl) {
7294 // Note that we are no longer parsing the initializer for this declaration.
7295 ParsingInitForAutoVars.erase(ThisDecl);
7297 // Now we have parsed the initializer and can update the table of magic
7299 if (ThisDecl && ThisDecl->hasAttr<TypeTagForDatatypeAttr>()) {
7300 const VarDecl *VD = dyn_cast<VarDecl>(ThisDecl);
7301 if (VD && VD->getType()->isIntegralOrEnumerationType()) {
7302 for (specific_attr_iterator<TypeTagForDatatypeAttr>
7303 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
7304 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
7306 const Expr *MagicValueExpr = VD->getInit();
7307 if (!MagicValueExpr) {
7310 llvm::APSInt MagicValueInt;
7311 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
7312 Diag(I->getRange().getBegin(),
7313 diag::err_type_tag_for_datatype_not_ice)
7314 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
7317 if (MagicValueInt.getActiveBits() > 64) {
7318 Diag(I->getRange().getBegin(),
7319 diag::err_type_tag_for_datatype_too_large)
7320 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
7323 uint64_t MagicValue = MagicValueInt.getZExtValue();
7324 RegisterTypeTagForDatatype(I->getArgumentKind(),
7326 I->getMatchingCType(),
7327 I->getLayoutCompatible(),
7328 I->getMustBeNull());
7334 Sema::DeclGroupPtrTy
7335 Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
7336 Decl **Group, unsigned NumDecls) {
7337 SmallVector<Decl*, 8> Decls;
7339 if (DS.isTypeSpecOwned())
7340 Decls.push_back(DS.getRepAsDecl());
7342 for (unsigned i = 0; i != NumDecls; ++i)
7343 if (Decl *D = Group[i])
7346 return BuildDeclaratorGroup(Decls.data(), Decls.size(),
7347 DS.getTypeSpecType() == DeclSpec::TST_auto);
7350 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
7351 /// group, performing any necessary semantic checking.
7352 Sema::DeclGroupPtrTy
7353 Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
7354 bool TypeMayContainAuto) {
7355 // C++0x [dcl.spec.auto]p7:
7356 // If the type deduced for the template parameter U is not the same in each
7357 // deduction, the program is ill-formed.
7358 // FIXME: When initializer-list support is added, a distinction is needed
7359 // between the deduced type U and the deduced type which 'auto' stands for.
7360 // auto a = 0, b = { 1, 2, 3 };
7361 // is legal because the deduced type U is 'int' in both cases.
7362 if (TypeMayContainAuto && NumDecls > 1) {
7364 CanQualType DeducedCanon;
7365 VarDecl *DeducedDecl = 0;
7366 for (unsigned i = 0; i != NumDecls; ++i) {
7367 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
7368 AutoType *AT = D->getType()->getContainedAutoType();
7369 // Don't reissue diagnostics when instantiating a template.
7370 if (AT && D->isInvalidDecl())
7372 if (AT && AT->isDeduced()) {
7373 QualType U = AT->getDeducedType();
7374 CanQualType UCanon = Context.getCanonicalType(U);
7375 if (Deduced.isNull()) {
7377 DeducedCanon = UCanon;
7379 } else if (DeducedCanon != UCanon) {
7380 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
7381 diag::err_auto_different_deductions)
7382 << Deduced << DeducedDecl->getDeclName()
7383 << U << D->getDeclName()
7384 << DeducedDecl->getInit()->getSourceRange()
7385 << D->getInit()->getSourceRange();
7386 D->setInvalidDecl();
7394 ActOnDocumentableDecls(Group, NumDecls);
7396 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls));
7399 void Sema::ActOnDocumentableDecl(Decl *D) {
7400 ActOnDocumentableDecls(&D, 1);
7403 void Sema::ActOnDocumentableDecls(Decl **Group, unsigned NumDecls) {
7404 // Don't parse the comment if Doxygen diagnostics are ignored.
7405 if (NumDecls == 0 || !Group[0])
7408 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
7409 Group[0]->getLocation())
7410 == DiagnosticsEngine::Ignored)
7413 if (NumDecls >= 2) {
7414 // This is a decl group. Normally it will contain only declarations
7415 // procuded from declarator list. But in case we have any definitions or
7416 // additional declaration references:
7417 // 'typedef struct S {} S;'
7418 // 'typedef struct S *S;'
7420 // FinalizeDeclaratorGroup adds these as separate declarations.
7421 Decl *MaybeTagDecl = Group[0];
7422 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
7428 // See if there are any new comments that are not attached to a decl.
7429 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
7430 if (!Comments.empty() &&
7431 !Comments.back()->isAttached()) {
7432 // There is at least one comment that not attached to a decl.
7433 // Maybe it should be attached to one of these decls?
7435 // Note that this way we pick up not only comments that precede the
7436 // declaration, but also comments that *follow* the declaration -- thanks to
7437 // the lookahead in the lexer: we've consumed the semicolon and looked
7438 // ahead through comments.
7439 for (unsigned i = 0; i != NumDecls; ++i)
7440 Context.getCommentForDecl(Group[i], &PP);
7444 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
7445 /// to introduce parameters into function prototype scope.
7446 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
7447 const DeclSpec &DS = D.getDeclSpec();
7449 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
7450 // C++03 [dcl.stc]p2 also permits 'auto'.
7451 VarDecl::StorageClass StorageClass = SC_None;
7452 VarDecl::StorageClass StorageClassAsWritten = SC_None;
7453 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
7454 StorageClass = SC_Register;
7455 StorageClassAsWritten = SC_Register;
7456 } else if (getLangOpts().CPlusPlus &&
7457 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
7458 StorageClass = SC_Auto;
7459 StorageClassAsWritten = SC_Auto;
7460 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
7461 Diag(DS.getStorageClassSpecLoc(),
7462 diag::err_invalid_storage_class_in_func_decl);
7463 D.getMutableDeclSpec().ClearStorageClassSpecs();
7466 if (D.getDeclSpec().isThreadSpecified())
7467 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
7468 if (D.getDeclSpec().isConstexprSpecified())
7469 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
7472 DiagnoseFunctionSpecifiers(D);
7474 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
7475 QualType parmDeclType = TInfo->getType();
7477 if (getLangOpts().CPlusPlus) {
7478 // Check that there are no default arguments inside the type of this
7480 CheckExtraCXXDefaultArguments(D);
7482 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
7483 if (D.getCXXScopeSpec().isSet()) {
7484 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
7485 << D.getCXXScopeSpec().getRange();
7486 D.getCXXScopeSpec().clear();
7490 // Ensure we have a valid name
7491 IdentifierInfo *II = 0;
7493 II = D.getIdentifier();
7495 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
7496 << GetNameForDeclarator(D).getName().getAsString();
7497 D.setInvalidType(true);
7501 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
7503 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
7506 if (R.isSingleResult()) {
7507 NamedDecl *PrevDecl = R.getFoundDecl();
7508 if (PrevDecl->isTemplateParameter()) {
7509 // Maybe we will complain about the shadowed template parameter.
7510 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
7511 // Just pretend that we didn't see the previous declaration.
7513 } else if (S->isDeclScope(PrevDecl)) {
7514 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
7515 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
7517 // Recover by removing the name
7519 D.SetIdentifier(0, D.getIdentifierLoc());
7520 D.setInvalidType(true);
7525 // Temporarily put parameter variables in the translation unit, not
7526 // the enclosing context. This prevents them from accidentally
7527 // looking like class members in C++.
7528 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
7530 D.getIdentifierLoc(), II,
7531 parmDeclType, TInfo,
7532 StorageClass, StorageClassAsWritten);
7534 if (D.isInvalidType())
7535 New->setInvalidDecl();
7537 assert(S->isFunctionPrototypeScope());
7538 assert(S->getFunctionPrototypeDepth() >= 1);
7539 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
7540 S->getNextFunctionPrototypeIndex());
7542 // Add the parameter declaration into this scope.
7545 IdResolver.AddDecl(New);
7547 ProcessDeclAttributes(S, New, D);
7549 if (D.getDeclSpec().isModulePrivateSpecified())
7550 Diag(New->getLocation(), diag::err_module_private_local)
7551 << 1 << New->getDeclName()
7552 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7553 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7555 if (New->hasAttr<BlocksAttr>()) {
7556 Diag(New->getLocation(), diag::err_block_on_nonlocal);
7561 /// \brief Synthesizes a variable for a parameter arising from a
7563 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
7566 /* FIXME: setting StartLoc == Loc.
7567 Would it be worth to modify callers so as to provide proper source
7568 location for the unnamed parameters, embedding the parameter's type? */
7569 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
7570 T, Context.getTrivialTypeSourceInfo(T, Loc),
7571 SC_None, SC_None, 0);
7572 Param->setImplicit();
7576 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
7577 ParmVarDecl * const *ParamEnd) {
7578 // Don't diagnose unused-parameter errors in template instantiations; we
7579 // will already have done so in the template itself.
7580 if (!ActiveTemplateInstantiations.empty())
7583 for (; Param != ParamEnd; ++Param) {
7584 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
7585 !(*Param)->hasAttr<UnusedAttr>()) {
7586 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
7587 << (*Param)->getDeclName();
7592 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
7593 ParmVarDecl * const *ParamEnd,
7596 if (LangOpts.NumLargeByValueCopy == 0) // No check.
7599 // Warn if the return value is pass-by-value and larger than the specified
7601 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
7602 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
7603 if (Size > LangOpts.NumLargeByValueCopy)
7604 Diag(D->getLocation(), diag::warn_return_value_size)
7605 << D->getDeclName() << Size;
7608 // Warn if any parameter is pass-by-value and larger than the specified
7610 for (; Param != ParamEnd; ++Param) {
7611 QualType T = (*Param)->getType();
7612 if (T->isDependentType() || !T.isPODType(Context))
7614 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
7615 if (Size > LangOpts.NumLargeByValueCopy)
7616 Diag((*Param)->getLocation(), diag::warn_parameter_size)
7617 << (*Param)->getDeclName() << Size;
7621 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
7622 SourceLocation NameLoc, IdentifierInfo *Name,
7623 QualType T, TypeSourceInfo *TSInfo,
7624 VarDecl::StorageClass StorageClass,
7625 VarDecl::StorageClass StorageClassAsWritten) {
7626 // In ARC, infer a lifetime qualifier for appropriate parameter types.
7627 if (getLangOpts().ObjCAutoRefCount &&
7628 T.getObjCLifetime() == Qualifiers::OCL_None &&
7629 T->isObjCLifetimeType()) {
7631 Qualifiers::ObjCLifetime lifetime;
7633 // Special cases for arrays:
7634 // - if it's const, use __unsafe_unretained
7635 // - otherwise, it's an error
7636 if (T->isArrayType()) {
7637 if (!T.isConstQualified()) {
7638 DelayedDiagnostics.add(
7639 sema::DelayedDiagnostic::makeForbiddenType(
7640 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
7642 lifetime = Qualifiers::OCL_ExplicitNone;
7644 lifetime = T->getObjCARCImplicitLifetime();
7646 T = Context.getLifetimeQualifiedType(T, lifetime);
7649 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
7650 Context.getAdjustedParameterType(T),
7652 StorageClass, StorageClassAsWritten,
7655 // Parameters can not be abstract class types.
7656 // For record types, this is done by the AbstractClassUsageDiagnoser once
7657 // the class has been completely parsed.
7658 if (!CurContext->isRecord() &&
7659 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
7661 New->setInvalidDecl();
7663 // Parameter declarators cannot be interface types. All ObjC objects are
7664 // passed by reference.
7665 if (T->isObjCObjectType()) {
7666 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
7668 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
7669 << FixItHint::CreateInsertion(TypeEndLoc, "*");
7670 T = Context.getObjCObjectPointerType(T);
7674 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
7675 // duration shall not be qualified by an address-space qualifier."
7676 // Since all parameters have automatic store duration, they can not have
7677 // an address space.
7678 if (T.getAddressSpace() != 0) {
7679 Diag(NameLoc, diag::err_arg_with_address_space);
7680 New->setInvalidDecl();
7686 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
7687 SourceLocation LocAfterDecls) {
7688 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7690 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
7691 // for a K&R function.
7692 if (!FTI.hasPrototype) {
7693 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
7695 if (FTI.ArgInfo[i].Param == 0) {
7696 SmallString<256> Code;
7697 llvm::raw_svector_ostream(Code) << " int "
7698 << FTI.ArgInfo[i].Ident->getName()
7700 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
7701 << FTI.ArgInfo[i].Ident
7702 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
7704 // Implicitly declare the argument as type 'int' for lack of a better
7706 AttributeFactory attrs;
7708 const char* PrevSpec; // unused
7709 unsigned DiagID; // unused
7710 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
7712 // Use the identifier location for the type source range.
7713 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc);
7714 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc);
7715 Declarator ParamD(DS, Declarator::KNRTypeListContext);
7716 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
7717 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
7723 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
7724 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
7725 assert(D.isFunctionDeclarator() && "Not a function declarator!");
7726 Scope *ParentScope = FnBodyScope->getParent();
7728 D.setFunctionDefinitionKind(FDK_Definition);
7729 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
7730 return ActOnStartOfFunctionDef(FnBodyScope, DP);
7733 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
7734 // Don't warn about invalid declarations.
7735 if (FD->isInvalidDecl())
7738 // Or declarations that aren't global.
7739 if (!FD->isGlobal())
7742 // Don't warn about C++ member functions.
7743 if (isa<CXXMethodDecl>(FD))
7746 // Don't warn about 'main'.
7750 // Don't warn about inline functions.
7751 if (FD->isInlined())
7754 // Don't warn about function templates.
7755 if (FD->getDescribedFunctionTemplate())
7758 // Don't warn about function template specializations.
7759 if (FD->isFunctionTemplateSpecialization())
7762 // Don't warn for OpenCL kernels.
7763 if (FD->hasAttr<OpenCLKernelAttr>())
7766 bool MissingPrototype = true;
7767 for (const FunctionDecl *Prev = FD->getPreviousDecl();
7768 Prev; Prev = Prev->getPreviousDecl()) {
7769 // Ignore any declarations that occur in function or method
7770 // scope, because they aren't visible from the header.
7771 if (Prev->getDeclContext()->isFunctionOrMethod())
7774 MissingPrototype = !Prev->getType()->isFunctionProtoType();
7778 return MissingPrototype;
7781 void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) {
7782 // Don't complain if we're in GNU89 mode and the previous definition
7783 // was an extern inline function.
7784 const FunctionDecl *Definition;
7785 if (FD->isDefined(Definition) &&
7786 !canRedefineFunction(Definition, getLangOpts())) {
7787 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
7788 Definition->getStorageClass() == SC_Extern)
7789 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
7790 << FD->getDeclName() << getLangOpts().CPlusPlus;
7792 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
7793 Diag(Definition->getLocation(), diag::note_previous_definition);
7794 FD->setInvalidDecl();
7798 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
7799 // Clear the last template instantiation error context.
7800 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
7804 FunctionDecl *FD = 0;
7806 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
7807 FD = FunTmpl->getTemplatedDecl();
7809 FD = cast<FunctionDecl>(D);
7811 // Enter a new function scope
7812 PushFunctionScope();
7814 // See if this is a redefinition.
7815 if (!FD->isLateTemplateParsed())
7816 CheckForFunctionRedefinition(FD);
7818 // Builtin functions cannot be defined.
7819 if (unsigned BuiltinID = FD->getBuiltinID()) {
7820 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
7821 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
7822 FD->setInvalidDecl();
7826 // The return type of a function definition must be complete
7827 // (C99 6.9.1p3, C++ [dcl.fct]p6).
7828 QualType ResultType = FD->getResultType();
7829 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
7830 !FD->isInvalidDecl() &&
7831 RequireCompleteType(FD->getLocation(), ResultType,
7832 diag::err_func_def_incomplete_result))
7833 FD->setInvalidDecl();
7835 // GNU warning -Wmissing-prototypes:
7836 // Warn if a global function is defined without a previous
7837 // prototype declaration. This warning is issued even if the
7838 // definition itself provides a prototype. The aim is to detect
7839 // global functions that fail to be declared in header files.
7840 if (ShouldWarnAboutMissingPrototype(FD))
7841 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
7844 PushDeclContext(FnBodyScope, FD);
7846 // Check the validity of our function parameters
7847 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
7848 /*CheckParameterNames=*/true);
7850 // Introduce our parameters into the function scope
7851 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
7852 ParmVarDecl *Param = FD->getParamDecl(p);
7853 Param->setOwningFunction(FD);
7855 // If this has an identifier, add it to the scope stack.
7856 if (Param->getIdentifier() && FnBodyScope) {
7857 CheckShadow(FnBodyScope, Param);
7859 PushOnScopeChains(Param, FnBodyScope);
7863 // If we had any tags defined in the function prototype,
7864 // introduce them into the function scope.
7866 for (llvm::ArrayRef<NamedDecl*>::iterator I = FD->getDeclsInPrototypeScope().begin(),
7867 E = FD->getDeclsInPrototypeScope().end(); I != E; ++I) {
7870 // Some of these decls (like enums) may have been pinned to the translation unit
7871 // for lack of a real context earlier. If so, remove from the translation unit
7872 // and reattach to the current context.
7873 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
7874 // Is the decl actually in the context?
7875 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
7876 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
7878 Context.getTranslationUnitDecl()->removeDecl(D);
7882 // Either way, reassign the lexical decl context to our FunctionDecl.
7883 D->setLexicalDeclContext(CurContext);
7886 // If the decl has a non-null name, make accessible in the current scope.
7887 if (!D->getName().empty())
7888 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
7890 // Similarly, dive into enums and fish their constants out, making them
7891 // accessible in this scope.
7892 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
7893 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
7894 EE = ED->enumerator_end(); EI != EE; ++EI)
7895 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
7900 // Ensure that the function's exception specification is instantiated.
7901 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
7902 ResolveExceptionSpec(D->getLocation(), FPT);
7904 // Checking attributes of current function definition
7905 // dllimport attribute.
7906 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
7907 if (DA && (!FD->getAttr<DLLExportAttr>())) {
7908 // dllimport attribute cannot be directly applied to definition.
7909 // Microsoft accepts dllimport for functions defined within class scope.
7910 if (!DA->isInherited() &&
7911 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
7912 Diag(FD->getLocation(),
7913 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
7915 FD->setInvalidDecl();
7919 // Visual C++ appears to not think this is an issue, so only issue
7920 // a warning when Microsoft extensions are disabled.
7921 if (!LangOpts.MicrosoftExt) {
7922 // If a symbol previously declared dllimport is later defined, the
7923 // attribute is ignored in subsequent references, and a warning is
7925 Diag(FD->getLocation(),
7926 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7927 << FD->getName() << "dllimport";
7930 // We want to attach documentation to original Decl (which might be
7931 // a function template).
7932 ActOnDocumentableDecl(D);
7936 /// \brief Given the set of return statements within a function body,
7937 /// compute the variables that are subject to the named return value
7940 /// Each of the variables that is subject to the named return value
7941 /// optimization will be marked as NRVO variables in the AST, and any
7942 /// return statement that has a marked NRVO variable as its NRVO candidate can
7943 /// use the named return value optimization.
7945 /// This function applies a very simplistic algorithm for NRVO: if every return
7946 /// statement in the function has the same NRVO candidate, that candidate is
7947 /// the NRVO variable.
7949 /// FIXME: Employ a smarter algorithm that accounts for multiple return
7950 /// statements and the lifetimes of the NRVO candidates. We should be able to
7951 /// find a maximal set of NRVO variables.
7952 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
7953 ReturnStmt **Returns = Scope->Returns.data();
7955 const VarDecl *NRVOCandidate = 0;
7956 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
7957 if (!Returns[I]->getNRVOCandidate())
7961 NRVOCandidate = Returns[I]->getNRVOCandidate();
7962 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
7967 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
7970 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
7971 return ActOnFinishFunctionBody(D, BodyArg, false);
7974 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
7975 bool IsInstantiation) {
7976 FunctionDecl *FD = 0;
7977 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
7979 FD = FunTmpl->getTemplatedDecl();
7981 FD = dyn_cast_or_null<FunctionDecl>(dcl);
7983 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
7984 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
7989 // If the function implicitly returns zero (like 'main') or is naked,
7990 // don't complain about missing return statements.
7991 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
7992 WP.disableCheckFallThrough();
7994 // MSVC permits the use of pure specifier (=0) on function definition,
7995 // defined at class scope, warn about this non standard construct.
7996 if (getLangOpts().MicrosoftExt && FD->isPure())
7997 Diag(FD->getLocation(), diag::warn_pure_function_definition);
7999 if (!FD->isInvalidDecl()) {
8000 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
8001 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
8002 FD->getResultType(), FD);
8004 // If this is a constructor, we need a vtable.
8005 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
8006 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
8008 // Try to apply the named return value optimization. We have to check
8009 // if we can do this here because lambdas keep return statements around
8010 // to deduce an implicit return type.
8011 if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() &&
8012 !FD->isDependentContext())
8013 computeNRVO(Body, getCurFunction());
8016 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
8017 "Function parsing confused");
8018 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
8019 assert(MD == getCurMethodDecl() && "Method parsing confused");
8021 if (!MD->isInvalidDecl()) {
8022 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
8023 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
8024 MD->getResultType(), MD);
8027 computeNRVO(Body, getCurFunction());
8029 if (getCurFunction()->ObjCShouldCallSuper) {
8030 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
8031 << MD->getSelector().getAsString();
8032 getCurFunction()->ObjCShouldCallSuper = false;
8038 assert(!getCurFunction()->ObjCShouldCallSuper &&
8039 "This should only be set for ObjC methods, which should have been "
8040 "handled in the block above.");
8042 // Verify and clean out per-function state.
8044 // C++ constructors that have function-try-blocks can't have return
8045 // statements in the handlers of that block. (C++ [except.handle]p14)
8047 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
8048 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
8050 // Verify that gotos and switch cases don't jump into scopes illegally.
8051 if (getCurFunction()->NeedsScopeChecking() &&
8052 !dcl->isInvalidDecl() &&
8053 !hasAnyUnrecoverableErrorsInThisFunction() &&
8054 !PP.isCodeCompletionEnabled())
8055 DiagnoseInvalidJumps(Body);
8057 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
8058 if (!Destructor->getParent()->isDependentType())
8059 CheckDestructor(Destructor);
8061 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8062 Destructor->getParent());
8065 // If any errors have occurred, clear out any temporaries that may have
8066 // been leftover. This ensures that these temporaries won't be picked up for
8067 // deletion in some later function.
8068 if (PP.getDiagnostics().hasErrorOccurred() ||
8069 PP.getDiagnostics().getSuppressAllDiagnostics()) {
8070 DiscardCleanupsInEvaluationContext();
8071 } else if (!isa<FunctionTemplateDecl>(dcl)) {
8072 // Since the body is valid, issue any analysis-based warnings that are
8077 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
8078 (!CheckConstexprFunctionDecl(FD) ||
8079 !CheckConstexprFunctionBody(FD, Body)))
8080 FD->setInvalidDecl();
8082 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
8083 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
8084 assert(MaybeODRUseExprs.empty() &&
8085 "Leftover expressions for odr-use checking");
8088 if (!IsInstantiation)
8091 PopFunctionScopeInfo(ActivePolicy, dcl);
8093 // If any errors have occurred, clear out any temporaries that may have
8094 // been leftover. This ensures that these temporaries won't be picked up for
8095 // deletion in some later function.
8096 if (getDiagnostics().hasErrorOccurred()) {
8097 DiscardCleanupsInEvaluationContext();
8104 /// When we finish delayed parsing of an attribute, we must attach it to the
8106 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
8107 ParsedAttributes &Attrs) {
8108 // Always attach attributes to the underlying decl.
8109 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
8110 D = TD->getTemplatedDecl();
8111 ProcessDeclAttributeList(S, D, Attrs.getList());
8113 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
8114 if (Method->isStatic())
8115 checkThisInStaticMemberFunctionAttributes(Method);
8119 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
8120 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
8121 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
8122 IdentifierInfo &II, Scope *S) {
8123 // Before we produce a declaration for an implicitly defined
8124 // function, see whether there was a locally-scoped declaration of
8125 // this name as a function or variable. If so, use that
8126 // (non-visible) declaration, and complain about it.
8127 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
8128 = findLocallyScopedExternalDecl(&II);
8129 if (Pos != LocallyScopedExternalDecls.end()) {
8130 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
8131 Diag(Pos->second->getLocation(), diag::note_previous_declaration);
8135 // Extension in C99. Legal in C90, but warn about it.
8137 if (II.getName().startswith("__builtin_"))
8138 diag_id = diag::warn_builtin_unknown;
8139 else if (getLangOpts().C99)
8140 diag_id = diag::ext_implicit_function_decl;
8142 diag_id = diag::warn_implicit_function_decl;
8143 Diag(Loc, diag_id) << &II;
8145 // Because typo correction is expensive, only do it if the implicit
8146 // function declaration is going to be treated as an error.
8147 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
8148 TypoCorrection Corrected;
8149 DeclFilterCCC<FunctionDecl> Validator;
8150 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
8151 LookupOrdinaryName, S, 0, Validator))) {
8152 std::string CorrectedStr = Corrected.getAsString(getLangOpts());
8153 std::string CorrectedQuotedStr = Corrected.getQuoted(getLangOpts());
8154 FunctionDecl *Func = Corrected.getCorrectionDeclAs<FunctionDecl>();
8156 Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr
8157 << FixItHint::CreateReplacement(Loc, CorrectedStr);
8159 if (Func->getLocation().isValid()
8160 && !II.getName().startswith("__builtin_"))
8161 Diag(Func->getLocation(), diag::note_previous_decl)
8162 << CorrectedQuotedStr;
8166 // Set a Declarator for the implicit definition: int foo();
8168 AttributeFactory attrFactory;
8169 DeclSpec DS(attrFactory);
8171 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
8172 (void)Error; // Silence warning.
8173 assert(!Error && "Error setting up implicit decl!");
8174 SourceLocation NoLoc;
8175 Declarator D(DS, Declarator::BlockContext);
8176 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
8177 /*IsAmbiguous=*/false,
8178 /*RParenLoc=*/NoLoc,
8181 /*EllipsisLoc=*/NoLoc,
8182 /*RParenLoc=*/NoLoc,
8184 /*RefQualifierIsLvalueRef=*/true,
8185 /*RefQualifierLoc=*/NoLoc,
8186 /*ConstQualifierLoc=*/NoLoc,
8187 /*VolatileQualifierLoc=*/NoLoc,
8188 /*MutableLoc=*/NoLoc,
8192 /*ExceptionRanges=*/0,
8193 /*NumExceptions=*/0,
8198 D.SetIdentifier(&II, Loc);
8200 // Insert this function into translation-unit scope.
8202 DeclContext *PrevDC = CurContext;
8203 CurContext = Context.getTranslationUnitDecl();
8205 FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
8208 CurContext = PrevDC;
8210 AddKnownFunctionAttributes(FD);
8215 /// \brief Adds any function attributes that we know a priori based on
8216 /// the declaration of this function.
8218 /// These attributes can apply both to implicitly-declared builtins
8219 /// (like __builtin___printf_chk) or to library-declared functions
8220 /// like NSLog or printf.
8222 /// We need to check for duplicate attributes both here and where user-written
8223 /// attributes are applied to declarations.
8224 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
8225 if (FD->isInvalidDecl())
8228 // If this is a built-in function, map its builtin attributes to
8229 // actual attributes.
8230 if (unsigned BuiltinID = FD->getBuiltinID()) {
8231 // Handle printf-formatting attributes.
8234 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
8235 if (!FD->getAttr<FormatAttr>()) {
8236 const char *fmt = "printf";
8237 unsigned int NumParams = FD->getNumParams();
8238 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
8239 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
8241 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
8243 HasVAListArg ? 0 : FormatIdx+2));
8246 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
8248 if (!FD->getAttr<FormatAttr>())
8249 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
8250 "scanf", FormatIdx+1,
8251 HasVAListArg ? 0 : FormatIdx+2));
8254 // Mark const if we don't care about errno and that is the only
8255 // thing preventing the function from being const. This allows
8256 // IRgen to use LLVM intrinsics for such functions.
8257 if (!getLangOpts().MathErrno &&
8258 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
8259 if (!FD->getAttr<ConstAttr>())
8260 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
8263 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
8264 !FD->getAttr<ReturnsTwiceAttr>())
8265 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
8266 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
8267 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
8268 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
8269 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
8272 IdentifierInfo *Name = FD->getIdentifier();
8275 if ((!getLangOpts().CPlusPlus &&
8276 FD->getDeclContext()->isTranslationUnit()) ||
8277 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
8278 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
8279 LinkageSpecDecl::lang_c)) {
8280 // Okay: this could be a libc/libm/Objective-C function we know
8285 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
8286 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
8287 // target-specific builtins, perhaps?
8288 if (!FD->getAttr<FormatAttr>())
8289 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
8291 Name->isStr("vasprintf") ? 0 : 3));
8294 if (Name->isStr("__CFStringMakeConstantString")) {
8295 // We already have a __builtin___CFStringMakeConstantString,
8296 // but builds that use -fno-constant-cfstrings don't go through that.
8297 if (!FD->getAttr<FormatArgAttr>())
8298 FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1));
8302 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
8303 TypeSourceInfo *TInfo) {
8304 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
8305 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
8308 assert(D.isInvalidType() && "no declarator info for valid type");
8309 TInfo = Context.getTrivialTypeSourceInfo(T);
8312 // Scope manipulation handled by caller.
8313 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
8315 D.getIdentifierLoc(),
8319 // Bail out immediately if we have an invalid declaration.
8320 if (D.isInvalidType()) {
8321 NewTD->setInvalidDecl();
8325 if (D.getDeclSpec().isModulePrivateSpecified()) {
8326 if (CurContext->isFunctionOrMethod())
8327 Diag(NewTD->getLocation(), diag::err_module_private_local)
8328 << 2 << NewTD->getDeclName()
8329 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
8330 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
8332 NewTD->setModulePrivate();
8335 // C++ [dcl.typedef]p8:
8336 // If the typedef declaration defines an unnamed class (or
8337 // enum), the first typedef-name declared by the declaration
8338 // to be that class type (or enum type) is used to denote the
8339 // class type (or enum type) for linkage purposes only.
8340 // We need to check whether the type was declared in the declaration.
8341 switch (D.getDeclSpec().getTypeSpecType()) {
8347 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
8349 // Do nothing if the tag is not anonymous or already has an
8350 // associated typedef (from an earlier typedef in this decl group).
8351 if (tagFromDeclSpec->getIdentifier()) break;
8352 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
8354 // A well-formed anonymous tag must always be a TUK_Definition.
8355 assert(tagFromDeclSpec->isThisDeclarationADefinition());
8357 // The type must match the tag exactly; no qualifiers allowed.
8358 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
8361 // Otherwise, set this is the anon-decl typedef for the tag.
8362 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
8374 /// \brief Check that this is a valid underlying type for an enum declaration.
8375 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
8376 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
8377 QualType T = TI->getType();
8379 if (T->isDependentType() || T->isIntegralType(Context))
8382 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
8386 /// Check whether this is a valid redeclaration of a previous enumeration.
8387 /// \return true if the redeclaration was invalid.
8388 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
8389 QualType EnumUnderlyingTy,
8390 const EnumDecl *Prev) {
8391 bool IsFixed = !EnumUnderlyingTy.isNull();
8393 if (IsScoped != Prev->isScoped()) {
8394 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
8395 << Prev->isScoped();
8396 Diag(Prev->getLocation(), diag::note_previous_use);
8400 if (IsFixed && Prev->isFixed()) {
8401 if (!EnumUnderlyingTy->isDependentType() &&
8402 !Prev->getIntegerType()->isDependentType() &&
8403 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
8404 Prev->getIntegerType())) {
8405 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
8406 << EnumUnderlyingTy << Prev->getIntegerType();
8407 Diag(Prev->getLocation(), diag::note_previous_use);
8410 } else if (IsFixed != Prev->isFixed()) {
8411 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
8413 Diag(Prev->getLocation(), diag::note_previous_use);
8420 /// \brief Get diagnostic %select index for tag kind for
8421 /// redeclaration diagnostic message.
8422 /// WARNING: Indexes apply to particular diagnostics only!
8424 /// \returns diagnostic %select index.
8425 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
8427 case TTK_Struct: return 0;
8428 case TTK_Interface: return 1;
8429 case TTK_Class: return 2;
8430 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
8434 /// \brief Determine if tag kind is a class-key compatible with
8435 /// class for redeclaration (class, struct, or __interface).
8437 /// \returns true iff the tag kind is compatible.
8438 static bool isClassCompatTagKind(TagTypeKind Tag)
8440 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
8443 /// \brief Determine whether a tag with a given kind is acceptable
8444 /// as a redeclaration of the given tag declaration.
8446 /// \returns true if the new tag kind is acceptable, false otherwise.
8447 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
8448 TagTypeKind NewTag, bool isDefinition,
8449 SourceLocation NewTagLoc,
8450 const IdentifierInfo &Name) {
8451 // C++ [dcl.type.elab]p3:
8452 // The class-key or enum keyword present in the
8453 // elaborated-type-specifier shall agree in kind with the
8454 // declaration to which the name in the elaborated-type-specifier
8455 // refers. This rule also applies to the form of
8456 // elaborated-type-specifier that declares a class-name or
8457 // friend class since it can be construed as referring to the
8458 // definition of the class. Thus, in any
8459 // elaborated-type-specifier, the enum keyword shall be used to
8460 // refer to an enumeration (7.2), the union class-key shall be
8461 // used to refer to a union (clause 9), and either the class or
8462 // struct class-key shall be used to refer to a class (clause 9)
8463 // declared using the class or struct class-key.
8464 TagTypeKind OldTag = Previous->getTagKind();
8465 if (!isDefinition || !isClassCompatTagKind(NewTag))
8466 if (OldTag == NewTag)
8469 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
8470 // Warn about the struct/class tag mismatch.
8471 bool isTemplate = false;
8472 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
8473 isTemplate = Record->getDescribedClassTemplate();
8475 if (!ActiveTemplateInstantiations.empty()) {
8476 // In a template instantiation, do not offer fix-its for tag mismatches
8477 // since they usually mess up the template instead of fixing the problem.
8478 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
8479 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
8480 << getRedeclDiagFromTagKind(OldTag);
8485 // On definitions, check previous tags and issue a fix-it for each
8486 // one that doesn't match the current tag.
8487 if (Previous->getDefinition()) {
8488 // Don't suggest fix-its for redefinitions.
8492 bool previousMismatch = false;
8493 for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
8494 E(Previous->redecls_end()); I != E; ++I) {
8495 if (I->getTagKind() != NewTag) {
8496 if (!previousMismatch) {
8497 previousMismatch = true;
8498 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
8499 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
8500 << getRedeclDiagFromTagKind(I->getTagKind());
8502 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
8503 << getRedeclDiagFromTagKind(NewTag)
8504 << FixItHint::CreateReplacement(I->getInnerLocStart(),
8505 TypeWithKeyword::getTagTypeKindName(NewTag));
8511 // Check for a previous definition. If current tag and definition
8512 // are same type, do nothing. If no definition, but disagree with
8513 // with previous tag type, give a warning, but no fix-it.
8514 const TagDecl *Redecl = Previous->getDefinition() ?
8515 Previous->getDefinition() : Previous;
8516 if (Redecl->getTagKind() == NewTag) {
8520 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
8521 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
8522 << getRedeclDiagFromTagKind(OldTag);
8523 Diag(Redecl->getLocation(), diag::note_previous_use);
8525 // If there is a previous defintion, suggest a fix-it.
8526 if (Previous->getDefinition()) {
8527 Diag(NewTagLoc, diag::note_struct_class_suggestion)
8528 << getRedeclDiagFromTagKind(Redecl->getTagKind())
8529 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
8530 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
8538 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
8539 /// former case, Name will be non-null. In the later case, Name will be null.
8540 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
8541 /// reference/declaration/definition of a tag.
8542 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
8543 SourceLocation KWLoc, CXXScopeSpec &SS,
8544 IdentifierInfo *Name, SourceLocation NameLoc,
8545 AttributeList *Attr, AccessSpecifier AS,
8546 SourceLocation ModulePrivateLoc,
8547 MultiTemplateParamsArg TemplateParameterLists,
8548 bool &OwnedDecl, bool &IsDependent,
8549 SourceLocation ScopedEnumKWLoc,
8550 bool ScopedEnumUsesClassTag,
8551 TypeResult UnderlyingType) {
8552 // If this is not a definition, it must have a name.
8553 IdentifierInfo *OrigName = Name;
8554 assert((Name != 0 || TUK == TUK_Definition) &&
8555 "Nameless record must be a definition!");
8556 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
8559 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8560 bool ScopedEnum = ScopedEnumKWLoc.isValid();
8562 // FIXME: Check explicit specializations more carefully.
8563 bool isExplicitSpecialization = false;
8564 bool Invalid = false;
8566 // We only need to do this matching if we have template parameters
8567 // or a scope specifier, which also conveniently avoids this work
8568 // for non-C++ cases.
8569 if (TemplateParameterLists.size() > 0 ||
8570 (SS.isNotEmpty() && TUK != TUK_Reference)) {
8571 if (TemplateParameterList *TemplateParams
8572 = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS,
8573 TemplateParameterLists.data(),
8574 TemplateParameterLists.size(),
8576 isExplicitSpecialization,
8578 if (TemplateParams->size() > 0) {
8579 // This is a declaration or definition of a class template (which may
8580 // be a member of another template).
8586 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
8587 SS, Name, NameLoc, Attr,
8590 TemplateParameterLists.size()-1,
8591 TemplateParameterLists.data());
8592 return Result.get();
8594 // The "template<>" header is extraneous.
8595 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
8596 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
8597 isExplicitSpecialization = true;
8602 // Figure out the underlying type if this a enum declaration. We need to do
8603 // this early, because it's needed to detect if this is an incompatible
8605 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
8607 if (Kind == TTK_Enum) {
8608 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
8609 // No underlying type explicitly specified, or we failed to parse the
8610 // type, default to int.
8611 EnumUnderlying = Context.IntTy.getTypePtr();
8612 else if (UnderlyingType.get()) {
8613 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
8614 // integral type; any cv-qualification is ignored.
8615 TypeSourceInfo *TI = 0;
8616 GetTypeFromParser(UnderlyingType.get(), &TI);
8617 EnumUnderlying = TI;
8619 if (CheckEnumUnderlyingType(TI))
8620 // Recover by falling back to int.
8621 EnumUnderlying = Context.IntTy.getTypePtr();
8623 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
8624 UPPC_FixedUnderlyingType))
8625 EnumUnderlying = Context.IntTy.getTypePtr();
8627 } else if (getLangOpts().MicrosoftMode)
8628 // Microsoft enums are always of int type.
8629 EnumUnderlying = Context.IntTy.getTypePtr();
8632 DeclContext *SearchDC = CurContext;
8633 DeclContext *DC = CurContext;
8634 bool isStdBadAlloc = false;
8636 RedeclarationKind Redecl = ForRedeclaration;
8637 if (TUK == TUK_Friend || TUK == TUK_Reference)
8638 Redecl = NotForRedeclaration;
8640 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
8642 if (Name && SS.isNotEmpty()) {
8643 // We have a nested-name tag ('struct foo::bar').
8645 // Check for invalid 'foo::'.
8646 if (SS.isInvalid()) {
8651 // If this is a friend or a reference to a class in a dependent
8652 // context, don't try to make a decl for it.
8653 if (TUK == TUK_Friend || TUK == TUK_Reference) {
8654 DC = computeDeclContext(SS, false);
8660 DC = computeDeclContext(SS, true);
8662 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
8668 if (RequireCompleteDeclContext(SS, DC))
8672 // Look-up name inside 'foo::'.
8673 LookupQualifiedName(Previous, DC);
8675 if (Previous.isAmbiguous())
8678 if (Previous.empty()) {
8679 // Name lookup did not find anything. However, if the
8680 // nested-name-specifier refers to the current instantiation,
8681 // and that current instantiation has any dependent base
8682 // classes, we might find something at instantiation time: treat
8683 // this as a dependent elaborated-type-specifier.
8684 // But this only makes any sense for reference-like lookups.
8685 if (Previous.wasNotFoundInCurrentInstantiation() &&
8686 (TUK == TUK_Reference || TUK == TUK_Friend)) {
8691 // A tag 'foo::bar' must already exist.
8692 Diag(NameLoc, diag::err_not_tag_in_scope)
8693 << Kind << Name << DC << SS.getRange();
8699 // If this is a named struct, check to see if there was a previous forward
8700 // declaration or definition.
8701 // FIXME: We're looking into outer scopes here, even when we
8702 // shouldn't be. Doing so can result in ambiguities that we
8703 // shouldn't be diagnosing.
8704 LookupName(Previous, S);
8706 if (Previous.isAmbiguous() &&
8707 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
8708 LookupResult::Filter F = Previous.makeFilter();
8709 while (F.hasNext()) {
8710 NamedDecl *ND = F.next();
8711 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
8717 // Note: there used to be some attempt at recovery here.
8718 if (Previous.isAmbiguous())
8721 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
8722 // FIXME: This makes sure that we ignore the contexts associated
8723 // with C structs, unions, and enums when looking for a matching
8724 // tag declaration or definition. See the similar lookup tweak
8725 // in Sema::LookupName; is there a better way to deal with this?
8726 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
8727 SearchDC = SearchDC->getParent();
8729 } else if (S->isFunctionPrototypeScope()) {
8730 // If this is an enum declaration in function prototype scope, set its
8731 // initial context to the translation unit.
8732 // FIXME: [citation needed]
8733 SearchDC = Context.getTranslationUnitDecl();
8736 if (Previous.isSingleResult() &&
8737 Previous.getFoundDecl()->isTemplateParameter()) {
8738 // Maybe we will complain about the shadowed template parameter.
8739 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
8740 // Just pretend that we didn't see the previous declaration.
8744 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
8745 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
8746 // This is a declaration of or a reference to "std::bad_alloc".
8747 isStdBadAlloc = true;
8749 if (Previous.empty() && StdBadAlloc) {
8750 // std::bad_alloc has been implicitly declared (but made invisible to
8751 // name lookup). Fill in this implicit declaration as the previous
8752 // declaration, so that the declarations get chained appropriately.
8753 Previous.addDecl(getStdBadAlloc());
8757 // If we didn't find a previous declaration, and this is a reference
8758 // (or friend reference), move to the correct scope. In C++, we
8759 // also need to do a redeclaration lookup there, just in case
8760 // there's a shadow friend decl.
8761 if (Name && Previous.empty() &&
8762 (TUK == TUK_Reference || TUK == TUK_Friend)) {
8763 if (Invalid) goto CreateNewDecl;
8764 assert(SS.isEmpty());
8766 if (TUK == TUK_Reference) {
8767 // C++ [basic.scope.pdecl]p5:
8768 // -- for an elaborated-type-specifier of the form
8770 // class-key identifier
8772 // if the elaborated-type-specifier is used in the
8773 // decl-specifier-seq or parameter-declaration-clause of a
8774 // function defined in namespace scope, the identifier is
8775 // declared as a class-name in the namespace that contains
8776 // the declaration; otherwise, except as a friend
8777 // declaration, the identifier is declared in the smallest
8778 // non-class, non-function-prototype scope that contains the
8781 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
8782 // C structs and unions.
8784 // It is an error in C++ to declare (rather than define) an enum
8785 // type, including via an elaborated type specifier. We'll
8786 // diagnose that later; for now, declare the enum in the same
8787 // scope as we would have picked for any other tag type.
8789 // GNU C also supports this behavior as part of its incomplete
8790 // enum types extension, while GNU C++ does not.
8792 // Find the context where we'll be declaring the tag.
8793 // FIXME: We would like to maintain the current DeclContext as the
8795 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
8796 SearchDC = SearchDC->getParent();
8798 // Find the scope where we'll be declaring the tag.
8799 while (S->isClassScope() ||
8800 (getLangOpts().CPlusPlus &&
8801 S->isFunctionPrototypeScope()) ||
8802 ((S->getFlags() & Scope::DeclScope) == 0) ||
8804 ((DeclContext *)S->getEntity())->isTransparentContext()))
8807 assert(TUK == TUK_Friend);
8808 // C++ [namespace.memdef]p3:
8809 // If a friend declaration in a non-local class first declares a
8810 // class or function, the friend class or function is a member of
8811 // the innermost enclosing namespace.
8812 SearchDC = SearchDC->getEnclosingNamespaceContext();
8815 // In C++, we need to do a redeclaration lookup to properly
8816 // diagnose some problems.
8817 if (getLangOpts().CPlusPlus) {
8818 Previous.setRedeclarationKind(ForRedeclaration);
8819 LookupQualifiedName(Previous, SearchDC);
8823 if (!Previous.empty()) {
8824 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
8826 // It's okay to have a tag decl in the same scope as a typedef
8827 // which hides a tag decl in the same scope. Finding this
8828 // insanity with a redeclaration lookup can only actually happen
8831 // This is also okay for elaborated-type-specifiers, which is
8832 // technically forbidden by the current standard but which is
8833 // okay according to the likely resolution of an open issue;
8834 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
8835 if (getLangOpts().CPlusPlus) {
8836 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
8837 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
8838 TagDecl *Tag = TT->getDecl();
8839 if (Tag->getDeclName() == Name &&
8840 Tag->getDeclContext()->getRedeclContext()
8841 ->Equals(TD->getDeclContext()->getRedeclContext())) {
8844 Previous.addDecl(Tag);
8845 Previous.resolveKind();
8851 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
8852 // If this is a use of a previous tag, or if the tag is already declared
8853 // in the same scope (so that the definition/declaration completes or
8854 // rementions the tag), reuse the decl.
8855 if (TUK == TUK_Reference || TUK == TUK_Friend ||
8856 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
8857 // Make sure that this wasn't declared as an enum and now used as a
8858 // struct or something similar.
8859 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
8860 TUK == TUK_Definition, KWLoc,
8863 = (PrevTagDecl->getTagKind() != TTK_Enum &&
8866 Diag(KWLoc, diag::err_use_with_wrong_tag)
8868 << FixItHint::CreateReplacement(SourceRange(KWLoc),
8869 PrevTagDecl->getKindName());
8871 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
8872 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
8875 Kind = PrevTagDecl->getTagKind();
8877 // Recover by making this an anonymous redefinition.
8884 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
8885 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
8887 // If this is an elaborated-type-specifier for a scoped enumeration,
8888 // the 'class' keyword is not necessary and not permitted.
8889 if (TUK == TUK_Reference || TUK == TUK_Friend) {
8891 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
8892 << PrevEnum->isScoped()
8893 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
8897 QualType EnumUnderlyingTy;
8898 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
8899 EnumUnderlyingTy = TI->getType();
8900 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
8901 EnumUnderlyingTy = QualType(T, 0);
8903 // All conflicts with previous declarations are recovered by
8904 // returning the previous declaration, unless this is a definition,
8905 // in which case we want the caller to bail out.
8906 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
8907 ScopedEnum, EnumUnderlyingTy, PrevEnum))
8908 return TUK == TUK_Declaration ? PrevTagDecl : 0;
8912 // If this is a use, just return the declaration we found.
8914 // FIXME: In the future, return a variant or some other clue
8915 // for the consumer of this Decl to know it doesn't own it.
8916 // For our current ASTs this shouldn't be a problem, but will
8917 // need to be changed with DeclGroups.
8918 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
8919 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
8922 // Diagnose attempts to redefine a tag.
8923 if (TUK == TUK_Definition) {
8924 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
8925 // If we're defining a specialization and the previous definition
8926 // is from an implicit instantiation, don't emit an error
8927 // here; we'll catch this in the general case below.
8928 bool IsExplicitSpecializationAfterInstantiation = false;
8929 if (isExplicitSpecialization) {
8930 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
8931 IsExplicitSpecializationAfterInstantiation =
8932 RD->getTemplateSpecializationKind() !=
8933 TSK_ExplicitSpecialization;
8934 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
8935 IsExplicitSpecializationAfterInstantiation =
8936 ED->getTemplateSpecializationKind() !=
8937 TSK_ExplicitSpecialization;
8940 if (!IsExplicitSpecializationAfterInstantiation) {
8941 // A redeclaration in function prototype scope in C isn't
8942 // visible elsewhere, so merely issue a warning.
8943 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
8944 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
8946 Diag(NameLoc, diag::err_redefinition) << Name;
8947 Diag(Def->getLocation(), diag::note_previous_definition);
8948 // If this is a redefinition, recover by making this
8949 // struct be anonymous, which will make any later
8950 // references get the previous definition.
8956 // If the type is currently being defined, complain
8957 // about a nested redefinition.
8959 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
8960 if (Tag->isBeingDefined()) {
8961 Diag(NameLoc, diag::err_nested_redefinition) << Name;
8962 Diag(PrevTagDecl->getLocation(),
8963 diag::note_previous_definition);
8970 // Okay, this is definition of a previously declared or referenced
8971 // tag PrevDecl. We're going to create a new Decl for it.
8974 // If we get here we have (another) forward declaration or we
8975 // have a definition. Just create a new decl.
8978 // If we get here, this is a definition of a new tag type in a nested
8979 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
8980 // new decl/type. We set PrevDecl to NULL so that the entities
8981 // have distinct types.
8984 // If we get here, we're going to create a new Decl. If PrevDecl
8985 // is non-NULL, it's a definition of the tag declared by
8986 // PrevDecl. If it's NULL, we have a new definition.
8989 // Otherwise, PrevDecl is not a tag, but was found with tag
8990 // lookup. This is only actually possible in C++, where a few
8991 // things like templates still live in the tag namespace.
8993 // Use a better diagnostic if an elaborated-type-specifier
8994 // found the wrong kind of type on the first
8995 // (non-redeclaration) lookup.
8996 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
8997 !Previous.isForRedeclaration()) {
8999 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
9000 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
9001 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
9002 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
9003 Diag(PrevDecl->getLocation(), diag::note_declared_at);
9006 // Otherwise, only diagnose if the declaration is in scope.
9007 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
9008 isExplicitSpecialization)) {
9011 // Diagnose implicit declarations introduced by elaborated types.
9012 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
9014 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
9015 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
9016 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
9017 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
9018 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
9021 // Otherwise it's a declaration. Call out a particularly common
9023 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
9025 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
9026 Diag(NameLoc, diag::err_tag_definition_of_typedef)
9027 << Name << Kind << TND->getUnderlyingType();
9028 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
9031 // Otherwise, diagnose.
9033 // The tag name clashes with something else in the target scope,
9034 // issue an error and recover by making this tag be anonymous.
9035 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
9036 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
9041 // The existing declaration isn't relevant to us; we're in a
9042 // new scope, so clear out the previous declaration.
9049 TagDecl *PrevDecl = 0;
9050 if (Previous.isSingleResult())
9051 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
9053 // If there is an identifier, use the location of the identifier as the
9054 // location of the decl, otherwise use the location of the struct/union
9056 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
9058 // Otherwise, create a new declaration. If there is a previous
9059 // declaration of the same entity, the two will be linked via
9063 bool IsForwardReference = false;
9064 if (Kind == TTK_Enum) {
9065 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
9066 // enum X { A, B, C } D; D should chain to X.
9067 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
9068 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
9069 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
9070 // If this is an undefined enum, warn.
9071 if (TUK != TUK_Definition && !Invalid) {
9073 if (getLangOpts().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) {
9074 // C++0x: 7.2p2: opaque-enum-declaration.
9075 // Conflicts are diagnosed above. Do nothing.
9077 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
9078 Diag(Loc, diag::ext_forward_ref_enum_def)
9080 Diag(Def->getLocation(), diag::note_previous_definition);
9082 unsigned DiagID = diag::ext_forward_ref_enum;
9083 if (getLangOpts().MicrosoftMode)
9084 DiagID = diag::ext_ms_forward_ref_enum;
9085 else if (getLangOpts().CPlusPlus)
9086 DiagID = diag::err_forward_ref_enum;
9089 // If this is a forward-declared reference to an enumeration, make a
9090 // note of it; we won't actually be introducing the declaration into
9091 // the declaration context.
9092 if (TUK == TUK_Reference)
9093 IsForwardReference = true;
9097 if (EnumUnderlying) {
9098 EnumDecl *ED = cast<EnumDecl>(New);
9099 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
9100 ED->setIntegerTypeSourceInfo(TI);
9102 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
9103 ED->setPromotionType(ED->getIntegerType());
9107 // struct/union/class
9109 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
9110 // struct X { int A; } D; D should chain to X.
9111 if (getLangOpts().CPlusPlus) {
9112 // FIXME: Look for a way to use RecordDecl for simple structs.
9113 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
9114 cast_or_null<CXXRecordDecl>(PrevDecl));
9116 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
9117 StdBadAlloc = cast<CXXRecordDecl>(New);
9119 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
9120 cast_or_null<RecordDecl>(PrevDecl));
9123 // Maybe add qualifier info.
9124 if (SS.isNotEmpty()) {
9126 // If this is either a declaration or a definition, check the
9127 // nested-name-specifier against the current context. We don't do this
9128 // for explicit specializations, because they have similar checking
9129 // (with more specific diagnostics) in the call to
9130 // CheckMemberSpecialization, below.
9131 if (!isExplicitSpecialization &&
9132 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
9133 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
9136 New->setQualifierInfo(SS.getWithLocInContext(Context));
9137 if (TemplateParameterLists.size() > 0) {
9138 New->setTemplateParameterListsInfo(Context,
9139 TemplateParameterLists.size(),
9140 TemplateParameterLists.data());
9147 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
9148 // Add alignment attributes if necessary; these attributes are checked when
9149 // the ASTContext lays out the structure.
9151 // It is important for implementing the correct semantics that this
9152 // happen here (in act on tag decl). The #pragma pack stack is
9153 // maintained as a result of parser callbacks which can occur at
9154 // many points during the parsing of a struct declaration (because
9155 // the #pragma tokens are effectively skipped over during the
9156 // parsing of the struct).
9157 if (TUK == TUK_Definition) {
9158 AddAlignmentAttributesForRecord(RD);
9159 AddMsStructLayoutForRecord(RD);
9163 if (ModulePrivateLoc.isValid()) {
9164 if (isExplicitSpecialization)
9165 Diag(New->getLocation(), diag::err_module_private_specialization)
9167 << FixItHint::CreateRemoval(ModulePrivateLoc);
9168 // __module_private__ does not apply to local classes. However, we only
9169 // diagnose this as an error when the declaration specifiers are
9170 // freestanding. Here, we just ignore the __module_private__.
9171 else if (!SearchDC->isFunctionOrMethod())
9172 New->setModulePrivate();
9175 // If this is a specialization of a member class (of a class template),
9176 // check the specialization.
9177 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
9181 New->setInvalidDecl();
9184 ProcessDeclAttributeList(S, New, Attr);
9186 // If we're declaring or defining a tag in function prototype scope
9187 // in C, note that this type can only be used within the function.
9188 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
9189 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
9191 // Set the lexical context. If the tag has a C++ scope specifier, the
9192 // lexical context will be different from the semantic context.
9193 New->setLexicalDeclContext(CurContext);
9195 // Mark this as a friend decl if applicable.
9196 // In Microsoft mode, a friend declaration also acts as a forward
9197 // declaration so we always pass true to setObjectOfFriendDecl to make
9198 // the tag name visible.
9199 if (TUK == TUK_Friend)
9200 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() ||
9201 getLangOpts().MicrosoftExt);
9203 // Set the access specifier.
9204 if (!Invalid && SearchDC->isRecord())
9205 SetMemberAccessSpecifier(New, PrevDecl, AS);
9207 if (TUK == TUK_Definition)
9208 New->startDefinition();
9210 // If this has an identifier, add it to the scope stack.
9211 if (TUK == TUK_Friend) {
9212 // We might be replacing an existing declaration in the lookup tables;
9213 // if so, borrow its access specifier.
9215 New->setAccess(PrevDecl->getAccess());
9217 DeclContext *DC = New->getDeclContext()->getRedeclContext();
9218 DC->makeDeclVisibleInContext(New);
9219 if (Name) // can be null along some error paths
9220 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
9221 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
9223 S = getNonFieldDeclScope(S);
9224 PushOnScopeChains(New, S, !IsForwardReference);
9225 if (IsForwardReference)
9226 SearchDC->makeDeclVisibleInContext(New);
9229 CurContext->addDecl(New);
9232 // If this is the C FILE type, notify the AST context.
9233 if (IdentifierInfo *II = New->getIdentifier())
9234 if (!New->isInvalidDecl() &&
9235 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
9237 Context.setFILEDecl(New);
9239 // If we were in function prototype scope (and not in C++ mode), add this
9240 // tag to the list of decls to inject into the function definition scope.
9241 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
9242 InFunctionDeclarator && Name)
9243 DeclsInPrototypeScope.push_back(New);
9246 mergeDeclAttributes(New, PrevDecl);
9248 // If there's a #pragma GCC visibility in scope, set the visibility of this
9250 AddPushedVisibilityAttribute(New);
9256 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
9257 AdjustDeclIfTemplate(TagD);
9258 TagDecl *Tag = cast<TagDecl>(TagD);
9260 // Enter the tag context.
9261 PushDeclContext(S, Tag);
9263 ActOnDocumentableDecl(TagD);
9265 // If there's a #pragma GCC visibility in scope, set the visibility of this
9267 AddPushedVisibilityAttribute(Tag);
9270 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
9271 assert(isa<ObjCContainerDecl>(IDecl) &&
9272 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
9273 DeclContext *OCD = cast<DeclContext>(IDecl);
9274 assert(getContainingDC(OCD) == CurContext &&
9275 "The next DeclContext should be lexically contained in the current one.");
9280 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
9281 SourceLocation FinalLoc,
9282 SourceLocation LBraceLoc) {
9283 AdjustDeclIfTemplate(TagD);
9284 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
9286 FieldCollector->StartClass();
9288 if (!Record->getIdentifier())
9291 if (FinalLoc.isValid())
9292 Record->addAttr(new (Context) FinalAttr(FinalLoc, Context));
9295 // [...] The class-name is also inserted into the scope of the
9296 // class itself; this is known as the injected-class-name. For
9297 // purposes of access checking, the injected-class-name is treated
9298 // as if it were a public member name.
9299 CXXRecordDecl *InjectedClassName
9300 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
9301 Record->getLocStart(), Record->getLocation(),
9302 Record->getIdentifier(),
9304 /*DelayTypeCreation=*/true);
9305 Context.getTypeDeclType(InjectedClassName, Record);
9306 InjectedClassName->setImplicit();
9307 InjectedClassName->setAccess(AS_public);
9308 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
9309 InjectedClassName->setDescribedClassTemplate(Template);
9310 PushOnScopeChains(InjectedClassName, S);
9311 assert(InjectedClassName->isInjectedClassName() &&
9312 "Broken injected-class-name");
9315 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
9316 SourceLocation RBraceLoc) {
9317 AdjustDeclIfTemplate(TagD);
9318 TagDecl *Tag = cast<TagDecl>(TagD);
9319 Tag->setRBraceLoc(RBraceLoc);
9321 // Make sure we "complete" the definition even it is invalid.
9322 if (Tag->isBeingDefined()) {
9323 assert(Tag->isInvalidDecl() && "We should already have completed it");
9324 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
9325 RD->completeDefinition();
9328 if (isa<CXXRecordDecl>(Tag))
9329 FieldCollector->FinishClass();
9331 // Exit this scope of this tag's definition.
9334 // Notify the consumer that we've defined a tag.
9335 Consumer.HandleTagDeclDefinition(Tag);
9338 void Sema::ActOnObjCContainerFinishDefinition() {
9339 // Exit this scope of this interface definition.
9343 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
9344 assert(DC == CurContext && "Mismatch of container contexts");
9345 OriginalLexicalContext = DC;
9346 ActOnObjCContainerFinishDefinition();
9349 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
9350 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
9351 OriginalLexicalContext = 0;
9354 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
9355 AdjustDeclIfTemplate(TagD);
9356 TagDecl *Tag = cast<TagDecl>(TagD);
9357 Tag->setInvalidDecl();
9359 // Make sure we "complete" the definition even it is invalid.
9360 if (Tag->isBeingDefined()) {
9361 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
9362 RD->completeDefinition();
9365 // We're undoing ActOnTagStartDefinition here, not
9366 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
9367 // the FieldCollector.
9372 // Note that FieldName may be null for anonymous bitfields.
9373 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
9374 IdentifierInfo *FieldName,
9375 QualType FieldTy, Expr *BitWidth,
9377 // Default to true; that shouldn't confuse checks for emptiness
9381 // C99 6.7.2.1p4 - verify the field type.
9382 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
9383 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
9384 // Handle incomplete types with specific error.
9385 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
9388 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
9389 << FieldName << FieldTy << BitWidth->getSourceRange();
9390 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
9391 << FieldTy << BitWidth->getSourceRange();
9392 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
9393 UPPC_BitFieldWidth))
9396 // If the bit-width is type- or value-dependent, don't try to check
9398 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
9399 return Owned(BitWidth);
9402 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
9403 if (ICE.isInvalid())
9405 BitWidth = ICE.take();
9407 if (Value != 0 && ZeroWidth)
9410 // Zero-width bitfield is ok for anonymous field.
9411 if (Value == 0 && FieldName)
9412 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
9414 if (Value.isSigned() && Value.isNegative()) {
9416 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
9417 << FieldName << Value.toString(10);
9418 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
9419 << Value.toString(10);
9422 if (!FieldTy->isDependentType()) {
9423 uint64_t TypeSize = Context.getTypeSize(FieldTy);
9424 if (Value.getZExtValue() > TypeSize) {
9425 if (!getLangOpts().CPlusPlus) {
9427 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
9428 << FieldName << (unsigned)Value.getZExtValue()
9429 << (unsigned)TypeSize;
9431 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
9432 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
9436 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
9437 << FieldName << (unsigned)Value.getZExtValue()
9438 << (unsigned)TypeSize;
9440 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
9441 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
9445 return Owned(BitWidth);
9448 /// ActOnField - Each field of a C struct/union is passed into this in order
9449 /// to create a FieldDecl object for it.
9450 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
9451 Declarator &D, Expr *BitfieldWidth) {
9452 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
9453 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
9454 /*InitStyle=*/ICIS_NoInit, AS_public);
9458 /// HandleField - Analyze a field of a C struct or a C++ data member.
9460 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
9461 SourceLocation DeclStart,
9462 Declarator &D, Expr *BitWidth,
9463 InClassInitStyle InitStyle,
9464 AccessSpecifier AS) {
9465 IdentifierInfo *II = D.getIdentifier();
9466 SourceLocation Loc = DeclStart;
9467 if (II) Loc = D.getIdentifierLoc();
9469 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9470 QualType T = TInfo->getType();
9471 if (getLangOpts().CPlusPlus) {
9472 CheckExtraCXXDefaultArguments(D);
9474 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9475 UPPC_DataMemberType)) {
9478 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
9482 DiagnoseFunctionSpecifiers(D);
9484 if (D.getDeclSpec().isThreadSpecified())
9485 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
9486 if (D.getDeclSpec().isConstexprSpecified())
9487 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
9490 // Check to see if this name was declared as a member previously
9491 NamedDecl *PrevDecl = 0;
9492 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
9493 LookupName(Previous, S);
9494 switch (Previous.getResultKind()) {
9495 case LookupResult::Found:
9496 case LookupResult::FoundUnresolvedValue:
9497 PrevDecl = Previous.getAsSingle<NamedDecl>();
9500 case LookupResult::FoundOverloaded:
9501 PrevDecl = Previous.getRepresentativeDecl();
9504 case LookupResult::NotFound:
9505 case LookupResult::NotFoundInCurrentInstantiation:
9506 case LookupResult::Ambiguous:
9509 Previous.suppressDiagnostics();
9511 if (PrevDecl && PrevDecl->isTemplateParameter()) {
9512 // Maybe we will complain about the shadowed template parameter.
9513 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9514 // Just pretend that we didn't see the previous declaration.
9518 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
9522 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
9523 SourceLocation TSSL = D.getLocStart();
9525 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
9526 TSSL, AS, PrevDecl, &D);
9528 if (NewFD->isInvalidDecl())
9529 Record->setInvalidDecl();
9531 if (D.getDeclSpec().isModulePrivateSpecified())
9532 NewFD->setModulePrivate();
9534 if (NewFD->isInvalidDecl() && PrevDecl) {
9535 // Don't introduce NewFD into scope; there's already something
9536 // with the same name in the same scope.
9538 PushOnScopeChains(NewFD, S);
9540 Record->addDecl(NewFD);
9545 /// \brief Build a new FieldDecl and check its well-formedness.
9547 /// This routine builds a new FieldDecl given the fields name, type,
9548 /// record, etc. \p PrevDecl should refer to any previous declaration
9549 /// with the same name and in the same scope as the field to be
9552 /// \returns a new FieldDecl.
9554 /// \todo The Declarator argument is a hack. It will be removed once
9555 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
9556 TypeSourceInfo *TInfo,
9557 RecordDecl *Record, SourceLocation Loc,
9558 bool Mutable, Expr *BitWidth,
9559 InClassInitStyle InitStyle,
9560 SourceLocation TSSL,
9561 AccessSpecifier AS, NamedDecl *PrevDecl,
9563 IdentifierInfo *II = Name.getAsIdentifierInfo();
9564 bool InvalidDecl = false;
9565 if (D) InvalidDecl = D->isInvalidType();
9567 // If we receive a broken type, recover by assuming 'int' and
9568 // marking this declaration as invalid.
9574 QualType EltTy = Context.getBaseElementType(T);
9575 if (!EltTy->isDependentType()) {
9576 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
9577 // Fields of incomplete type force their record to be invalid.
9578 Record->setInvalidDecl();
9582 EltTy->isIncompleteType(&Def);
9583 if (Def && Def->isInvalidDecl()) {
9584 Record->setInvalidDecl();
9590 // C99 6.7.2.1p8: A member of a structure or union may have any type other
9591 // than a variably modified type.
9592 if (!InvalidDecl && T->isVariablyModifiedType()) {
9593 bool SizeIsNegative;
9594 llvm::APSInt Oversized;
9596 TypeSourceInfo *FixedTInfo =
9597 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
9601 Diag(Loc, diag::warn_illegal_constant_array_size);
9603 T = FixedTInfo->getType();
9606 Diag(Loc, diag::err_typecheck_negative_array_size);
9607 else if (Oversized.getBoolValue())
9608 Diag(Loc, diag::err_array_too_large)
9609 << Oversized.toString(10);
9611 Diag(Loc, diag::err_typecheck_field_variable_size);
9616 // Fields can not have abstract class types
9617 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
9618 diag::err_abstract_type_in_decl,
9622 bool ZeroWidth = false;
9623 // If this is declared as a bit-field, check the bit-field.
9624 if (!InvalidDecl && BitWidth) {
9625 BitWidth = VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth).take();
9633 // Check that 'mutable' is consistent with the type of the declaration.
9634 if (!InvalidDecl && Mutable) {
9635 unsigned DiagID = 0;
9636 if (T->isReferenceType())
9637 DiagID = diag::err_mutable_reference;
9638 else if (T.isConstQualified())
9639 DiagID = diag::err_mutable_const;
9642 SourceLocation ErrLoc = Loc;
9643 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
9644 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
9645 Diag(ErrLoc, DiagID);
9651 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
9652 BitWidth, Mutable, InitStyle);
9654 NewFD->setInvalidDecl();
9656 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
9657 Diag(Loc, diag::err_duplicate_member) << II;
9658 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9659 NewFD->setInvalidDecl();
9662 if (!InvalidDecl && getLangOpts().CPlusPlus) {
9663 if (Record->isUnion()) {
9664 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
9665 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
9666 if (RDecl->getDefinition()) {
9667 // C++ [class.union]p1: An object of a class with a non-trivial
9668 // constructor, a non-trivial copy constructor, a non-trivial
9669 // destructor, or a non-trivial copy assignment operator
9670 // cannot be a member of a union, nor can an array of such
9672 if (CheckNontrivialField(NewFD))
9673 NewFD->setInvalidDecl();
9677 // C++ [class.union]p1: If a union contains a member of reference type,
9678 // the program is ill-formed.
9679 if (EltTy->isReferenceType()) {
9680 Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
9681 << NewFD->getDeclName() << EltTy;
9682 NewFD->setInvalidDecl();
9687 // FIXME: We need to pass in the attributes given an AST
9688 // representation, not a parser representation.
9690 // FIXME: What to pass instead of TUScope?
9691 ProcessDeclAttributes(TUScope, NewFD, *D);
9693 // In auto-retain/release, infer strong retension for fields of
9695 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
9696 NewFD->setInvalidDecl();
9698 if (T.isObjCGCWeak())
9699 Diag(Loc, diag::warn_attribute_weak_on_field);
9701 NewFD->setAccess(AS);
9705 bool Sema::CheckNontrivialField(FieldDecl *FD) {
9707 assert(getLangOpts().CPlusPlus && "valid check only for C++");
9709 if (FD->isInvalidDecl())
9712 QualType EltTy = Context.getBaseElementType(FD->getType());
9713 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
9714 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
9715 if (RDecl->getDefinition()) {
9716 // We check for copy constructors before constructors
9717 // because otherwise we'll never get complaints about
9718 // copy constructors.
9720 CXXSpecialMember member = CXXInvalid;
9721 if (!RDecl->hasTrivialCopyConstructor())
9722 member = CXXCopyConstructor;
9723 else if (!RDecl->hasTrivialDefaultConstructor())
9724 member = CXXDefaultConstructor;
9725 else if (!RDecl->hasTrivialCopyAssignment())
9726 member = CXXCopyAssignment;
9727 else if (!RDecl->hasTrivialDestructor())
9728 member = CXXDestructor;
9730 if (member != CXXInvalid) {
9731 if (!getLangOpts().CPlusPlus0x &&
9732 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
9733 // Objective-C++ ARC: it is an error to have a non-trivial field of
9734 // a union. However, system headers in Objective-C programs
9735 // occasionally have Objective-C lifetime objects within unions,
9736 // and rather than cause the program to fail, we make those
9737 // members unavailable.
9738 SourceLocation Loc = FD->getLocation();
9739 if (getSourceManager().isInSystemHeader(Loc)) {
9740 if (!FD->hasAttr<UnavailableAttr>())
9741 FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
9742 "this system field has retaining ownership"));
9747 Diag(FD->getLocation(), getLangOpts().CPlusPlus0x ?
9748 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
9749 diag::err_illegal_union_or_anon_struct_member)
9750 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
9751 DiagnoseNontrivial(RT, member);
9752 return !getLangOpts().CPlusPlus0x;
9760 /// If the given constructor is user-declared, produce a diagnostic explaining
9761 /// that it makes the class non-trivial.
9762 static bool diagnoseNonTrivialUserDeclaredCtor(Sema &S, QualType QT,
9763 CXXConstructorDecl *CD,
9764 Sema::CXXSpecialMember CSM) {
9765 if (CD->isImplicit())
9768 SourceLocation CtorLoc = CD->getLocation();
9769 S.Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << CSM;
9773 /// DiagnoseNontrivial - Given that a class has a non-trivial
9774 /// special member, figure out why.
9775 void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
9777 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
9779 // Check whether the member was user-declared.
9784 case CXXDefaultConstructor:
9785 if (RD->hasUserDeclaredConstructor()) {
9786 typedef CXXRecordDecl::ctor_iterator ctor_iter;
9787 for (ctor_iter CI = RD->ctor_begin(), CE = RD->ctor_end(); CI != CE; ++CI)
9788 if (diagnoseNonTrivialUserDeclaredCtor(*this, QT, *CI, member))
9791 // No user-delcared constructors; look for constructor templates.
9792 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9794 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end());
9796 CXXConstructorDecl *CD =
9797 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl());
9798 if (CD && diagnoseNonTrivialUserDeclaredCtor(*this, QT, CD, member))
9804 case CXXCopyConstructor:
9805 if (RD->hasUserDeclaredCopyConstructor()) {
9806 SourceLocation CtorLoc =
9807 RD->getCopyConstructor(0)->getLocation();
9808 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9813 case CXXMoveConstructor:
9814 if (RD->hasUserDeclaredMoveConstructor()) {
9815 SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation();
9816 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9821 case CXXCopyAssignment:
9822 if (RD->hasUserDeclaredCopyAssignment()) {
9823 SourceLocation AssignLoc =
9824 RD->getCopyAssignmentOperator(0)->getLocation();
9825 Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member;
9830 case CXXMoveAssignment:
9831 if (RD->hasUserDeclaredMoveAssignment()) {
9832 SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation();
9833 Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member;
9839 if (RD->hasUserDeclaredDestructor()) {
9840 SourceLocation DtorLoc = LookupDestructor(RD)->getLocation();
9841 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9847 typedef CXXRecordDecl::base_class_iterator base_iter;
9849 // Virtual bases and members inhibit trivial copying/construction,
9850 // but not trivial destruction.
9851 if (member != CXXDestructor) {
9852 // Check for virtual bases. vbases includes indirect virtual bases,
9853 // so we just iterate through the direct bases.
9854 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
9855 if (bi->isVirtual()) {
9856 SourceLocation BaseLoc = bi->getLocStart();
9857 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
9861 // Check for virtual methods.
9862 typedef CXXRecordDecl::method_iterator meth_iter;
9863 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
9865 if (mi->isVirtual()) {
9866 SourceLocation MLoc = mi->getLocStart();
9867 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
9873 bool (CXXRecordDecl::*hasTrivial)() const;
9875 case CXXDefaultConstructor:
9876 hasTrivial = &CXXRecordDecl::hasTrivialDefaultConstructor; break;
9877 case CXXCopyConstructor:
9878 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
9879 case CXXCopyAssignment:
9880 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
9882 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
9884 llvm_unreachable("unexpected special member");
9887 // Check for nontrivial bases (and recurse).
9888 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
9889 const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
9890 assert(BaseRT && "Don't know how to handle dependent bases");
9891 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
9892 if (!(BaseRecTy->*hasTrivial)()) {
9893 SourceLocation BaseLoc = bi->getLocStart();
9894 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
9895 DiagnoseNontrivial(BaseRT, member);
9900 // Check for nontrivial members (and recurse).
9901 typedef RecordDecl::field_iterator field_iter;
9902 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
9904 QualType EltTy = Context.getBaseElementType(fi->getType());
9905 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
9906 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
9908 if (!(EltRD->*hasTrivial)()) {
9909 SourceLocation FLoc = fi->getLocation();
9910 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
9911 DiagnoseNontrivial(EltRT, member);
9916 if (EltTy->isObjCLifetimeType()) {
9917 switch (EltTy.getObjCLifetime()) {
9918 case Qualifiers::OCL_None:
9919 case Qualifiers::OCL_ExplicitNone:
9922 case Qualifiers::OCL_Autoreleasing:
9923 case Qualifiers::OCL_Weak:
9924 case Qualifiers::OCL_Strong:
9925 Diag(fi->getLocation(), diag::note_nontrivial_objc_ownership)
9926 << QT << EltTy.getObjCLifetime();
9932 llvm_unreachable("found no explanation for non-trivial member");
9935 /// TranslateIvarVisibility - Translate visibility from a token ID to an
9937 static ObjCIvarDecl::AccessControl
9938 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
9939 switch (ivarVisibility) {
9940 default: llvm_unreachable("Unknown visitibility kind");
9941 case tok::objc_private: return ObjCIvarDecl::Private;
9942 case tok::objc_public: return ObjCIvarDecl::Public;
9943 case tok::objc_protected: return ObjCIvarDecl::Protected;
9944 case tok::objc_package: return ObjCIvarDecl::Package;
9948 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
9949 /// in order to create an IvarDecl object for it.
9950 Decl *Sema::ActOnIvar(Scope *S,
9951 SourceLocation DeclStart,
9952 Declarator &D, Expr *BitfieldWidth,
9953 tok::ObjCKeywordKind Visibility) {
9955 IdentifierInfo *II = D.getIdentifier();
9956 Expr *BitWidth = (Expr*)BitfieldWidth;
9957 SourceLocation Loc = DeclStart;
9958 if (II) Loc = D.getIdentifierLoc();
9960 // FIXME: Unnamed fields can be handled in various different ways, for
9961 // example, unnamed unions inject all members into the struct namespace!
9963 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9964 QualType T = TInfo->getType();
9967 // 6.7.2.1p3, 6.7.2.1p4
9968 BitWidth = VerifyBitField(Loc, II, T, BitWidth).take();
9977 if (T->isReferenceType()) {
9978 Diag(Loc, diag::err_ivar_reference_type);
9981 // C99 6.7.2.1p8: A member of a structure or union may have any type other
9982 // than a variably modified type.
9983 else if (T->isVariablyModifiedType()) {
9984 Diag(Loc, diag::err_typecheck_ivar_variable_size);
9988 // Get the visibility (access control) for this ivar.
9989 ObjCIvarDecl::AccessControl ac =
9990 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
9991 : ObjCIvarDecl::None;
9992 // Must set ivar's DeclContext to its enclosing interface.
9993 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
9994 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
9996 ObjCContainerDecl *EnclosingContext;
9997 if (ObjCImplementationDecl *IMPDecl =
9998 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
9999 if (LangOpts.ObjCRuntime.isFragile()) {
10000 // Case of ivar declared in an implementation. Context is that of its class.
10001 EnclosingContext = IMPDecl->getClassInterface();
10002 assert(EnclosingContext && "Implementation has no class interface!");
10005 EnclosingContext = EnclosingDecl;
10007 if (ObjCCategoryDecl *CDecl =
10008 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
10009 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
10010 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
10014 EnclosingContext = EnclosingDecl;
10017 // Construct the decl.
10018 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
10019 DeclStart, Loc, II, T,
10020 TInfo, ac, (Expr *)BitfieldWidth);
10023 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
10025 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
10026 && !isa<TagDecl>(PrevDecl)) {
10027 Diag(Loc, diag::err_duplicate_member) << II;
10028 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10029 NewID->setInvalidDecl();
10033 // Process attributes attached to the ivar.
10034 ProcessDeclAttributes(S, NewID, D);
10036 if (D.isInvalidType())
10037 NewID->setInvalidDecl();
10039 // In ARC, infer 'retaining' for ivars of retainable type.
10040 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
10041 NewID->setInvalidDecl();
10043 if (D.getDeclSpec().isModulePrivateSpecified())
10044 NewID->setModulePrivate();
10047 // FIXME: When interfaces are DeclContexts, we'll need to add
10048 // these to the interface.
10050 IdResolver.AddDecl(NewID);
10053 if (LangOpts.ObjCRuntime.isNonFragile() &&
10054 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
10055 Diag(Loc, diag::warn_ivars_in_interface);
10060 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
10061 /// class and class extensions. For every class @interface and class
10062 /// extension @interface, if the last ivar is a bitfield of any type,
10063 /// then add an implicit `char :0` ivar to the end of that interface.
10064 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
10065 SmallVectorImpl<Decl *> &AllIvarDecls) {
10066 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
10069 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
10070 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
10072 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
10074 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
10076 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
10077 if (!CD->IsClassExtension())
10080 // No need to add this to end of @implementation.
10084 // All conditions are met. Add a new bitfield to the tail end of ivars.
10085 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
10086 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
10088 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
10089 DeclLoc, DeclLoc, 0,
10091 Context.getTrivialTypeSourceInfo(Context.CharTy,
10093 ObjCIvarDecl::Private, BW,
10095 AllIvarDecls.push_back(Ivar);
10098 void Sema::ActOnFields(Scope* S,
10099 SourceLocation RecLoc, Decl *EnclosingDecl,
10100 llvm::ArrayRef<Decl *> Fields,
10101 SourceLocation LBrac, SourceLocation RBrac,
10102 AttributeList *Attr) {
10103 assert(EnclosingDecl && "missing record or interface decl");
10105 // If this is an Objective-C @implementation or category and we have
10106 // new fields here we should reset the layout of the interface since
10107 // it will now change.
10108 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
10109 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
10110 switch (DC->getKind()) {
10112 case Decl::ObjCCategory:
10113 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
10115 case Decl::ObjCImplementation:
10117 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
10122 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
10124 // Start counting up the number of named members; make sure to include
10125 // members of anonymous structs and unions in the total.
10126 unsigned NumNamedMembers = 0;
10128 for (RecordDecl::decl_iterator i = Record->decls_begin(),
10129 e = Record->decls_end(); i != e; i++) {
10130 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
10131 if (IFD->getDeclName())
10136 // Verify that all the fields are okay.
10137 SmallVector<FieldDecl*, 32> RecFields;
10139 bool ARCErrReported = false;
10140 for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
10142 FieldDecl *FD = cast<FieldDecl>(*i);
10144 // Get the type for the field.
10145 const Type *FDTy = FD->getType().getTypePtr();
10147 if (!FD->isAnonymousStructOrUnion()) {
10148 // Remember all fields written by the user.
10149 RecFields.push_back(FD);
10152 // If the field is already invalid for some reason, don't emit more
10153 // diagnostics about it.
10154 if (FD->isInvalidDecl()) {
10155 EnclosingDecl->setInvalidDecl();
10160 // A structure or union shall not contain a member with
10161 // incomplete or function type (hence, a structure shall not
10162 // contain an instance of itself, but may contain a pointer to
10163 // an instance of itself), except that the last member of a
10164 // structure with more than one named member may have incomplete
10165 // array type; such a structure (and any union containing,
10166 // possibly recursively, a member that is such a structure)
10167 // shall not be a member of a structure or an element of an
10169 if (FDTy->isFunctionType()) {
10170 // Field declared as a function.
10171 Diag(FD->getLocation(), diag::err_field_declared_as_function)
10172 << FD->getDeclName();
10173 FD->setInvalidDecl();
10174 EnclosingDecl->setInvalidDecl();
10176 } else if (FDTy->isIncompleteArrayType() && Record &&
10177 ((i + 1 == Fields.end() && !Record->isUnion()) ||
10178 ((getLangOpts().MicrosoftExt ||
10179 getLangOpts().CPlusPlus) &&
10180 (i + 1 == Fields.end() || Record->isUnion())))) {
10181 // Flexible array member.
10182 // Microsoft and g++ is more permissive regarding flexible array.
10183 // It will accept flexible array in union and also
10184 // as the sole element of a struct/class.
10185 if (getLangOpts().MicrosoftExt) {
10186 if (Record->isUnion())
10187 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
10188 << FD->getDeclName();
10189 else if (Fields.size() == 1)
10190 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
10191 << FD->getDeclName() << Record->getTagKind();
10192 } else if (getLangOpts().CPlusPlus) {
10193 if (Record->isUnion())
10194 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
10195 << FD->getDeclName();
10196 else if (Fields.size() == 1)
10197 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
10198 << FD->getDeclName() << Record->getTagKind();
10199 } else if (!getLangOpts().C99) {
10200 if (Record->isUnion())
10201 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
10202 << FD->getDeclName();
10204 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
10205 << FD->getDeclName() << Record->getTagKind();
10206 } else if (NumNamedMembers < 1) {
10207 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
10208 << FD->getDeclName();
10209 FD->setInvalidDecl();
10210 EnclosingDecl->setInvalidDecl();
10213 if (!FD->getType()->isDependentType() &&
10214 !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
10215 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
10216 << FD->getDeclName() << FD->getType();
10217 FD->setInvalidDecl();
10218 EnclosingDecl->setInvalidDecl();
10221 // Okay, we have a legal flexible array member at the end of the struct.
10223 Record->setHasFlexibleArrayMember(true);
10224 } else if (!FDTy->isDependentType() &&
10225 RequireCompleteType(FD->getLocation(), FD->getType(),
10226 diag::err_field_incomplete)) {
10228 FD->setInvalidDecl();
10229 EnclosingDecl->setInvalidDecl();
10231 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
10232 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
10233 // If this is a member of a union, then entire union becomes "flexible".
10234 if (Record && Record->isUnion()) {
10235 Record->setHasFlexibleArrayMember(true);
10237 // If this is a struct/class and this is not the last element, reject
10238 // it. Note that GCC supports variable sized arrays in the middle of
10240 if (i + 1 != Fields.end())
10241 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
10242 << FD->getDeclName() << FD->getType();
10244 // We support flexible arrays at the end of structs in
10245 // other structs as an extension.
10246 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
10247 << FD->getDeclName();
10249 Record->setHasFlexibleArrayMember(true);
10253 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
10254 RequireNonAbstractType(FD->getLocation(), FD->getType(),
10255 diag::err_abstract_type_in_decl,
10256 AbstractIvarType)) {
10257 // Ivars can not have abstract class types
10258 FD->setInvalidDecl();
10260 if (Record && FDTTy->getDecl()->hasObjectMember())
10261 Record->setHasObjectMember(true);
10262 } else if (FDTy->isObjCObjectType()) {
10263 /// A field cannot be an Objective-c object
10264 Diag(FD->getLocation(), diag::err_statically_allocated_object)
10265 << FixItHint::CreateInsertion(FD->getLocation(), "*");
10266 QualType T = Context.getObjCObjectPointerType(FD->getType());
10268 } else if (!getLangOpts().CPlusPlus) {
10269 if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported) {
10270 // It's an error in ARC if a field has lifetime.
10271 // We don't want to report this in a system header, though,
10272 // so we just make the field unavailable.
10273 // FIXME: that's really not sufficient; we need to make the type
10274 // itself invalid to, say, initialize or copy.
10275 QualType T = FD->getType();
10276 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
10277 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
10278 SourceLocation loc = FD->getLocation();
10279 if (getSourceManager().isInSystemHeader(loc)) {
10280 if (!FD->hasAttr<UnavailableAttr>()) {
10281 FD->addAttr(new (Context) UnavailableAttr(loc, Context,
10282 "this system field has retaining ownership"));
10285 Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct)
10286 << T->isBlockPointerType();
10288 ARCErrReported = true;
10291 else if (getLangOpts().ObjC1 &&
10292 getLangOpts().getGC() != LangOptions::NonGC &&
10293 Record && !Record->hasObjectMember()) {
10294 if (FD->getType()->isObjCObjectPointerType() ||
10295 FD->getType().isObjCGCStrong())
10296 Record->setHasObjectMember(true);
10297 else if (Context.getAsArrayType(FD->getType())) {
10298 QualType BaseType = Context.getBaseElementType(FD->getType());
10299 if (BaseType->isRecordType() &&
10300 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
10301 Record->setHasObjectMember(true);
10302 else if (BaseType->isObjCObjectPointerType() ||
10303 BaseType.isObjCGCStrong())
10304 Record->setHasObjectMember(true);
10308 // Keep track of the number of named members.
10309 if (FD->getIdentifier())
10313 // Okay, we successfully defined 'Record'.
10315 bool Completed = false;
10316 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
10317 if (!CXXRecord->isInvalidDecl()) {
10318 // Set access bits correctly on the directly-declared conversions.
10319 UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions();
10320 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end();
10322 Convs->setAccess(I, (*I)->getAccess());
10324 if (!CXXRecord->isDependentType()) {
10325 // Adjust user-defined destructor exception spec.
10326 if (getLangOpts().CPlusPlus0x &&
10327 CXXRecord->hasUserDeclaredDestructor())
10328 AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor());
10330 // Add any implicitly-declared members to this class.
10331 AddImplicitlyDeclaredMembersToClass(CXXRecord);
10333 // If we have virtual base classes, we may end up finding multiple
10334 // final overriders for a given virtual function. Check for this
10336 if (CXXRecord->getNumVBases()) {
10337 CXXFinalOverriderMap FinalOverriders;
10338 CXXRecord->getFinalOverriders(FinalOverriders);
10340 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
10341 MEnd = FinalOverriders.end();
10343 for (OverridingMethods::iterator SO = M->second.begin(),
10344 SOEnd = M->second.end();
10345 SO != SOEnd; ++SO) {
10346 assert(SO->second.size() > 0 &&
10347 "Virtual function without overridding functions?");
10348 if (SO->second.size() == 1)
10351 // C++ [class.virtual]p2:
10352 // In a derived class, if a virtual member function of a base
10353 // class subobject has more than one final overrider the
10354 // program is ill-formed.
10355 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
10356 << (const NamedDecl *)M->first << Record;
10357 Diag(M->first->getLocation(),
10358 diag::note_overridden_virtual_function);
10359 for (OverridingMethods::overriding_iterator
10360 OM = SO->second.begin(),
10361 OMEnd = SO->second.end();
10363 Diag(OM->Method->getLocation(), diag::note_final_overrider)
10364 << (const NamedDecl *)M->first << OM->Method->getParent();
10366 Record->setInvalidDecl();
10369 CXXRecord->completeDefinition(&FinalOverriders);
10377 Record->completeDefinition();
10380 ObjCIvarDecl **ClsFields =
10381 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
10382 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
10383 ID->setEndOfDefinitionLoc(RBrac);
10384 // Add ivar's to class's DeclContext.
10385 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
10386 ClsFields[i]->setLexicalDeclContext(ID);
10387 ID->addDecl(ClsFields[i]);
10389 // Must enforce the rule that ivars in the base classes may not be
10391 if (ID->getSuperClass())
10392 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
10393 } else if (ObjCImplementationDecl *IMPDecl =
10394 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
10395 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
10396 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
10397 // Ivar declared in @implementation never belongs to the implementation.
10398 // Only it is in implementation's lexical context.
10399 ClsFields[I]->setLexicalDeclContext(IMPDecl);
10400 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
10401 IMPDecl->setIvarLBraceLoc(LBrac);
10402 IMPDecl->setIvarRBraceLoc(RBrac);
10403 } else if (ObjCCategoryDecl *CDecl =
10404 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
10405 // case of ivars in class extension; all other cases have been
10406 // reported as errors elsewhere.
10407 // FIXME. Class extension does not have a LocEnd field.
10408 // CDecl->setLocEnd(RBrac);
10409 // Add ivar's to class extension's DeclContext.
10410 // Diagnose redeclaration of private ivars.
10411 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
10412 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
10414 if (const ObjCIvarDecl *ClsIvar =
10415 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
10416 Diag(ClsFields[i]->getLocation(),
10417 diag::err_duplicate_ivar_declaration);
10418 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
10421 for (const ObjCCategoryDecl *ClsExtDecl =
10422 IDecl->getFirstClassExtension();
10423 ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
10424 if (const ObjCIvarDecl *ClsExtIvar =
10425 ClsExtDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
10426 Diag(ClsFields[i]->getLocation(),
10427 diag::err_duplicate_ivar_declaration);
10428 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
10433 ClsFields[i]->setLexicalDeclContext(CDecl);
10434 CDecl->addDecl(ClsFields[i]);
10436 CDecl->setIvarLBraceLoc(LBrac);
10437 CDecl->setIvarRBraceLoc(RBrac);
10442 ProcessDeclAttributeList(S, Record, Attr);
10445 /// \brief Determine whether the given integral value is representable within
10446 /// the given type T.
10447 static bool isRepresentableIntegerValue(ASTContext &Context,
10448 llvm::APSInt &Value,
10450 assert(T->isIntegralType(Context) && "Integral type required!");
10451 unsigned BitWidth = Context.getIntWidth(T);
10453 if (Value.isUnsigned() || Value.isNonNegative()) {
10454 if (T->isSignedIntegerOrEnumerationType())
10456 return Value.getActiveBits() <= BitWidth;
10458 return Value.getMinSignedBits() <= BitWidth;
10461 // \brief Given an integral type, return the next larger integral type
10462 // (or a NULL type of no such type exists).
10463 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
10464 // FIXME: Int128/UInt128 support, which also needs to be introduced into
10465 // enum checking below.
10466 assert(T->isIntegralType(Context) && "Integral type required!");
10467 const unsigned NumTypes = 4;
10468 QualType SignedIntegralTypes[NumTypes] = {
10469 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
10471 QualType UnsignedIntegralTypes[NumTypes] = {
10472 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
10473 Context.UnsignedLongLongTy
10476 unsigned BitWidth = Context.getTypeSize(T);
10477 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
10478 : UnsignedIntegralTypes;
10479 for (unsigned I = 0; I != NumTypes; ++I)
10480 if (Context.getTypeSize(Types[I]) > BitWidth)
10486 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
10487 EnumConstantDecl *LastEnumConst,
10488 SourceLocation IdLoc,
10489 IdentifierInfo *Id,
10491 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
10492 llvm::APSInt EnumVal(IntWidth);
10495 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
10499 Val = DefaultLvalueConversion(Val).take();
10502 if (Enum->isDependentType() || Val->isTypeDependent())
10503 EltTy = Context.DependentTy;
10505 SourceLocation ExpLoc;
10506 if (getLangOpts().CPlusPlus0x && Enum->isFixed() &&
10507 !getLangOpts().MicrosoftMode) {
10508 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
10509 // constant-expression in the enumerator-definition shall be a converted
10510 // constant expression of the underlying type.
10511 EltTy = Enum->getIntegerType();
10512 ExprResult Converted =
10513 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
10515 if (Converted.isInvalid())
10518 Val = Converted.take();
10519 } else if (!Val->isValueDependent() &&
10520 !(Val = VerifyIntegerConstantExpression(Val,
10521 &EnumVal).take())) {
10522 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
10524 if (Enum->isFixed()) {
10525 EltTy = Enum->getIntegerType();
10527 // In Obj-C and Microsoft mode, require the enumeration value to be
10528 // representable in the underlying type of the enumeration. In C++11,
10529 // we perform a non-narrowing conversion as part of converted constant
10530 // expression checking.
10531 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
10532 if (getLangOpts().MicrosoftMode) {
10533 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
10534 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
10536 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
10538 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
10539 } else if (getLangOpts().CPlusPlus) {
10540 // C++11 [dcl.enum]p5:
10541 // If the underlying type is not fixed, the type of each enumerator
10542 // is the type of its initializing value:
10543 // - If an initializer is specified for an enumerator, the
10544 // initializing value has the same type as the expression.
10545 EltTy = Val->getType();
10548 // The expression that defines the value of an enumeration constant
10549 // shall be an integer constant expression that has a value
10550 // representable as an int.
10552 // Complain if the value is not representable in an int.
10553 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
10554 Diag(IdLoc, diag::ext_enum_value_not_int)
10555 << EnumVal.toString(10) << Val->getSourceRange()
10556 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
10557 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
10558 // Force the type of the expression to 'int'.
10559 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
10561 EltTy = Val->getType();
10568 if (Enum->isDependentType())
10569 EltTy = Context.DependentTy;
10570 else if (!LastEnumConst) {
10571 // C++0x [dcl.enum]p5:
10572 // If the underlying type is not fixed, the type of each enumerator
10573 // is the type of its initializing value:
10574 // - If no initializer is specified for the first enumerator, the
10575 // initializing value has an unspecified integral type.
10577 // GCC uses 'int' for its unspecified integral type, as does
10579 if (Enum->isFixed()) {
10580 EltTy = Enum->getIntegerType();
10583 EltTy = Context.IntTy;
10586 // Assign the last value + 1.
10587 EnumVal = LastEnumConst->getInitVal();
10589 EltTy = LastEnumConst->getType();
10591 // Check for overflow on increment.
10592 if (EnumVal < LastEnumConst->getInitVal()) {
10593 // C++0x [dcl.enum]p5:
10594 // If the underlying type is not fixed, the type of each enumerator
10595 // is the type of its initializing value:
10597 // - Otherwise the type of the initializing value is the same as
10598 // the type of the initializing value of the preceding enumerator
10599 // unless the incremented value is not representable in that type,
10600 // in which case the type is an unspecified integral type
10601 // sufficient to contain the incremented value. If no such type
10602 // exists, the program is ill-formed.
10603 QualType T = getNextLargerIntegralType(Context, EltTy);
10604 if (T.isNull() || Enum->isFixed()) {
10605 // There is no integral type larger enough to represent this
10606 // value. Complain, then allow the value to wrap around.
10607 EnumVal = LastEnumConst->getInitVal();
10608 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
10610 if (Enum->isFixed())
10611 // When the underlying type is fixed, this is ill-formed.
10612 Diag(IdLoc, diag::err_enumerator_wrapped)
10613 << EnumVal.toString(10)
10616 Diag(IdLoc, diag::warn_enumerator_too_large)
10617 << EnumVal.toString(10);
10622 // Retrieve the last enumerator's value, extent that type to the
10623 // type that is supposed to be large enough to represent the incremented
10624 // value, then increment.
10625 EnumVal = LastEnumConst->getInitVal();
10626 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
10627 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
10630 // If we're not in C++, diagnose the overflow of enumerator values,
10631 // which in C99 means that the enumerator value is not representable in
10632 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
10633 // permits enumerator values that are representable in some larger
10635 if (!getLangOpts().CPlusPlus && !T.isNull())
10636 Diag(IdLoc, diag::warn_enum_value_overflow);
10637 } else if (!getLangOpts().CPlusPlus &&
10638 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
10639 // Enforce C99 6.7.2.2p2 even when we compute the next value.
10640 Diag(IdLoc, diag::ext_enum_value_not_int)
10641 << EnumVal.toString(10) << 1;
10646 if (!EltTy->isDependentType()) {
10647 // Make the enumerator value match the signedness and size of the
10648 // enumerator's type.
10649 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
10650 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
10653 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
10658 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
10659 SourceLocation IdLoc, IdentifierInfo *Id,
10660 AttributeList *Attr,
10661 SourceLocation EqualLoc, Expr *Val) {
10662 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
10663 EnumConstantDecl *LastEnumConst =
10664 cast_or_null<EnumConstantDecl>(lastEnumConst);
10666 // The scope passed in may not be a decl scope. Zip up the scope tree until
10667 // we find one that is.
10668 S = getNonFieldDeclScope(S);
10670 // Verify that there isn't already something declared with this name in this
10672 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
10674 if (PrevDecl && PrevDecl->isTemplateParameter()) {
10675 // Maybe we will complain about the shadowed template parameter.
10676 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
10677 // Just pretend that we didn't see the previous declaration.
10682 // When in C++, we may get a TagDecl with the same name; in this case the
10683 // enum constant will 'hide' the tag.
10684 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
10685 "Received TagDecl when not in C++!");
10686 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
10687 if (isa<EnumConstantDecl>(PrevDecl))
10688 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
10690 Diag(IdLoc, diag::err_redefinition) << Id;
10691 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10696 // C++ [class.mem]p15:
10697 // If T is the name of a class, then each of the following shall have a name
10698 // different from T:
10699 // - every enumerator of every member of class T that is an unscoped
10701 if (CXXRecordDecl *Record
10702 = dyn_cast<CXXRecordDecl>(
10703 TheEnumDecl->getDeclContext()->getRedeclContext()))
10704 if (!TheEnumDecl->isScoped() &&
10705 Record->getIdentifier() && Record->getIdentifier() == Id)
10706 Diag(IdLoc, diag::err_member_name_of_class) << Id;
10708 EnumConstantDecl *New =
10709 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
10712 // Process attributes.
10713 if (Attr) ProcessDeclAttributeList(S, New, Attr);
10715 // Register this decl in the current scope stack.
10716 New->setAccess(TheEnumDecl->getAccess());
10717 PushOnScopeChains(New, S);
10720 ActOnDocumentableDecl(New);
10725 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
10726 SourceLocation RBraceLoc, Decl *EnumDeclX,
10727 Decl **Elements, unsigned NumElements,
10728 Scope *S, AttributeList *Attr) {
10729 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
10730 QualType EnumType = Context.getTypeDeclType(Enum);
10733 ProcessDeclAttributeList(S, Enum, Attr);
10735 if (Enum->isDependentType()) {
10736 for (unsigned i = 0; i != NumElements; ++i) {
10737 EnumConstantDecl *ECD =
10738 cast_or_null<EnumConstantDecl>(Elements[i]);
10739 if (!ECD) continue;
10741 ECD->setType(EnumType);
10744 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
10748 // TODO: If the result value doesn't fit in an int, it must be a long or long
10749 // long value. ISO C does not support this, but GCC does as an extension,
10751 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
10752 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
10753 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
10755 // Verify that all the values are okay, compute the size of the values, and
10756 // reverse the list.
10757 unsigned NumNegativeBits = 0;
10758 unsigned NumPositiveBits = 0;
10760 // Keep track of whether all elements have type int.
10761 bool AllElementsInt = true;
10763 for (unsigned i = 0; i != NumElements; ++i) {
10764 EnumConstantDecl *ECD =
10765 cast_or_null<EnumConstantDecl>(Elements[i]);
10766 if (!ECD) continue; // Already issued a diagnostic.
10768 const llvm::APSInt &InitVal = ECD->getInitVal();
10770 // Keep track of the size of positive and negative values.
10771 if (InitVal.isUnsigned() || InitVal.isNonNegative())
10772 NumPositiveBits = std::max(NumPositiveBits,
10773 (unsigned)InitVal.getActiveBits());
10775 NumNegativeBits = std::max(NumNegativeBits,
10776 (unsigned)InitVal.getMinSignedBits());
10778 // Keep track of whether every enum element has type int (very commmon).
10779 if (AllElementsInt)
10780 AllElementsInt = ECD->getType() == Context.IntTy;
10783 // Figure out the type that should be used for this enum.
10785 unsigned BestWidth;
10787 // C++0x N3000 [conv.prom]p3:
10788 // An rvalue of an unscoped enumeration type whose underlying
10789 // type is not fixed can be converted to an rvalue of the first
10790 // of the following types that can represent all the values of
10791 // the enumeration: int, unsigned int, long int, unsigned long
10792 // int, long long int, or unsigned long long int.
10794 // An identifier declared as an enumeration constant has type int.
10795 // The C99 rule is modified by a gcc extension
10796 QualType BestPromotionType;
10798 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
10799 // -fshort-enums is the equivalent to specifying the packed attribute on all
10800 // enum definitions.
10801 if (LangOpts.ShortEnums)
10804 if (Enum->isFixed()) {
10805 BestType = Enum->getIntegerType();
10806 if (BestType->isPromotableIntegerType())
10807 BestPromotionType = Context.getPromotedIntegerType(BestType);
10809 BestPromotionType = BestType;
10810 // We don't need to set BestWidth, because BestType is going to be the type
10811 // of the enumerators, but we do anyway because otherwise some compilers
10812 // warn that it might be used uninitialized.
10813 BestWidth = CharWidth;
10815 else if (NumNegativeBits) {
10816 // If there is a negative value, figure out the smallest integer type (of
10817 // int/long/longlong) that fits.
10818 // If it's packed, check also if it fits a char or a short.
10819 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
10820 BestType = Context.SignedCharTy;
10821 BestWidth = CharWidth;
10822 } else if (Packed && NumNegativeBits <= ShortWidth &&
10823 NumPositiveBits < ShortWidth) {
10824 BestType = Context.ShortTy;
10825 BestWidth = ShortWidth;
10826 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
10827 BestType = Context.IntTy;
10828 BestWidth = IntWidth;
10830 BestWidth = Context.getTargetInfo().getLongWidth();
10832 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
10833 BestType = Context.LongTy;
10835 BestWidth = Context.getTargetInfo().getLongLongWidth();
10837 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
10838 Diag(Enum->getLocation(), diag::warn_enum_too_large);
10839 BestType = Context.LongLongTy;
10842 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
10844 // If there is no negative value, figure out the smallest type that fits
10845 // all of the enumerator values.
10846 // If it's packed, check also if it fits a char or a short.
10847 if (Packed && NumPositiveBits <= CharWidth) {
10848 BestType = Context.UnsignedCharTy;
10849 BestPromotionType = Context.IntTy;
10850 BestWidth = CharWidth;
10851 } else if (Packed && NumPositiveBits <= ShortWidth) {
10852 BestType = Context.UnsignedShortTy;
10853 BestPromotionType = Context.IntTy;
10854 BestWidth = ShortWidth;
10855 } else if (NumPositiveBits <= IntWidth) {
10856 BestType = Context.UnsignedIntTy;
10857 BestWidth = IntWidth;
10859 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
10860 ? Context.UnsignedIntTy : Context.IntTy;
10861 } else if (NumPositiveBits <=
10862 (BestWidth = Context.getTargetInfo().getLongWidth())) {
10863 BestType = Context.UnsignedLongTy;
10865 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
10866 ? Context.UnsignedLongTy : Context.LongTy;
10868 BestWidth = Context.getTargetInfo().getLongLongWidth();
10869 assert(NumPositiveBits <= BestWidth &&
10870 "How could an initializer get larger than ULL?");
10871 BestType = Context.UnsignedLongLongTy;
10873 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
10874 ? Context.UnsignedLongLongTy : Context.LongLongTy;
10878 // Loop over all of the enumerator constants, changing their types to match
10879 // the type of the enum if needed.
10880 for (unsigned i = 0; i != NumElements; ++i) {
10881 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
10882 if (!ECD) continue; // Already issued a diagnostic.
10884 // Standard C says the enumerators have int type, but we allow, as an
10885 // extension, the enumerators to be larger than int size. If each
10886 // enumerator value fits in an int, type it as an int, otherwise type it the
10887 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
10888 // that X has type 'int', not 'unsigned'.
10890 // Determine whether the value fits into an int.
10891 llvm::APSInt InitVal = ECD->getInitVal();
10893 // If it fits into an integer type, force it. Otherwise force it to match
10894 // the enum decl type.
10898 if (!getLangOpts().CPlusPlus &&
10899 !Enum->isFixed() &&
10900 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
10901 NewTy = Context.IntTy;
10902 NewWidth = IntWidth;
10904 } else if (ECD->getType() == BestType) {
10905 // Already the right type!
10906 if (getLangOpts().CPlusPlus)
10907 // C++ [dcl.enum]p4: Following the closing brace of an
10908 // enum-specifier, each enumerator has the type of its
10910 ECD->setType(EnumType);
10914 NewWidth = BestWidth;
10915 NewSign = BestType->isSignedIntegerOrEnumerationType();
10918 // Adjust the APSInt value.
10919 InitVal = InitVal.extOrTrunc(NewWidth);
10920 InitVal.setIsSigned(NewSign);
10921 ECD->setInitVal(InitVal);
10923 // Adjust the Expr initializer and type.
10924 if (ECD->getInitExpr() &&
10925 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
10926 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
10928 ECD->getInitExpr(),
10931 if (getLangOpts().CPlusPlus)
10932 // C++ [dcl.enum]p4: Following the closing brace of an
10933 // enum-specifier, each enumerator has the type of its
10935 ECD->setType(EnumType);
10937 ECD->setType(NewTy);
10940 Enum->completeDefinition(BestType, BestPromotionType,
10941 NumPositiveBits, NumNegativeBits);
10943 // If we're declaring a function, ensure this decl isn't forgotten about -
10944 // it needs to go into the function scope.
10945 if (InFunctionDeclarator)
10946 DeclsInPrototypeScope.push_back(Enum);
10949 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
10950 SourceLocation StartLoc,
10951 SourceLocation EndLoc) {
10952 StringLiteral *AsmString = cast<StringLiteral>(expr);
10954 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
10955 AsmString, StartLoc,
10957 CurContext->addDecl(New);
10961 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
10962 SourceLocation ImportLoc,
10963 ModuleIdPath Path) {
10964 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
10965 Module::AllVisible,
10966 /*IsIncludeDirective=*/false);
10970 llvm::SmallVector<SourceLocation, 2> IdentifierLocs;
10971 Module *ModCheck = Mod;
10972 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
10973 // If we've run out of module parents, just drop the remaining identifiers.
10974 // We need the length to be consistent.
10977 ModCheck = ModCheck->Parent;
10979 IdentifierLocs.push_back(Path[I].second);
10982 ImportDecl *Import = ImportDecl::Create(Context,
10983 Context.getTranslationUnitDecl(),
10984 AtLoc.isValid()? AtLoc : ImportLoc,
10985 Mod, IdentifierLocs);
10986 Context.getTranslationUnitDecl()->addDecl(Import);
10990 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
10991 IdentifierInfo* AliasName,
10992 SourceLocation PragmaLoc,
10993 SourceLocation NameLoc,
10994 SourceLocation AliasNameLoc) {
10995 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
10996 LookupOrdinaryName);
10997 AsmLabelAttr *Attr =
10998 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
11001 PrevDecl->addAttr(Attr);
11003 (void)ExtnameUndeclaredIdentifiers.insert(
11004 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
11007 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
11008 SourceLocation PragmaLoc,
11009 SourceLocation NameLoc) {
11010 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
11013 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
11015 (void)WeakUndeclaredIdentifiers.insert(
11016 std::pair<IdentifierInfo*,WeakInfo>
11017 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
11021 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
11022 IdentifierInfo* AliasName,
11023 SourceLocation PragmaLoc,
11024 SourceLocation NameLoc,
11025 SourceLocation AliasNameLoc) {
11026 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
11027 LookupOrdinaryName);
11028 WeakInfo W = WeakInfo(Name, NameLoc);
11031 if (!PrevDecl->hasAttr<AliasAttr>())
11032 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
11033 DeclApplyPragmaWeak(TUScope, ND, W);
11035 (void)WeakUndeclaredIdentifiers.insert(
11036 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
11040 Decl *Sema::getObjCDeclContext() const {
11041 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
11044 AvailabilityResult Sema::getCurContextAvailability() const {
11045 const Decl *D = cast<Decl>(getCurObjCLexicalContext());
11046 return D->getAvailability();