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 //===----------------------------------------------------------------------===//
17 #include "clang/Analysis/AnalysisContext.h"
18 #include "clang/AST/APValue.h"
19 #include "clang/AST/ASTConsumer.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/CXXInheritance.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/Parse/DeclSpec.h"
26 #include "clang/Parse/ParseDiagnostic.h"
27 #include "clang/Parse/Template.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 // FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Lex/HeaderSearch.h"
34 #include "llvm/ADT/Triple.h"
38 using namespace clang;
40 /// getDeclName - Return a pretty name for the specified decl if possible, or
41 /// an empty string if not. This is used for pretty crash reporting.
42 std::string Sema::getDeclName(DeclPtrTy d) {
43 Decl *D = d.getAs<Decl>();
44 if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(D))
45 return DN->getQualifiedNameAsString();
49 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(DeclPtrTy Ptr) {
50 return DeclGroupPtrTy::make(DeclGroupRef(Ptr.getAs<Decl>()));
53 /// \brief If the identifier refers to a type name within this scope,
54 /// return the declaration of that type.
56 /// This routine performs ordinary name lookup of the identifier II
57 /// within the given scope, with optional C++ scope specifier SS, to
58 /// determine whether the name refers to a type. If so, returns an
59 /// opaque pointer (actually a QualType) corresponding to that
60 /// type. Otherwise, returns NULL.
62 /// If name lookup results in an ambiguity, this routine will complain
63 /// and then return NULL.
64 Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
65 Scope *S, const CXXScopeSpec *SS,
67 TypeTy *ObjectTypePtr) {
68 // Determine where we will perform name lookup.
69 DeclContext *LookupCtx = 0;
71 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
72 if (ObjectType->isRecordType())
73 LookupCtx = computeDeclContext(ObjectType);
74 } else if (SS && SS->isSet()) {
75 LookupCtx = computeDeclContext(*SS, false);
78 if (isDependentScopeSpecifier(*SS)) {
80 // A qualified-id that refers to a type and in which the
81 // nested-name-specifier depends on a template-parameter (14.6.2)
82 // shall be prefixed by the keyword typename to indicate that the
83 // qualified-id denotes a type, forming an
84 // elaborated-type-specifier (7.1.5.3).
86 // We therefore do not perform any name lookup if the result would
87 // refer to a member of an unknown specialization.
91 // We know from the grammar that this name refers to a type, so build a
92 // TypenameType node to describe the type.
93 // FIXME: Record somewhere that this TypenameType node has no "typename"
94 // keyword associated with it.
95 return CheckTypenameType((NestedNameSpecifier *)SS->getScopeRep(),
96 II, SS->getRange()).getAsOpaquePtr();
102 if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(*SS))
106 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
107 // lookup for class-names.
108 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
110 LookupResult Result(*this, &II, NameLoc, Kind);
112 // Perform "qualified" name lookup into the declaration context we
113 // computed, which is either the type of the base of a member access
114 // expression or the declaration context associated with a prior
115 // nested-name-specifier.
116 LookupQualifiedName(Result, LookupCtx);
118 if (ObjectTypePtr && Result.empty()) {
119 // C++ [basic.lookup.classref]p3:
120 // If the unqualified-id is ~type-name, the type-name is looked up
121 // in the context of the entire postfix-expression. If the type T of
122 // the object expression is of a class type C, the type-name is also
123 // looked up in the scope of class C. At least one of the lookups shall
124 // find a name that refers to (possibly cv-qualified) T.
125 LookupName(Result, S);
128 // Perform unqualified name lookup.
129 LookupName(Result, S);
132 NamedDecl *IIDecl = 0;
133 switch (Result.getResultKind()) {
134 case LookupResult::NotFound:
135 case LookupResult::NotFoundInCurrentInstantiation:
136 case LookupResult::FoundOverloaded:
137 case LookupResult::FoundUnresolvedValue:
138 Result.suppressDiagnostics();
141 case LookupResult::Ambiguous:
142 // Recover from type-hiding ambiguities by hiding the type. We'll
143 // do the lookup again when looking for an object, and we can
144 // diagnose the error then. If we don't do this, then the error
145 // about hiding the type will be immediately followed by an error
146 // that only makes sense if the identifier was treated like a type.
147 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
148 Result.suppressDiagnostics();
152 // Look to see if we have a type anywhere in the list of results.
153 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
154 Res != ResEnd; ++Res) {
155 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
157 (*Res)->getLocation().getRawEncoding() <
158 IIDecl->getLocation().getRawEncoding())
164 // None of the entities we found is a type, so there is no way
165 // to even assume that the result is a type. In this case, don't
166 // complain about the ambiguity. The parser will either try to
167 // perform this lookup again (e.g., as an object name), which
168 // will produce the ambiguity, or will complain that it expected
170 Result.suppressDiagnostics();
174 // We found a type within the ambiguous lookup; diagnose the
175 // ambiguity and then return that type. This might be the right
176 // answer, or it might not be, but it suppresses any attempt to
177 // perform the name lookup again.
180 case LookupResult::Found:
181 IIDecl = Result.getFoundDecl();
185 assert(IIDecl && "Didn't find decl");
188 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
189 DiagnoseUseOfDecl(IIDecl, NameLoc);
191 // C++ [temp.local]p2:
192 // Within the scope of a class template specialization or
193 // partial specialization, when the injected-class-name is
194 // not followed by a <, it is equivalent to the
195 // injected-class-name followed by the template-argument s
196 // of the class template specialization or partial
197 // specialization enclosed in <>.
198 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD))
199 if (RD->isInjectedClassName())
200 if (ClassTemplateDecl *Template = RD->getDescribedClassTemplate())
201 T = Template->getInjectedClassNameType(Context);
204 T = Context.getTypeDeclType(TD);
207 T = getQualifiedNameType(*SS, T);
209 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
210 T = Context.getObjCInterfaceType(IDecl);
211 } else if (UnresolvedUsingTypenameDecl *UUDecl =
212 dyn_cast<UnresolvedUsingTypenameDecl>(IIDecl)) {
213 // FIXME: preserve source structure information.
214 T = Context.getTypenameType(UUDecl->getTargetNestedNameSpecifier(), &II);
216 // If it's not plausibly a type, suppress diagnostics.
217 Result.suppressDiagnostics();
221 return T.getAsOpaquePtr();
224 /// isTagName() - This method is called *for error recovery purposes only*
225 /// to determine if the specified name is a valid tag name ("struct foo"). If
226 /// so, this returns the TST for the tag corresponding to it (TST_enum,
227 /// TST_union, TST_struct, TST_class). This is used to diagnose cases in C
228 /// where the user forgot to specify the tag.
229 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
230 // Do a tag name lookup in this scope.
231 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
232 LookupName(R, S, false);
233 R.suppressDiagnostics();
234 if (R.getResultKind() == LookupResult::Found)
235 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
236 switch (TD->getTagKind()) {
237 case TagDecl::TK_struct: return DeclSpec::TST_struct;
238 case TagDecl::TK_union: return DeclSpec::TST_union;
239 case TagDecl::TK_class: return DeclSpec::TST_class;
240 case TagDecl::TK_enum: return DeclSpec::TST_enum;
244 return DeclSpec::TST_unspecified;
247 bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
248 SourceLocation IILoc,
250 const CXXScopeSpec *SS,
251 TypeTy *&SuggestedType) {
252 // We don't have anything to suggest (yet).
255 // There may have been a typo in the name of the type. Look up typo
256 // results, in case we have something that we can suggest.
257 LookupResult Lookup(*this, &II, IILoc, LookupOrdinaryName,
258 NotForRedeclaration);
260 // FIXME: It would be nice if we could correct for typos in built-in
261 // names, such as "itn" for "int".
263 if (CorrectTypo(Lookup, S, SS) && Lookup.isSingleResult()) {
264 NamedDecl *Result = Lookup.getAsSingle<NamedDecl>();
265 if ((isa<TypeDecl>(Result) || isa<ObjCInterfaceDecl>(Result)) &&
266 !Result->isInvalidDecl()) {
267 // We found a similarly-named type or interface; suggest that.
268 if (!SS || !SS->isSet())
269 Diag(IILoc, diag::err_unknown_typename_suggest)
270 << &II << Lookup.getLookupName()
271 << CodeModificationHint::CreateReplacement(SourceRange(IILoc),
272 Result->getNameAsString());
273 else if (DeclContext *DC = computeDeclContext(*SS, false))
274 Diag(IILoc, diag::err_unknown_nested_typename_suggest)
275 << &II << DC << Lookup.getLookupName() << SS->getRange()
276 << CodeModificationHint::CreateReplacement(SourceRange(IILoc),
277 Result->getNameAsString());
279 llvm_unreachable("could not have corrected a typo here");
281 Diag(Result->getLocation(), diag::note_previous_decl)
282 << Result->getDeclName();
284 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS);
289 // FIXME: Should we move the logic that tries to recover from a missing tag
290 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
292 if (!SS || (!SS->isSet() && !SS->isInvalid()))
293 Diag(IILoc, diag::err_unknown_typename) << &II;
294 else if (DeclContext *DC = computeDeclContext(*SS, false))
295 Diag(IILoc, diag::err_typename_nested_not_found)
296 << &II << DC << SS->getRange();
297 else if (isDependentScopeSpecifier(*SS)) {
298 Diag(SS->getRange().getBegin(), diag::err_typename_missing)
299 << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
300 << SourceRange(SS->getRange().getBegin(), IILoc)
301 << CodeModificationHint::CreateInsertion(SS->getRange().getBegin(),
303 SuggestedType = ActOnTypenameType(SourceLocation(), *SS, II, IILoc).get();
305 assert(SS && SS->isInvalid() &&
306 "Invalid scope specifier has already been diagnosed");
312 // Determines the context to return to after temporarily entering a
313 // context. This depends in an unnecessarily complicated way on the
314 // exact ordering of callbacks from the parser.
315 DeclContext *Sema::getContainingDC(DeclContext *DC) {
317 // Functions defined inline within classes aren't parsed until we've
318 // finished parsing the top-level class, so the top-level class is
319 // the context we'll need to return to.
320 if (isa<FunctionDecl>(DC)) {
321 DC = DC->getLexicalParent();
323 // A function not defined within a class will always return to its
325 if (!isa<CXXRecordDecl>(DC))
328 // A C++ inline method/friend is parsed *after* the topmost class
329 // it was declared in is fully parsed ("complete"); the topmost
330 // class is the context we need to return to.
331 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
334 // Return the declaration context of the topmost class the inline method is
339 if (isa<ObjCMethodDecl>(DC))
340 return Context.getTranslationUnitDecl();
342 return DC->getLexicalParent();
345 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
346 assert(getContainingDC(DC) == CurContext &&
347 "The next DeclContext should be lexically contained in the current one.");
352 void Sema::PopDeclContext() {
353 assert(CurContext && "DeclContext imbalance!");
355 CurContext = getContainingDC(CurContext);
358 /// EnterDeclaratorContext - Used when we must lookup names in the context
359 /// of a declarator's nested name specifier.
361 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
362 // C++0x [basic.lookup.unqual]p13:
363 // A name used in the definition of a static data member of class
364 // X (after the qualified-id of the static member) is looked up as
365 // if the name was used in a member function of X.
366 // C++0x [basic.lookup.unqual]p14:
367 // If a variable member of a namespace is defined outside of the
368 // scope of its namespace then any name used in the definition of
369 // the variable member (after the declarator-id) is looked up as
370 // if the definition of the variable member occurred in its
372 // Both of these imply that we should push a scope whose context
373 // is the semantic context of the declaration. We can't use
374 // PushDeclContext here because that context is not necessarily
375 // lexically contained in the current context. Fortunately,
376 // the containing scope should have the appropriate information.
378 assert(!S->getEntity() && "scope already has entity");
381 Scope *Ancestor = S->getParent();
382 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
383 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
390 void Sema::ExitDeclaratorContext(Scope *S) {
391 assert(S->getEntity() == CurContext && "Context imbalance!");
393 // Switch back to the lexical context. The safety of this is
394 // enforced by an assert in EnterDeclaratorContext.
395 Scope *Ancestor = S->getParent();
396 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
397 CurContext = (DeclContext*) Ancestor->getEntity();
399 // We don't need to do anything with the scope, which is going to
403 /// \brief Determine whether we allow overloading of the function
404 /// PrevDecl with another declaration.
406 /// This routine determines whether overloading is possible, not
407 /// whether some new function is actually an overload. It will return
408 /// true in C++ (where we can always provide overloads) or, as an
409 /// extension, in C when the previous function is already an
410 /// overloaded function declaration or has the "overloadable"
412 static bool AllowOverloadingOfFunction(LookupResult &Previous,
413 ASTContext &Context) {
414 if (Context.getLangOptions().CPlusPlus)
417 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
420 return (Previous.getResultKind() == LookupResult::Found
421 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
424 /// Add this decl to the scope shadowed decl chains.
425 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
426 // Move up the scope chain until we find the nearest enclosing
427 // non-transparent context. The declaration will be introduced into this
429 while (S->getEntity() &&
430 ((DeclContext *)S->getEntity())->isTransparentContext())
433 // Add scoped declarations into their context, so that they can be
434 // found later. Declarations without a context won't be inserted
437 CurContext->addDecl(D);
439 // Out-of-line function and variable definitions should not be pushed into
441 if ((isa<FunctionTemplateDecl>(D) &&
442 cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->isOutOfLine()) ||
443 (isa<FunctionDecl>(D) &&
444 (cast<FunctionDecl>(D)->isFunctionTemplateSpecialization() ||
445 cast<FunctionDecl>(D)->isOutOfLine())) ||
446 (isa<VarDecl>(D) && cast<VarDecl>(D)->isOutOfLine()))
449 // If this replaces anything in the current scope,
450 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
451 IEnd = IdResolver.end();
452 for (; I != IEnd; ++I) {
453 if (S->isDeclScope(DeclPtrTy::make(*I)) && D->declarationReplaces(*I)) {
454 S->RemoveDecl(DeclPtrTy::make(*I));
455 IdResolver.RemoveDecl(*I);
457 // Should only need to replace one decl.
462 S->AddDecl(DeclPtrTy::make(D));
463 IdResolver.AddDecl(D);
466 bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S) {
467 return IdResolver.isDeclInScope(D, Ctx, Context, S);
470 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
474 /// Filters out lookup results that don't fall within the given scope
475 /// as determined by isDeclInScope.
476 static void FilterLookupForScope(Sema &SemaRef, LookupResult &R,
477 DeclContext *Ctx, Scope *S,
478 bool ConsiderLinkage) {
479 LookupResult::Filter F = R.makeFilter();
480 while (F.hasNext()) {
481 NamedDecl *D = F.next();
483 if (SemaRef.isDeclInScope(D, Ctx, S))
486 if (ConsiderLinkage &&
487 isOutOfScopePreviousDeclaration(D, Ctx, SemaRef.Context))
496 static bool isUsingDecl(NamedDecl *D) {
497 return isa<UsingShadowDecl>(D) ||
498 isa<UnresolvedUsingTypenameDecl>(D) ||
499 isa<UnresolvedUsingValueDecl>(D);
502 /// Removes using shadow declarations from the lookup results.
503 static void RemoveUsingDecls(LookupResult &R) {
504 LookupResult::Filter F = R.makeFilter();
506 if (isUsingDecl(F.next()))
512 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
513 if (D->isInvalidDecl())
516 if (D->isUsed() || D->hasAttr<UnusedAttr>())
519 // White-list anything that isn't a local variable.
520 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
521 !D->getDeclContext()->isFunctionOrMethod())
524 // Types of valid local variables should be complete, so this should succeed.
525 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
526 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
527 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
528 if (!RD->hasTrivialConstructor())
530 if (!RD->hasTrivialDestructor())
539 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
540 if (S->decl_empty()) return;
541 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
542 "Scope shouldn't contain decls!");
544 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
546 Decl *TmpD = (*I).getAs<Decl>();
547 assert(TmpD && "This decl didn't get pushed??");
549 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
550 NamedDecl *D = cast<NamedDecl>(TmpD);
552 if (!D->getDeclName()) continue;
554 // Diagnose unused variables in this scope.
555 if (ShouldDiagnoseUnusedDecl(D))
556 Diag(D->getLocation(), diag::warn_unused_variable) << D->getDeclName();
558 // Remove this name from our lexical scope.
559 IdResolver.RemoveDecl(D);
563 /// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
564 /// return 0 if one not found.
566 /// \param Id the name of the Objective-C class we're looking for. If
567 /// typo-correction fixes this name, the Id will be updated
568 /// to the fixed name.
570 /// \param RecoverLoc if provided, this routine will attempt to
571 /// recover from a typo in the name of an existing Objective-C class
572 /// and, if successful, will return the lookup that results from
574 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
575 SourceLocation RecoverLoc) {
576 // The third "scope" argument is 0 since we aren't enabling lazy built-in
577 // creation from this context.
578 NamedDecl *IDecl = LookupSingleName(TUScope, Id, LookupOrdinaryName);
580 if (!IDecl && !RecoverLoc.isInvalid()) {
581 // Perform typo correction at the given location, but only if we
582 // find an Objective-C class name.
583 LookupResult R(*this, Id, RecoverLoc, LookupOrdinaryName);
584 if (CorrectTypo(R, TUScope, 0) &&
585 (IDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
586 Diag(RecoverLoc, diag::err_undef_interface_suggest)
587 << Id << IDecl->getDeclName()
588 << CodeModificationHint::CreateReplacement(RecoverLoc,
589 IDecl->getNameAsString());
590 Diag(IDecl->getLocation(), diag::note_previous_decl)
591 << IDecl->getDeclName();
593 Id = IDecl->getIdentifier();
597 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
600 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
601 /// from S, where a non-field would be declared. This routine copes
602 /// with the difference between C and C++ scoping rules in structs and
603 /// unions. For example, the following code is well-formed in C but
604 /// ill-formed in C++:
615 /// For the declaration of BAR, this routine will return a different
616 /// scope. The scope S will be the scope of the unnamed enumeration
617 /// within S6. In C++, this routine will return the scope associated
618 /// with S6, because the enumeration's scope is a transparent
619 /// context but structures can contain non-field names. In C, this
620 /// routine will return the translation unit scope, since the
621 /// enumeration's scope is a transparent context and structures cannot
622 /// contain non-field names.
623 Scope *Sema::getNonFieldDeclScope(Scope *S) {
624 while (((S->getFlags() & Scope::DeclScope) == 0) ||
626 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
627 (S->isClassScope() && !getLangOptions().CPlusPlus))
632 void Sema::InitBuiltinVaListType() {
633 if (!Context.getBuiltinVaListType().isNull())
636 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
637 NamedDecl *VaDecl = LookupSingleName(TUScope, VaIdent, LookupOrdinaryName);
638 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
639 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
642 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
643 /// file scope. lazily create a decl for it. ForRedeclaration is true
644 /// if we're creating this built-in in anticipation of redeclaring the
646 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
647 Scope *S, bool ForRedeclaration,
648 SourceLocation Loc) {
649 Builtin::ID BID = (Builtin::ID)bid;
651 if (Context.BuiltinInfo.hasVAListUse(BID))
652 InitBuiltinVaListType();
654 ASTContext::GetBuiltinTypeError Error;
655 QualType R = Context.GetBuiltinType(BID, Error);
657 case ASTContext::GE_None:
661 case ASTContext::GE_Missing_stdio:
662 if (ForRedeclaration)
663 Diag(Loc, diag::err_implicit_decl_requires_stdio)
664 << Context.BuiltinInfo.GetName(BID);
667 case ASTContext::GE_Missing_setjmp:
668 if (ForRedeclaration)
669 Diag(Loc, diag::err_implicit_decl_requires_setjmp)
670 << Context.BuiltinInfo.GetName(BID);
674 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
675 Diag(Loc, diag::ext_implicit_lib_function_decl)
676 << Context.BuiltinInfo.GetName(BID)
678 if (Context.BuiltinInfo.getHeaderName(BID) &&
679 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl)
680 != Diagnostic::Ignored)
681 Diag(Loc, diag::note_please_include_header)
682 << Context.BuiltinInfo.getHeaderName(BID)
683 << Context.BuiltinInfo.GetName(BID);
686 FunctionDecl *New = FunctionDecl::Create(Context,
687 Context.getTranslationUnitDecl(),
688 Loc, II, R, /*TInfo=*/0,
689 FunctionDecl::Extern, false,
690 /*hasPrototype=*/true);
693 // Create Decl objects for each parameter, adding them to the
695 if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
696 llvm::SmallVector<ParmVarDecl*, 16> Params;
697 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
698 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
699 FT->getArgType(i), /*TInfo=*/0,
701 New->setParams(Params.data(), Params.size());
704 AddKnownFunctionAttributes(New);
706 // TUScope is the translation-unit scope to insert this function into.
707 // FIXME: This is hideous. We need to teach PushOnScopeChains to
708 // relate Scopes to DeclContexts, and probably eliminate CurContext
709 // entirely, but we're not there yet.
710 DeclContext *SavedContext = CurContext;
711 CurContext = Context.getTranslationUnitDecl();
712 PushOnScopeChains(New, TUScope);
713 CurContext = SavedContext;
717 /// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
718 /// same name and scope as a previous declaration 'Old'. Figure out
719 /// how to resolve this situation, merging decls or emitting
720 /// diagnostics as appropriate. If there was an error, set New to be invalid.
722 void Sema::MergeTypeDefDecl(TypedefDecl *New, LookupResult &OldDecls) {
723 // If the new decl is known invalid already, don't bother doing any
725 if (New->isInvalidDecl()) return;
727 // Allow multiple definitions for ObjC built-in typedefs.
728 // FIXME: Verify the underlying types are equivalent!
729 if (getLangOptions().ObjC1) {
730 const IdentifierInfo *TypeID = New->getIdentifier();
731 switch (TypeID->getLength()) {
734 if (!TypeID->isStr("id"))
736 Context.ObjCIdRedefinitionType = New->getUnderlyingType();
737 // Install the built-in type for 'id', ignoring the current definition.
738 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
741 if (!TypeID->isStr("Class"))
743 Context.ObjCClassRedefinitionType = New->getUnderlyingType();
744 // Install the built-in type for 'Class', ignoring the current definition.
745 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
748 if (!TypeID->isStr("SEL"))
750 Context.ObjCSelRedefinitionType = New->getUnderlyingType();
751 // Install the built-in type for 'SEL', ignoring the current definition.
752 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
755 if (!TypeID->isStr("Protocol"))
757 Context.setObjCProtoType(New->getUnderlyingType());
760 // Fall through - the typedef name was not a builtin type.
763 // Verify the old decl was also a type.
764 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
766 Diag(New->getLocation(), diag::err_redefinition_different_kind)
767 << New->getDeclName();
769 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
770 if (OldD->getLocation().isValid())
771 Diag(OldD->getLocation(), diag::note_previous_definition);
773 return New->setInvalidDecl();
776 // If the old declaration is invalid, just give up here.
777 if (Old->isInvalidDecl())
778 return New->setInvalidDecl();
780 // Determine the "old" type we'll use for checking and diagnostics.
782 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
783 OldType = OldTypedef->getUnderlyingType();
785 OldType = Context.getTypeDeclType(Old);
787 // If the typedef types are not identical, reject them in all languages and
788 // with any extensions enabled.
790 if (OldType != New->getUnderlyingType() &&
791 Context.getCanonicalType(OldType) !=
792 Context.getCanonicalType(New->getUnderlyingType())) {
793 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
794 << New->getUnderlyingType() << OldType;
795 if (Old->getLocation().isValid())
796 Diag(Old->getLocation(), diag::note_previous_definition);
797 return New->setInvalidDecl();
800 // The types match. Link up the redeclaration chain if the old
801 // declaration was a typedef.
802 // FIXME: this is a potential source of wierdness if the type
803 // spellings don't match exactly.
804 if (isa<TypedefDecl>(Old))
805 New->setPreviousDeclaration(cast<TypedefDecl>(Old));
807 if (getLangOptions().Microsoft)
810 if (getLangOptions().CPlusPlus) {
811 // C++ [dcl.typedef]p2:
812 // In a given non-class scope, a typedef specifier can be used to
813 // redefine the name of any type declared in that scope to refer
814 // to the type to which it already refers.
815 if (!isa<CXXRecordDecl>(CurContext))
818 // C++0x [dcl.typedef]p4:
819 // In a given class scope, a typedef specifier can be used to redefine
820 // any class-name declared in that scope that is not also a typedef-name
821 // to refer to the type to which it already refers.
823 // This wording came in via DR424, which was a correction to the
824 // wording in DR56, which accidentally banned code like:
827 // typedef struct A { } A;
830 // in the C++03 standard. We implement the C++0x semantics, which
831 // allow the above but disallow
838 // since that was the intent of DR56.
839 if (!isa<TypedefDecl >(Old))
842 Diag(New->getLocation(), diag::err_redefinition)
843 << New->getDeclName();
844 Diag(Old->getLocation(), diag::note_previous_definition);
845 return New->setInvalidDecl();
848 // If we have a redefinition of a typedef in C, emit a warning. This warning
849 // is normally mapped to an error, but can be controlled with
850 // -Wtypedef-redefinition. If either the original or the redefinition is
851 // in a system header, don't emit this for compatibility with GCC.
852 if (PP.getDiagnostics().getSuppressSystemWarnings() &&
853 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
854 Context.getSourceManager().isInSystemHeader(New->getLocation())))
857 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
858 << New->getDeclName();
859 Diag(Old->getLocation(), diag::note_previous_definition);
863 /// DeclhasAttr - returns true if decl Declaration already has the target
866 DeclHasAttr(const Decl *decl, const Attr *target) {
867 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
868 if (attr->getKind() == target->getKind())
874 /// MergeAttributes - append attributes from the Old decl to the New one.
875 static void MergeAttributes(Decl *New, Decl *Old, ASTContext &C) {
876 for (const Attr *attr = Old->getAttrs(); attr; attr = attr->getNext()) {
877 if (!DeclHasAttr(New, attr) && attr->isMerged()) {
878 Attr *NewAttr = attr->clone(C);
879 NewAttr->setInherited(true);
880 New->addAttr(NewAttr);
885 /// Used in MergeFunctionDecl to keep track of function parameters in
887 struct GNUCompatibleParamWarning {
888 ParmVarDecl *OldParm;
889 ParmVarDecl *NewParm;
890 QualType PromotedType;
894 /// getSpecialMember - get the special member enum for a method.
895 static Sema::CXXSpecialMember getSpecialMember(ASTContext &Ctx,
896 const CXXMethodDecl *MD) {
897 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
898 if (Ctor->isDefaultConstructor())
899 return Sema::CXXDefaultConstructor;
900 if (Ctor->isCopyConstructor())
901 return Sema::CXXCopyConstructor;
904 if (isa<CXXDestructorDecl>(MD))
905 return Sema::CXXDestructor;
907 assert(MD->isCopyAssignment() && "Must have copy assignment operator");
908 return Sema::CXXCopyAssignment;
911 /// MergeFunctionDecl - We just parsed a function 'New' from
912 /// declarator D which has the same name and scope as a previous
913 /// declaration 'Old'. Figure out how to resolve this situation,
914 /// merging decls or emitting diagnostics as appropriate.
916 /// In C++, New and Old must be declarations that are not
917 /// overloaded. Use IsOverload to determine whether New and Old are
918 /// overloaded, and to select the Old declaration that New should be
921 /// Returns true if there was an error, false otherwise.
922 bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
923 // Verify the old decl was also a function.
924 FunctionDecl *Old = 0;
925 if (FunctionTemplateDecl *OldFunctionTemplate
926 = dyn_cast<FunctionTemplateDecl>(OldD))
927 Old = OldFunctionTemplate->getTemplatedDecl();
929 Old = dyn_cast<FunctionDecl>(OldD);
931 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
932 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
933 Diag(Shadow->getTargetDecl()->getLocation(),
934 diag::note_using_decl_target);
935 Diag(Shadow->getUsingDecl()->getLocation(),
936 diag::note_using_decl) << 0;
940 Diag(New->getLocation(), diag::err_redefinition_different_kind)
941 << New->getDeclName();
942 Diag(OldD->getLocation(), diag::note_previous_definition);
946 // Determine whether the previous declaration was a definition,
947 // implicit declaration, or a declaration.
949 if (Old->isThisDeclarationADefinition())
950 PrevDiag = diag::note_previous_definition;
951 else if (Old->isImplicit())
952 PrevDiag = diag::note_previous_implicit_declaration;
954 PrevDiag = diag::note_previous_declaration;
956 QualType OldQType = Context.getCanonicalType(Old->getType());
957 QualType NewQType = Context.getCanonicalType(New->getType());
959 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
960 New->getStorageClass() == FunctionDecl::Static &&
961 Old->getStorageClass() != FunctionDecl::Static) {
962 Diag(New->getLocation(), diag::err_static_non_static)
964 Diag(Old->getLocation(), PrevDiag);
968 // If a function is first declared with a calling convention, but is
969 // later declared or defined without one, the second decl assumes the
970 // calling convention of the first.
972 // For the new decl, we have to look at the NON-canonical type to tell the
973 // difference between a function that really doesn't have a calling
974 // convention and one that is declared cdecl. That's because in
975 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
976 // because it is the default calling convention.
978 // Note also that we DO NOT return at this point, because we still have
979 // other tests to run.
980 const FunctionType *OldType = OldQType->getAs<FunctionType>();
981 const FunctionType *NewType = New->getType()->getAs<FunctionType>();
982 if (OldType->getCallConv() != CC_Default &&
983 NewType->getCallConv() == CC_Default) {
984 NewQType = Context.getCallConvType(NewQType, OldType->getCallConv());
985 New->setType(NewQType);
986 NewQType = Context.getCanonicalType(NewQType);
987 } else if (!Context.isSameCallConv(OldType->getCallConv(),
988 NewType->getCallConv())) {
989 // Calling conventions really aren't compatible, so complain.
990 Diag(New->getLocation(), diag::err_cconv_change)
991 << FunctionType::getNameForCallConv(NewType->getCallConv())
992 << (OldType->getCallConv() == CC_Default)
993 << (OldType->getCallConv() == CC_Default ? "" :
994 FunctionType::getNameForCallConv(OldType->getCallConv()));
995 Diag(Old->getLocation(), diag::note_previous_declaration);
999 // FIXME: diagnose the other way around?
1000 if (OldType->getNoReturnAttr() && !NewType->getNoReturnAttr()) {
1001 NewQType = Context.getNoReturnType(NewQType);
1002 New->setType(NewQType);
1003 assert(NewQType.isCanonical());
1006 if (getLangOptions().CPlusPlus) {
1008 // Certain function declarations cannot be overloaded:
1009 // -- Function declarations that differ only in the return type
1010 // cannot be overloaded.
1011 QualType OldReturnType
1012 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
1013 QualType NewReturnType
1014 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
1015 if (OldReturnType != NewReturnType) {
1016 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
1017 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1021 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
1022 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
1023 if (OldMethod && NewMethod) {
1024 if (!NewMethod->getFriendObjectKind() &&
1025 NewMethod->getLexicalDeclContext()->isRecord()) {
1026 // -- Member function declarations with the same name and the
1027 // same parameter types cannot be overloaded if any of them
1028 // is a static member function declaration.
1029 if (OldMethod->isStatic() || NewMethod->isStatic()) {
1030 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
1031 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1035 // C++ [class.mem]p1:
1036 // [...] A member shall not be declared twice in the
1037 // member-specification, except that a nested class or member
1038 // class template can be declared and then later defined.
1040 if (isa<CXXConstructorDecl>(OldMethod))
1041 NewDiag = diag::err_constructor_redeclared;
1042 else if (isa<CXXDestructorDecl>(NewMethod))
1043 NewDiag = diag::err_destructor_redeclared;
1044 else if (isa<CXXConversionDecl>(NewMethod))
1045 NewDiag = diag::err_conv_function_redeclared;
1047 NewDiag = diag::err_member_redeclared;
1049 Diag(New->getLocation(), NewDiag);
1050 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1052 if (OldMethod->isImplicit()) {
1053 Diag(NewMethod->getLocation(),
1054 diag::err_definition_of_implicitly_declared_member)
1055 << New << getSpecialMember(Context, OldMethod);
1057 Diag(OldMethod->getLocation(),
1058 diag::note_previous_implicit_declaration);
1065 // All declarations for a function shall agree exactly in both the
1066 // return type and the parameter-type-list.
1067 // attributes should be ignored when comparing.
1068 if (Context.getNoReturnType(OldQType, false) ==
1069 Context.getNoReturnType(NewQType, false))
1070 return MergeCompatibleFunctionDecls(New, Old);
1072 // Fall through for conflicting redeclarations and redefinitions.
1075 // C: Function types need to be compatible, not identical. This handles
1076 // duplicate function decls like "void f(int); void f(enum X);" properly.
1077 if (!getLangOptions().CPlusPlus &&
1078 Context.typesAreCompatible(OldQType, NewQType)) {
1079 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
1080 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
1081 const FunctionProtoType *OldProto = 0;
1082 if (isa<FunctionNoProtoType>(NewFuncType) &&
1083 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
1084 // The old declaration provided a function prototype, but the
1085 // new declaration does not. Merge in the prototype.
1086 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
1087 llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
1088 OldProto->arg_type_end());
1089 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
1090 ParamTypes.data(), ParamTypes.size(),
1091 OldProto->isVariadic(),
1092 OldProto->getTypeQuals());
1093 New->setType(NewQType);
1094 New->setHasInheritedPrototype();
1096 // Synthesize a parameter for each argument type.
1097 llvm::SmallVector<ParmVarDecl*, 16> Params;
1098 for (FunctionProtoType::arg_type_iterator
1099 ParamType = OldProto->arg_type_begin(),
1100 ParamEnd = OldProto->arg_type_end();
1101 ParamType != ParamEnd; ++ParamType) {
1102 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
1103 SourceLocation(), 0,
1104 *ParamType, /*TInfo=*/0,
1106 Param->setImplicit();
1107 Params.push_back(Param);
1110 New->setParams(Params.data(), Params.size());
1113 return MergeCompatibleFunctionDecls(New, Old);
1116 // GNU C permits a K&R definition to follow a prototype declaration
1117 // if the declared types of the parameters in the K&R definition
1118 // match the types in the prototype declaration, even when the
1119 // promoted types of the parameters from the K&R definition differ
1120 // from the types in the prototype. GCC then keeps the types from
1123 // If a variadic prototype is followed by a non-variadic K&R definition,
1124 // the K&R definition becomes variadic. This is sort of an edge case, but
1125 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
1127 if (!getLangOptions().CPlusPlus &&
1128 Old->hasPrototype() && !New->hasPrototype() &&
1129 New->getType()->getAs<FunctionProtoType>() &&
1130 Old->getNumParams() == New->getNumParams()) {
1131 llvm::SmallVector<QualType, 16> ArgTypes;
1132 llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
1133 const FunctionProtoType *OldProto
1134 = Old->getType()->getAs<FunctionProtoType>();
1135 const FunctionProtoType *NewProto
1136 = New->getType()->getAs<FunctionProtoType>();
1138 // Determine whether this is the GNU C extension.
1139 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
1140 NewProto->getResultType());
1141 bool LooseCompatible = !MergedReturn.isNull();
1142 for (unsigned Idx = 0, End = Old->getNumParams();
1143 LooseCompatible && Idx != End; ++Idx) {
1144 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
1145 ParmVarDecl *NewParm = New->getParamDecl(Idx);
1146 if (Context.typesAreCompatible(OldParm->getType(),
1147 NewProto->getArgType(Idx))) {
1148 ArgTypes.push_back(NewParm->getType());
1149 } else if (Context.typesAreCompatible(OldParm->getType(),
1150 NewParm->getType())) {
1151 GNUCompatibleParamWarning Warn
1152 = { OldParm, NewParm, NewProto->getArgType(Idx) };
1153 Warnings.push_back(Warn);
1154 ArgTypes.push_back(NewParm->getType());
1156 LooseCompatible = false;
1159 if (LooseCompatible) {
1160 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
1161 Diag(Warnings[Warn].NewParm->getLocation(),
1162 diag::ext_param_promoted_not_compatible_with_prototype)
1163 << Warnings[Warn].PromotedType
1164 << Warnings[Warn].OldParm->getType();
1165 Diag(Warnings[Warn].OldParm->getLocation(),
1166 diag::note_previous_declaration);
1169 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
1171 OldProto->isVariadic(), 0));
1172 return MergeCompatibleFunctionDecls(New, Old);
1175 // Fall through to diagnose conflicting types.
1178 // A function that has already been declared has been redeclared or defined
1179 // with a different type- show appropriate diagnostic
1180 if (unsigned BuiltinID = Old->getBuiltinID()) {
1181 // The user has declared a builtin function with an incompatible
1183 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
1184 // The function the user is redeclaring is a library-defined
1185 // function like 'malloc' or 'printf'. Warn about the
1186 // redeclaration, then pretend that we don't know about this
1187 // library built-in.
1188 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
1189 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
1190 << Old << Old->getType();
1191 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
1192 Old->setInvalidDecl();
1196 PrevDiag = diag::note_previous_builtin_declaration;
1199 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
1200 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1204 /// \brief Completes the merge of two function declarations that are
1205 /// known to be compatible.
1207 /// This routine handles the merging of attributes and other
1208 /// properties of function declarations form the old declaration to
1209 /// the new declaration, once we know that New is in fact a
1210 /// redeclaration of Old.
1213 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
1214 // Merge the attributes
1215 MergeAttributes(New, Old, Context);
1217 // Merge the storage class.
1218 if (Old->getStorageClass() != FunctionDecl::Extern &&
1219 Old->getStorageClass() != FunctionDecl::None)
1220 New->setStorageClass(Old->getStorageClass());
1222 // Merge "pure" flag.
1226 // Merge the "deleted" flag.
1227 if (Old->isDeleted())
1230 if (getLangOptions().CPlusPlus)
1231 return MergeCXXFunctionDecl(New, Old);
1236 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
1237 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
1238 /// situation, merging decls or emitting diagnostics as appropriate.
1240 /// Tentative definition rules (C99 6.9.2p2) are checked by
1241 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
1242 /// definitions here, since the initializer hasn't been attached.
1244 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
1245 // If the new decl is already invalid, don't do any other checking.
1246 if (New->isInvalidDecl())
1249 // Verify the old decl was also a variable.
1251 if (!Previous.isSingleResult() ||
1252 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
1253 Diag(New->getLocation(), diag::err_redefinition_different_kind)
1254 << New->getDeclName();
1255 Diag(Previous.getRepresentativeDecl()->getLocation(),
1256 diag::note_previous_definition);
1257 return New->setInvalidDecl();
1260 MergeAttributes(New, Old, Context);
1264 if (getLangOptions().CPlusPlus) {
1265 if (Context.hasSameType(New->getType(), Old->getType()))
1266 MergedT = New->getType();
1267 // C++ [basic.link]p10:
1268 // [...] the types specified by all declarations referring to a given
1269 // object or function shall be identical, except that declarations for an
1270 // array object can specify array types that differ by the presence or
1271 // absence of a major array bound (8.3.4).
1272 else if (Old->getType()->isIncompleteArrayType() &&
1273 New->getType()->isArrayType()) {
1274 CanQual<ArrayType> OldArray
1275 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1276 CanQual<ArrayType> NewArray
1277 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1278 if (OldArray->getElementType() == NewArray->getElementType())
1279 MergedT = New->getType();
1280 } else if (Old->getType()->isArrayType() &&
1281 New->getType()->isIncompleteArrayType()) {
1282 CanQual<ArrayType> OldArray
1283 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1284 CanQual<ArrayType> NewArray
1285 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1286 if (OldArray->getElementType() == NewArray->getElementType())
1287 MergedT = Old->getType();
1290 MergedT = Context.mergeTypes(New->getType(), Old->getType());
1292 if (MergedT.isNull()) {
1293 Diag(New->getLocation(), diag::err_redefinition_different_type)
1294 << New->getDeclName();
1295 Diag(Old->getLocation(), diag::note_previous_definition);
1296 return New->setInvalidDecl();
1298 New->setType(MergedT);
1300 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
1301 if (New->getStorageClass() == VarDecl::Static &&
1302 (Old->getStorageClass() == VarDecl::None || Old->hasExternalStorage())) {
1303 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
1304 Diag(Old->getLocation(), diag::note_previous_definition);
1305 return New->setInvalidDecl();
1308 // For an identifier declared with the storage-class specifier
1309 // extern in a scope in which a prior declaration of that
1310 // identifier is visible,23) if the prior declaration specifies
1311 // internal or external linkage, the linkage of the identifier at
1312 // the later declaration is the same as the linkage specified at
1313 // the prior declaration. If no prior declaration is visible, or
1314 // if the prior declaration specifies no linkage, then the
1315 // identifier has external linkage.
1316 if (New->hasExternalStorage() && Old->hasLinkage())
1318 else if (New->getStorageClass() != VarDecl::Static &&
1319 Old->getStorageClass() == VarDecl::Static) {
1320 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
1321 Diag(Old->getLocation(), diag::note_previous_definition);
1322 return New->setInvalidDecl();
1325 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
1327 // FIXME: The test for external storage here seems wrong? We still
1328 // need to check for mismatches.
1329 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
1330 // Don't complain about out-of-line definitions of static members.
1331 !(Old->getLexicalDeclContext()->isRecord() &&
1332 !New->getLexicalDeclContext()->isRecord())) {
1333 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
1334 Diag(Old->getLocation(), diag::note_previous_definition);
1335 return New->setInvalidDecl();
1338 if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
1339 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
1340 Diag(Old->getLocation(), diag::note_previous_definition);
1341 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
1342 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
1343 Diag(Old->getLocation(), diag::note_previous_definition);
1346 // C++ doesn't have tentative definitions, so go right ahead and check here.
1348 if (getLangOptions().CPlusPlus &&
1349 New->isThisDeclarationADefinition() == VarDecl::Definition &&
1350 (Def = Old->getDefinition())) {
1351 Diag(New->getLocation(), diag::err_redefinition)
1352 << New->getDeclName();
1353 Diag(Def->getLocation(), diag::note_previous_definition);
1354 New->setInvalidDecl();
1358 // Keep a chain of previous declarations.
1359 New->setPreviousDeclaration(Old);
1361 // Inherit access appropriately.
1362 New->setAccess(Old->getAccess());
1365 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
1366 /// no declarator (e.g. "struct foo;") is parsed.
1367 Sema::DeclPtrTy Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
1368 // FIXME: Error on auto/register at file scope
1369 // FIXME: Error on inline/virtual/explicit
1370 // FIXME: Warn on useless __thread
1371 // FIXME: Warn on useless const/volatile
1372 // FIXME: Warn on useless static/extern/typedef/private_extern/mutable
1373 // FIXME: Warn on useless attributes
1376 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
1377 DS.getTypeSpecType() == DeclSpec::TST_struct ||
1378 DS.getTypeSpecType() == DeclSpec::TST_union ||
1379 DS.getTypeSpecType() == DeclSpec::TST_enum) {
1380 TagD = static_cast<Decl *>(DS.getTypeRep());
1382 if (!TagD) // We probably had an error
1385 // Note that the above type specs guarantee that the
1386 // type rep is a Decl, whereas in many of the others
1388 Tag = dyn_cast<TagDecl>(TagD);
1391 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1392 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
1393 // or incomplete types shall not be restrict-qualified."
1394 if (TypeQuals & DeclSpec::TQ_restrict)
1395 Diag(DS.getRestrictSpecLoc(),
1396 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
1397 << DS.getSourceRange();
1400 if (DS.isFriendSpecified()) {
1401 // If we're dealing with a class template decl, assume that the
1402 // template routines are handling it.
1403 if (TagD && isa<ClassTemplateDecl>(TagD))
1405 return ActOnFriendTypeDecl(S, DS, MultiTemplateParamsArg(*this, 0, 0));
1408 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
1409 // If there are attributes in the DeclSpec, apply them to the record.
1410 if (const AttributeList *AL = DS.getAttributes())
1411 ProcessDeclAttributeList(S, Record, AL);
1413 if (!Record->getDeclName() && Record->isDefinition() &&
1414 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
1415 if (getLangOptions().CPlusPlus ||
1416 Record->getDeclContext()->isRecord())
1417 return BuildAnonymousStructOrUnion(S, DS, Record);
1419 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
1420 << DS.getSourceRange();
1423 // Microsoft allows unnamed struct/union fields. Don't complain
1425 // FIXME: Should we support Microsoft's extensions in this area?
1426 if (Record->getDeclName() && getLangOptions().Microsoft)
1427 return DeclPtrTy::make(Tag);
1430 if (!DS.isMissingDeclaratorOk() &&
1431 DS.getTypeSpecType() != DeclSpec::TST_error) {
1432 // Warn about typedefs of enums without names, since this is an
1433 // extension in both Microsoft an GNU.
1434 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
1435 Tag && isa<EnumDecl>(Tag)) {
1436 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
1437 << DS.getSourceRange();
1438 return DeclPtrTy::make(Tag);
1441 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
1442 << DS.getSourceRange();
1446 return DeclPtrTy::make(Tag);
1449 /// We are trying to inject an anonymous member into the given scope;
1450 /// check if there's an existing declaration that can't be overloaded.
1452 /// \return true if this is a forbidden redeclaration
1453 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
1456 DeclarationName Name,
1457 SourceLocation NameLoc,
1458 unsigned diagnostic) {
1459 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
1460 Sema::ForRedeclaration);
1461 if (!SemaRef.LookupName(R, S)) return false;
1463 if (R.getAsSingle<TagDecl>())
1466 // Pick a representative declaration.
1467 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
1468 if (PrevDecl && Owner->isRecord()) {
1469 RecordDecl *Record = cast<RecordDecl>(Owner);
1470 if (!SemaRef.isDeclInScope(PrevDecl, Record, S))
1474 SemaRef.Diag(NameLoc, diagnostic) << Name;
1475 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
1480 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
1481 /// anonymous struct or union AnonRecord into the owning context Owner
1482 /// and scope S. This routine will be invoked just after we realize
1483 /// that an unnamed union or struct is actually an anonymous union or
1490 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
1491 /// // f into the surrounding scope.x
1494 /// This routine is recursive, injecting the names of nested anonymous
1495 /// structs/unions into the owning context and scope as well.
1496 bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
1497 RecordDecl *AnonRecord) {
1499 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
1500 : diag::err_anonymous_struct_member_redecl;
1502 bool Invalid = false;
1503 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
1504 FEnd = AnonRecord->field_end();
1506 if ((*F)->getDeclName()) {
1507 if (CheckAnonMemberRedeclaration(*this, S, Owner, (*F)->getDeclName(),
1508 (*F)->getLocation(), diagKind)) {
1509 // C++ [class.union]p2:
1510 // The names of the members of an anonymous union shall be
1511 // distinct from the names of any other entity in the
1512 // scope in which the anonymous union is declared.
1515 // C++ [class.union]p2:
1516 // For the purpose of name lookup, after the anonymous union
1517 // definition, the members of the anonymous union are
1518 // considered to have been defined in the scope in which the
1519 // anonymous union is declared.
1520 Owner->makeDeclVisibleInContext(*F);
1521 S->AddDecl(DeclPtrTy::make(*F));
1522 IdResolver.AddDecl(*F);
1524 } else if (const RecordType *InnerRecordType
1525 = (*F)->getType()->getAs<RecordType>()) {
1526 RecordDecl *InnerRecord = InnerRecordType->getDecl();
1527 if (InnerRecord->isAnonymousStructOrUnion())
1528 Invalid = Invalid ||
1529 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
1536 /// ActOnAnonymousStructOrUnion - Handle the declaration of an
1537 /// anonymous structure or union. Anonymous unions are a C++ feature
1538 /// (C++ [class.union]) and a GNU C extension; anonymous structures
1539 /// are a GNU C and GNU C++ extension.
1540 Sema::DeclPtrTy Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1541 RecordDecl *Record) {
1542 DeclContext *Owner = Record->getDeclContext();
1544 // Diagnose whether this anonymous struct/union is an extension.
1545 if (Record->isUnion() && !getLangOptions().CPlusPlus)
1546 Diag(Record->getLocation(), diag::ext_anonymous_union);
1547 else if (!Record->isUnion())
1548 Diag(Record->getLocation(), diag::ext_anonymous_struct);
1550 // C and C++ require different kinds of checks for anonymous
1552 bool Invalid = false;
1553 if (getLangOptions().CPlusPlus) {
1554 const char* PrevSpec = 0;
1556 // C++ [class.union]p3:
1557 // Anonymous unions declared in a named namespace or in the
1558 // global namespace shall be declared static.
1559 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
1560 (isa<TranslationUnitDecl>(Owner) ||
1561 (isa<NamespaceDecl>(Owner) &&
1562 cast<NamespaceDecl>(Owner)->getDeclName()))) {
1563 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
1566 // Recover by adding 'static'.
1567 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(),
1570 // C++ [class.union]p3:
1571 // A storage class is not allowed in a declaration of an
1572 // anonymous union in a class scope.
1573 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1574 isa<RecordDecl>(Owner)) {
1575 Diag(DS.getStorageClassSpecLoc(),
1576 diag::err_anonymous_union_with_storage_spec);
1579 // Recover by removing the storage specifier.
1580 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
1584 // C++ [class.union]p2:
1585 // The member-specification of an anonymous union shall only
1586 // define non-static data members. [Note: nested types and
1587 // functions cannot be declared within an anonymous union. ]
1588 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
1589 MemEnd = Record->decls_end();
1590 Mem != MemEnd; ++Mem) {
1591 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
1592 // C++ [class.union]p3:
1593 // An anonymous union shall not have private or protected
1594 // members (clause 11).
1595 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
1596 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
1597 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
1600 } else if ((*Mem)->isImplicit()) {
1601 // Any implicit members are fine.
1602 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
1603 // This is a type that showed up in an
1604 // elaborated-type-specifier inside the anonymous struct or
1605 // union, but which actually declares a type outside of the
1606 // anonymous struct or union. It's okay.
1607 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
1608 if (!MemRecord->isAnonymousStructOrUnion() &&
1609 MemRecord->getDeclName()) {
1610 // This is a nested type declaration.
1611 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
1612 << (int)Record->isUnion();
1616 // We have something that isn't a non-static data
1617 // member. Complain about it.
1618 unsigned DK = diag::err_anonymous_record_bad_member;
1619 if (isa<TypeDecl>(*Mem))
1620 DK = diag::err_anonymous_record_with_type;
1621 else if (isa<FunctionDecl>(*Mem))
1622 DK = diag::err_anonymous_record_with_function;
1623 else if (isa<VarDecl>(*Mem))
1624 DK = diag::err_anonymous_record_with_static;
1625 Diag((*Mem)->getLocation(), DK)
1626 << (int)Record->isUnion();
1632 if (!Record->isUnion() && !Owner->isRecord()) {
1633 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
1634 << (int)getLangOptions().CPlusPlus;
1638 // Mock up a declarator.
1639 Declarator Dc(DS, Declarator::TypeNameContext);
1640 TypeSourceInfo *TInfo = 0;
1641 GetTypeForDeclarator(Dc, S, &TInfo);
1642 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
1644 // Create a declaration for this anonymous struct/union.
1645 NamedDecl *Anon = 0;
1646 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
1647 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
1648 /*IdentifierInfo=*/0,
1649 Context.getTypeDeclType(Record),
1651 /*BitWidth=*/0, /*Mutable=*/false);
1652 Anon->setAccess(AS_public);
1653 if (getLangOptions().CPlusPlus)
1654 FieldCollector->Add(cast<FieldDecl>(Anon));
1656 VarDecl::StorageClass SC;
1657 switch (DS.getStorageClassSpec()) {
1658 default: assert(0 && "Unknown storage class!");
1659 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1660 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1661 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1662 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1663 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1664 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1665 case DeclSpec::SCS_mutable:
1666 // mutable can only appear on non-static class members, so it's always
1668 Diag(Record->getLocation(), diag::err_mutable_nonmember);
1674 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
1675 /*IdentifierInfo=*/0,
1676 Context.getTypeDeclType(Record),
1680 Anon->setImplicit();
1682 // Add the anonymous struct/union object to the current
1683 // context. We'll be referencing this object when we refer to one of
1685 Owner->addDecl(Anon);
1687 // Inject the members of the anonymous struct/union into the owning
1688 // context and into the identifier resolver chain for name lookup
1690 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
1693 // Mark this as an anonymous struct/union type. Note that we do not
1694 // do this until after we have already checked and injected the
1695 // members of this anonymous struct/union type, because otherwise
1696 // the members could be injected twice: once by DeclContext when it
1697 // builds its lookup table, and once by
1698 // InjectAnonymousStructOrUnionMembers.
1699 Record->setAnonymousStructOrUnion(true);
1702 Anon->setInvalidDecl();
1704 return DeclPtrTy::make(Anon);
1708 /// GetNameForDeclarator - Determine the full declaration name for the
1709 /// given Declarator.
1710 DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1711 return GetNameFromUnqualifiedId(D.getName());
1714 /// \brief Retrieves the canonicalized name from a parsed unqualified-id.
1715 DeclarationName Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
1716 switch (Name.getKind()) {
1717 case UnqualifiedId::IK_Identifier:
1718 return DeclarationName(Name.Identifier);
1720 case UnqualifiedId::IK_OperatorFunctionId:
1721 return Context.DeclarationNames.getCXXOperatorName(
1722 Name.OperatorFunctionId.Operator);
1724 case UnqualifiedId::IK_LiteralOperatorId:
1725 return Context.DeclarationNames.getCXXLiteralOperatorName(
1728 case UnqualifiedId::IK_ConversionFunctionId: {
1729 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId);
1731 return DeclarationName();
1733 return Context.DeclarationNames.getCXXConversionFunctionName(
1734 Context.getCanonicalType(Ty));
1737 case UnqualifiedId::IK_ConstructorName: {
1738 QualType Ty = GetTypeFromParser(Name.ConstructorName);
1740 return DeclarationName();
1742 return Context.DeclarationNames.getCXXConstructorName(
1743 Context.getCanonicalType(Ty));
1746 case UnqualifiedId::IK_ConstructorTemplateId: {
1747 // In well-formed code, we can only have a constructor
1748 // template-id that refers to the current context, so go there
1749 // to find the actual type being constructed.
1750 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
1751 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
1752 return DeclarationName();
1754 // Determine the type of the class being constructed.
1755 QualType CurClassType;
1756 if (ClassTemplateDecl *ClassTemplate
1757 = CurClass->getDescribedClassTemplate())
1758 CurClassType = ClassTemplate->getInjectedClassNameType(Context);
1760 CurClassType = Context.getTypeDeclType(CurClass);
1762 // FIXME: Check two things: that the template-id names the same type as
1763 // CurClassType, and that the template-id does not occur when the name
1766 return Context.DeclarationNames.getCXXConstructorName(
1767 Context.getCanonicalType(CurClassType));
1770 case UnqualifiedId::IK_DestructorName: {
1771 QualType Ty = GetTypeFromParser(Name.DestructorName);
1773 return DeclarationName();
1775 return Context.DeclarationNames.getCXXDestructorName(
1776 Context.getCanonicalType(Ty));
1779 case UnqualifiedId::IK_TemplateId: {
1781 = TemplateName::getFromVoidPointer(Name.TemplateId->Template);
1782 return Context.getNameForTemplate(TName);
1786 assert(false && "Unknown name kind");
1787 return DeclarationName();
1790 /// isNearlyMatchingFunction - Determine whether the C++ functions
1791 /// Declaration and Definition are "nearly" matching. This heuristic
1792 /// is used to improve diagnostics in the case where an out-of-line
1793 /// function definition doesn't match any declaration within
1794 /// the class or namespace.
1795 static bool isNearlyMatchingFunction(ASTContext &Context,
1796 FunctionDecl *Declaration,
1797 FunctionDecl *Definition) {
1798 if (Declaration->param_size() != Definition->param_size())
1800 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1801 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1802 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1804 if (!Context.hasSameUnqualifiedType(DeclParamTy.getNonReferenceType(),
1805 DefParamTy.getNonReferenceType()))
1813 Sema::HandleDeclarator(Scope *S, Declarator &D,
1814 MultiTemplateParamsArg TemplateParamLists,
1815 bool IsFunctionDefinition) {
1816 DeclarationName Name = GetNameForDeclarator(D);
1818 // All of these full declarators require an identifier. If it doesn't have
1819 // one, the ParsedFreeStandingDeclSpec action should be used.
1821 if (!D.isInvalidType()) // Reject this if we think it is valid.
1822 Diag(D.getDeclSpec().getSourceRange().getBegin(),
1823 diag::err_declarator_need_ident)
1824 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
1828 // The scope passed in may not be a decl scope. Zip up the scope tree until
1829 // we find one that is.
1830 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1831 (S->getFlags() & Scope::TemplateParamScope) != 0)
1834 // If this is an out-of-line definition of a member of a class template
1835 // or class template partial specialization, we may need to rebuild the
1836 // type specifier in the declarator. See RebuildTypeInCurrentInstantiation()
1837 // for more information.
1838 // FIXME: cope with decltype(expr) and typeof(expr) once the rebuilder can
1839 // handle expressions properly.
1840 DeclSpec &DS = const_cast<DeclSpec&>(D.getDeclSpec());
1841 if (D.getCXXScopeSpec().isSet() && !D.getCXXScopeSpec().isInvalid() &&
1842 isDependentScopeSpecifier(D.getCXXScopeSpec()) &&
1843 (DS.getTypeSpecType() == DeclSpec::TST_typename ||
1844 DS.getTypeSpecType() == DeclSpec::TST_typeofType ||
1845 DS.getTypeSpecType() == DeclSpec::TST_typeofExpr ||
1846 DS.getTypeSpecType() == DeclSpec::TST_decltype)) {
1847 if (DeclContext *DC = computeDeclContext(D.getCXXScopeSpec(), true)) {
1848 // FIXME: Preserve type source info.
1849 QualType T = GetTypeFromParser(DS.getTypeRep());
1851 DeclContext *SavedContext = CurContext;
1853 T = RebuildTypeInCurrentInstantiation(T, D.getIdentifierLoc(), Name);
1854 CurContext = SavedContext;
1858 DS.UpdateTypeRep(T.getAsOpaquePtr());
1865 TypeSourceInfo *TInfo = 0;
1866 QualType R = GetTypeForDeclarator(D, S, &TInfo);
1868 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
1871 // See if this is a redefinition of a variable in the same scope.
1872 if (D.getCXXScopeSpec().isInvalid()) {
1875 } else if (!D.getCXXScopeSpec().isSet()) {
1876 bool IsLinkageLookup = false;
1878 // If the declaration we're planning to build will be a function
1879 // or object with linkage, then look for another declaration with
1880 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
1881 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1883 else if (R->isFunctionType()) {
1884 if (CurContext->isFunctionOrMethod() ||
1885 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
1886 IsLinkageLookup = true;
1887 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
1888 IsLinkageLookup = true;
1889 else if (CurContext->getLookupContext()->isTranslationUnit() &&
1890 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
1891 IsLinkageLookup = true;
1893 if (IsLinkageLookup)
1894 Previous.clear(LookupRedeclarationWithLinkage);
1897 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
1898 } else { // Something like "int foo::x;"
1899 DC = computeDeclContext(D.getCXXScopeSpec(), true);
1902 // If we could not compute the declaration context, it's because the
1903 // declaration context is dependent but does not refer to a class,
1904 // class template, or class template partial specialization. Complain
1905 // and return early, to avoid the coming semantic disaster.
1906 Diag(D.getIdentifierLoc(),
1907 diag::err_template_qualified_declarator_no_match)
1908 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
1909 << D.getCXXScopeSpec().getRange();
1913 if (!DC->isDependentContext() &&
1914 RequireCompleteDeclContext(D.getCXXScopeSpec()))
1917 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
1918 Diag(D.getIdentifierLoc(),
1919 diag::err_member_def_undefined_record)
1920 << Name << DC << D.getCXXScopeSpec().getRange();
1924 LookupQualifiedName(Previous, DC);
1926 // Don't consider using declarations as previous declarations for
1927 // out-of-line members.
1928 RemoveUsingDecls(Previous);
1931 // Members (including explicit specializations of templates) of a named
1932 // namespace can also be defined outside that namespace by explicit
1933 // qualification of the name being defined, provided that the entity being
1934 // defined was already declared in the namespace and the definition appears
1935 // after the point of declaration in a namespace that encloses the
1936 // declarations namespace.
1938 // Note that we only check the context at this point. We don't yet
1939 // have enough information to make sure that PrevDecl is actually
1940 // the declaration we want to match. For example, given:
1947 // void X::f(int) { } // ill-formed
1949 // In this case, PrevDecl will point to the overload set
1950 // containing the two f's declared in X, but neither of them
1953 // First check whether we named the global scope.
1954 if (isa<TranslationUnitDecl>(DC)) {
1955 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
1956 << Name << D.getCXXScopeSpec().getRange();
1958 DeclContext *Cur = CurContext;
1959 while (isa<LinkageSpecDecl>(Cur))
1960 Cur = Cur->getParent();
1961 if (!Cur->Encloses(DC)) {
1962 // The qualifying scope doesn't enclose the original declaration.
1963 // Emit diagnostic based on current scope.
1964 SourceLocation L = D.getIdentifierLoc();
1965 SourceRange R = D.getCXXScopeSpec().getRange();
1966 if (isa<FunctionDecl>(Cur))
1967 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
1969 Diag(L, diag::err_invalid_declarator_scope)
1970 << Name << cast<NamedDecl>(DC) << R;
1976 if (Previous.isSingleResult() &&
1977 Previous.getFoundDecl()->isTemplateParameter()) {
1978 // Maybe we will complain about the shadowed template parameter.
1979 if (!D.isInvalidType())
1980 if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
1981 Previous.getFoundDecl()))
1984 // Just pretend that we didn't see the previous declaration.
1988 // In C++, the previous declaration we find might be a tag type
1989 // (class or enum). In this case, the new declaration will hide the
1990 // tag type. Note that this does does not apply if we're declaring a
1991 // typedef (C++ [dcl.typedef]p4).
1992 if (Previous.isSingleTagDecl() &&
1993 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
1996 bool Redeclaration = false;
1997 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
1998 if (TemplateParamLists.size()) {
1999 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
2003 New = ActOnTypedefDeclarator(S, D, DC, R, TInfo, Previous, Redeclaration);
2004 } else if (R->isFunctionType()) {
2005 New = ActOnFunctionDeclarator(S, D, DC, R, TInfo, Previous,
2006 move(TemplateParamLists),
2007 IsFunctionDefinition, Redeclaration);
2009 New = ActOnVariableDeclarator(S, D, DC, R, TInfo, Previous,
2010 move(TemplateParamLists),
2017 // If this has an identifier and is not an invalid redeclaration or
2018 // function template specialization, add it to the scope stack.
2019 if (Name && !(Redeclaration && New->isInvalidDecl()))
2020 PushOnScopeChains(New, S);
2022 return DeclPtrTy::make(New);
2025 /// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2026 /// types into constant array types in certain situations which would otherwise
2027 /// be errors (for GCC compatibility).
2028 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2029 ASTContext &Context,
2030 bool &SizeIsNegative) {
2031 // This method tries to turn a variable array into a constant
2032 // array even when the size isn't an ICE. This is necessary
2033 // for compatibility with code that depends on gcc's buggy
2034 // constant expression folding, like struct {char x[(int)(char*)2];}
2035 SizeIsNegative = false;
2037 QualifierCollector Qs;
2038 const Type *Ty = Qs.strip(T);
2040 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
2041 QualType Pointee = PTy->getPointeeType();
2042 QualType FixedType =
2043 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative);
2044 if (FixedType.isNull()) return FixedType;
2045 FixedType = Context.getPointerType(FixedType);
2046 return Qs.apply(FixedType);
2049 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2052 // FIXME: We should probably handle this case
2053 if (VLATy->getElementType()->isVariablyModifiedType())
2056 Expr::EvalResult EvalResult;
2057 if (!VLATy->getSizeExpr() ||
2058 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
2059 !EvalResult.Val.isInt())
2062 llvm::APSInt &Res = EvalResult.Val.getInt();
2063 if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) {
2064 // TODO: preserve the size expression in declarator info
2065 return Context.getConstantArrayType(VLATy->getElementType(),
2066 Res, ArrayType::Normal, 0);
2069 SizeIsNegative = true;
2073 /// \brief Register the given locally-scoped external C declaration so
2074 /// that it can be found later for redeclarations
2076 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
2077 const LookupResult &Previous,
2079 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
2080 "Decl is not a locally-scoped decl!");
2081 // Note that we have a locally-scoped external with this name.
2082 LocallyScopedExternalDecls[ND->getDeclName()] = ND;
2084 if (!Previous.isSingleResult())
2087 NamedDecl *PrevDecl = Previous.getFoundDecl();
2089 // If there was a previous declaration of this variable, it may be
2090 // in our identifier chain. Update the identifier chain with the new
2092 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
2093 // The previous declaration was found on the identifer resolver
2094 // chain, so remove it from its scope.
2095 while (S && !S->isDeclScope(DeclPtrTy::make(PrevDecl)))
2099 S->RemoveDecl(DeclPtrTy::make(PrevDecl));
2103 /// \brief Diagnose function specifiers on a declaration of an identifier that
2104 /// does not identify a function.
2105 void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
2106 // FIXME: We should probably indicate the identifier in question to avoid
2107 // confusion for constructs like "inline int a(), b;"
2108 if (D.getDeclSpec().isInlineSpecified())
2109 Diag(D.getDeclSpec().getInlineSpecLoc(),
2110 diag::err_inline_non_function);
2112 if (D.getDeclSpec().isVirtualSpecified())
2113 Diag(D.getDeclSpec().getVirtualSpecLoc(),
2114 diag::err_virtual_non_function);
2116 if (D.getDeclSpec().isExplicitSpecified())
2117 Diag(D.getDeclSpec().getExplicitSpecLoc(),
2118 diag::err_explicit_non_function);
2122 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2123 QualType R, TypeSourceInfo *TInfo,
2124 LookupResult &Previous, bool &Redeclaration) {
2125 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
2126 if (D.getCXXScopeSpec().isSet()) {
2127 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
2128 << D.getCXXScopeSpec().getRange();
2130 // Pretend we didn't see the scope specifier.
2134 if (getLangOptions().CPlusPlus) {
2135 // Check that there are no default arguments (C++ only).
2136 CheckExtraCXXDefaultArguments(D);
2139 DiagnoseFunctionSpecifiers(D);
2141 if (D.getDeclSpec().isThreadSpecified())
2142 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2144 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, TInfo);
2145 if (!NewTD) return 0;
2147 // Handle attributes prior to checking for duplicates in MergeVarDecl
2148 ProcessDeclAttributes(S, NewTD, D);
2150 // Merge the decl with the existing one if appropriate. If the decl is
2151 // in an outer scope, it isn't the same thing.
2152 FilterLookupForScope(*this, Previous, DC, S, /*ConsiderLinkage*/ false);
2153 if (!Previous.empty()) {
2154 Redeclaration = true;
2155 MergeTypeDefDecl(NewTD, Previous);
2158 // C99 6.7.7p2: If a typedef name specifies a variably modified type
2159 // then it shall have block scope.
2160 QualType T = NewTD->getUnderlyingType();
2161 if (T->isVariablyModifiedType()) {
2162 CurFunctionNeedsScopeChecking = true;
2164 if (S->getFnParent() == 0) {
2165 bool SizeIsNegative;
2167 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
2168 if (!FixedTy.isNull()) {
2169 Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size);
2170 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
2173 Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size);
2174 else if (T->isVariableArrayType())
2175 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
2177 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
2178 NewTD->setInvalidDecl();
2183 // If this is the C FILE type, notify the AST context.
2184 if (IdentifierInfo *II = NewTD->getIdentifier())
2185 if (!NewTD->isInvalidDecl() &&
2186 NewTD->getDeclContext()->getLookupContext()->isTranslationUnit()) {
2187 if (II->isStr("FILE"))
2188 Context.setFILEDecl(NewTD);
2189 else if (II->isStr("jmp_buf"))
2190 Context.setjmp_bufDecl(NewTD);
2191 else if (II->isStr("sigjmp_buf"))
2192 Context.setsigjmp_bufDecl(NewTD);
2198 /// \brief Determines whether the given declaration is an out-of-scope
2199 /// previous declaration.
2201 /// This routine should be invoked when name lookup has found a
2202 /// previous declaration (PrevDecl) that is not in the scope where a
2203 /// new declaration by the same name is being introduced. If the new
2204 /// declaration occurs in a local scope, previous declarations with
2205 /// linkage may still be considered previous declarations (C99
2206 /// 6.2.2p4-5, C++ [basic.link]p6).
2208 /// \param PrevDecl the previous declaration found by name
2211 /// \param DC the context in which the new declaration is being
2214 /// \returns true if PrevDecl is an out-of-scope previous declaration
2215 /// for a new delcaration with the same name.
2217 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
2218 ASTContext &Context) {
2222 if (!PrevDecl->hasLinkage())
2225 if (Context.getLangOptions().CPlusPlus) {
2226 // C++ [basic.link]p6:
2227 // If there is a visible declaration of an entity with linkage
2228 // having the same name and type, ignoring entities declared
2229 // outside the innermost enclosing namespace scope, the block
2230 // scope declaration declares that same entity and receives the
2231 // linkage of the previous declaration.
2232 DeclContext *OuterContext = DC->getLookupContext();
2233 if (!OuterContext->isFunctionOrMethod())
2234 // This rule only applies to block-scope declarations.
2237 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
2238 if (PrevOuterContext->isRecord())
2239 // We found a member function: ignore it.
2242 // Find the innermost enclosing namespace for the new and
2243 // previous declarations.
2244 while (!OuterContext->isFileContext())
2245 OuterContext = OuterContext->getParent();
2246 while (!PrevOuterContext->isFileContext())
2247 PrevOuterContext = PrevOuterContext->getParent();
2249 // The previous declaration is in a different namespace, so it
2250 // isn't the same function.
2251 if (OuterContext->getPrimaryContext() !=
2252 PrevOuterContext->getPrimaryContext())
2262 Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2263 QualType R, TypeSourceInfo *TInfo,
2264 LookupResult &Previous,
2265 MultiTemplateParamsArg TemplateParamLists,
2266 bool &Redeclaration) {
2267 DeclarationName Name = GetNameForDeclarator(D);
2269 // Check that there are no default arguments (C++ only).
2270 if (getLangOptions().CPlusPlus)
2271 CheckExtraCXXDefaultArguments(D);
2274 VarDecl::StorageClass SC;
2275 switch (D.getDeclSpec().getStorageClassSpec()) {
2276 default: assert(0 && "Unknown storage class!");
2277 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
2278 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
2279 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
2280 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
2281 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
2282 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
2283 case DeclSpec::SCS_mutable:
2284 // mutable can only appear on non-static class members, so it's always
2286 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
2292 IdentifierInfo *II = Name.getAsIdentifierInfo();
2294 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
2295 << Name.getAsString();
2299 DiagnoseFunctionSpecifiers(D);
2301 if (!DC->isRecord() && S->getFnParent() == 0) {
2302 // C99 6.9p2: The storage-class specifiers auto and register shall not
2303 // appear in the declaration specifiers in an external declaration.
2304 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
2306 // If this is a register variable with an asm label specified, then this
2307 // is a GNU extension.
2308 if (SC == VarDecl::Register && D.getAsmLabel())
2309 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
2311 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
2315 if (DC->isRecord() && !CurContext->isRecord()) {
2316 // This is an out-of-line definition of a static data member.
2317 if (SC == VarDecl::Static) {
2318 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2319 diag::err_static_out_of_line)
2320 << CodeModificationHint::CreateRemoval(
2321 D.getDeclSpec().getStorageClassSpecLoc());
2322 } else if (SC == VarDecl::None)
2323 SC = VarDecl::Static;
2325 if (SC == VarDecl::Static) {
2326 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
2327 if (RD->isLocalClass())
2328 Diag(D.getIdentifierLoc(),
2329 diag::err_static_data_member_not_allowed_in_local_class)
2330 << Name << RD->getDeclName();
2334 // Match up the template parameter lists with the scope specifier, then
2335 // determine whether we have a template or a template specialization.
2336 bool isExplicitSpecialization = false;
2337 if (TemplateParameterList *TemplateParams
2338 = MatchTemplateParametersToScopeSpecifier(
2339 D.getDeclSpec().getSourceRange().getBegin(),
2340 D.getCXXScopeSpec(),
2341 (TemplateParameterList**)TemplateParamLists.get(),
2342 TemplateParamLists.size(),
2343 isExplicitSpecialization)) {
2344 if (TemplateParams->size() > 0) {
2345 // There is no such thing as a variable template.
2346 Diag(D.getIdentifierLoc(), diag::err_template_variable)
2348 << SourceRange(TemplateParams->getTemplateLoc(),
2349 TemplateParams->getRAngleLoc());
2352 // There is an extraneous 'template<>' for this variable. Complain
2353 // about it, but allow the declaration of the variable.
2354 Diag(TemplateParams->getTemplateLoc(),
2355 diag::err_template_variable_noparams)
2357 << SourceRange(TemplateParams->getTemplateLoc(),
2358 TemplateParams->getRAngleLoc());
2360 isExplicitSpecialization = true;
2364 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
2367 if (D.isInvalidType())
2368 NewVD->setInvalidDecl();
2370 if (D.getDeclSpec().isThreadSpecified()) {
2371 if (NewVD->hasLocalStorage())
2372 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
2373 else if (!Context.Target.isTLSSupported())
2374 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
2376 NewVD->setThreadSpecified(true);
2379 // Set the lexical context. If the declarator has a C++ scope specifier, the
2380 // lexical context will be different from the semantic context.
2381 NewVD->setLexicalDeclContext(CurContext);
2383 // Handle attributes prior to checking for duplicates in MergeVarDecl
2384 ProcessDeclAttributes(S, NewVD, D);
2386 // Handle GNU asm-label extension (encoded as an attribute).
2387 if (Expr *E = (Expr*) D.getAsmLabel()) {
2388 // The parser guarantees this is a string.
2389 StringLiteral *SE = cast<StringLiteral>(E);
2390 NewVD->addAttr(::new (Context) AsmLabelAttr(Context, SE->getString()));
2393 // Don't consider existing declarations that are in a different
2394 // scope and are out-of-semantic-context declarations (if the new
2395 // declaration has linkage).
2396 FilterLookupForScope(*this, Previous, DC, S, NewVD->hasLinkage());
2398 // Merge the decl with the existing one if appropriate.
2399 if (!Previous.empty()) {
2400 if (Previous.isSingleResult() &&
2401 isa<FieldDecl>(Previous.getFoundDecl()) &&
2402 D.getCXXScopeSpec().isSet()) {
2403 // The user tried to define a non-static data member
2404 // out-of-line (C++ [dcl.meaning]p1).
2405 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
2406 << D.getCXXScopeSpec().getRange();
2408 NewVD->setInvalidDecl();
2410 } else if (D.getCXXScopeSpec().isSet()) {
2411 // No previous declaration in the qualifying scope.
2412 Diag(D.getIdentifierLoc(), diag::err_no_member)
2413 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
2414 << D.getCXXScopeSpec().getRange();
2415 NewVD->setInvalidDecl();
2418 CheckVariableDeclaration(NewVD, Previous, Redeclaration);
2420 // This is an explicit specialization of a static data member. Check it.
2421 if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
2422 CheckMemberSpecialization(NewVD, Previous))
2423 NewVD->setInvalidDecl();
2425 // attributes declared post-definition are currently ignored
2426 if (Previous.isSingleResult()) {
2427 VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl());
2428 if (Def && (Def = Def->getDefinition()) &&
2429 Def != NewVD && D.hasAttributes()) {
2430 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
2431 Diag(Def->getLocation(), diag::note_previous_definition);
2435 // If this is a locally-scoped extern C variable, update the map of
2437 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
2438 !NewVD->isInvalidDecl())
2439 RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
2444 /// \brief Perform semantic checking on a newly-created variable
2447 /// This routine performs all of the type-checking required for a
2448 /// variable declaration once it has been built. It is used both to
2449 /// check variables after they have been parsed and their declarators
2450 /// have been translated into a declaration, and to check variables
2451 /// that have been instantiated from a template.
2453 /// Sets NewVD->isInvalidDecl() if an error was encountered.
2454 void Sema::CheckVariableDeclaration(VarDecl *NewVD,
2455 LookupResult &Previous,
2456 bool &Redeclaration) {
2457 // If the decl is already known invalid, don't check it.
2458 if (NewVD->isInvalidDecl())
2461 QualType T = NewVD->getType();
2463 if (T->isObjCInterfaceType()) {
2464 Diag(NewVD->getLocation(), diag::err_statically_allocated_object);
2465 return NewVD->setInvalidDecl();
2468 // Emit an error if an address space was applied to decl with local storage.
2469 // This includes arrays of objects with address space qualifiers, but not
2470 // automatic variables that point to other address spaces.
2471 // ISO/IEC TR 18037 S5.1.2
2472 if (NewVD->hasLocalStorage() && (T.getAddressSpace() != 0)) {
2473 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
2474 return NewVD->setInvalidDecl();
2477 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
2478 && !NewVD->hasAttr<BlocksAttr>())
2479 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
2481 bool isVM = T->isVariablyModifiedType();
2482 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
2483 NewVD->hasAttr<BlocksAttr>())
2484 CurFunctionNeedsScopeChecking = true;
2486 if ((isVM && NewVD->hasLinkage()) ||
2487 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
2488 bool SizeIsNegative;
2490 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
2492 if (FixedTy.isNull() && T->isVariableArrayType()) {
2493 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
2494 // FIXME: This won't give the correct result for
2496 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
2498 if (NewVD->isFileVarDecl())
2499 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
2501 else if (NewVD->getStorageClass() == VarDecl::Static)
2502 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
2505 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
2507 return NewVD->setInvalidDecl();
2510 if (FixedTy.isNull()) {
2511 if (NewVD->isFileVarDecl())
2512 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
2514 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
2515 return NewVD->setInvalidDecl();
2518 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
2519 NewVD->setType(FixedTy);
2522 if (Previous.empty() && NewVD->isExternC()) {
2523 // Since we did not find anything by this name and we're declaring
2524 // an extern "C" variable, look for a non-visible extern "C"
2525 // declaration with the same name.
2526 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
2527 = LocallyScopedExternalDecls.find(NewVD->getDeclName());
2528 if (Pos != LocallyScopedExternalDecls.end())
2529 Previous.addDecl(Pos->second);
2532 if (T->isVoidType() && !NewVD->hasExternalStorage()) {
2533 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
2535 return NewVD->setInvalidDecl();
2538 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
2539 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
2540 return NewVD->setInvalidDecl();
2543 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
2544 Diag(NewVD->getLocation(), diag::err_block_on_vm);
2545 return NewVD->setInvalidDecl();
2548 if (!Previous.empty()) {
2549 Redeclaration = true;
2550 MergeVarDecl(NewVD, Previous);
2554 /// \brief Data used with FindOverriddenMethod
2555 struct FindOverriddenMethodData {
2557 CXXMethodDecl *Method;
2560 /// \brief Member lookup function that determines whether a given C++
2561 /// method overrides a method in a base class, to be used with
2562 /// CXXRecordDecl::lookupInBases().
2563 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
2566 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
2568 FindOverriddenMethodData *Data
2569 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
2571 DeclarationName Name = Data->Method->getDeclName();
2573 // FIXME: Do we care about other names here too?
2574 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
2575 // We really want to find the base class constructor here.
2576 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
2577 CanQualType CT = Data->S->Context.getCanonicalType(T);
2579 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
2582 for (Path.Decls = BaseRecord->lookup(Name);
2583 Path.Decls.first != Path.Decls.second;
2584 ++Path.Decls.first) {
2585 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*Path.Decls.first)) {
2586 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD))
2594 /// AddOverriddenMethods - See if a method overrides any in the base classes,
2595 /// and if so, check that it's a valid override and remember it.
2596 void Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2597 // Look for virtual methods in base classes that this method might override.
2599 FindOverriddenMethodData Data;
2602 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
2603 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
2604 E = Paths.found_decls_end(); I != E; ++I) {
2605 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
2606 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
2607 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
2608 !CheckOverridingFunctionAttributes(MD, OldMD))
2609 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
2616 Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2617 QualType R, TypeSourceInfo *TInfo,
2618 LookupResult &Previous,
2619 MultiTemplateParamsArg TemplateParamLists,
2620 bool IsFunctionDefinition, bool &Redeclaration) {
2621 assert(R.getTypePtr()->isFunctionType());
2623 DeclarationName Name = GetNameForDeclarator(D);
2624 FunctionDecl::StorageClass SC = FunctionDecl::None;
2625 switch (D.getDeclSpec().getStorageClassSpec()) {
2626 default: assert(0 && "Unknown storage class!");
2627 case DeclSpec::SCS_auto:
2628 case DeclSpec::SCS_register:
2629 case DeclSpec::SCS_mutable:
2630 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2631 diag::err_typecheck_sclass_func);
2634 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
2635 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
2636 case DeclSpec::SCS_static: {
2637 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
2639 // The declaration of an identifier for a function that has
2640 // block scope shall have no explicit storage-class specifier
2641 // other than extern
2642 // See also (C++ [dcl.stc]p4).
2643 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2644 diag::err_static_block_func);
2645 SC = FunctionDecl::None;
2647 SC = FunctionDecl::Static;
2650 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
2653 if (D.getDeclSpec().isThreadSpecified())
2654 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2656 bool isFriend = D.getDeclSpec().isFriendSpecified();
2657 bool isInline = D.getDeclSpec().isInlineSpecified();
2658 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
2659 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
2661 // Check that the return type is not an abstract class type.
2662 // For record types, this is done by the AbstractClassUsageDiagnoser once
2663 // the class has been completely parsed.
2664 if (!DC->isRecord() &&
2665 RequireNonAbstractType(D.getIdentifierLoc(),
2666 R->getAs<FunctionType>()->getResultType(),
2667 diag::err_abstract_type_in_decl,
2668 AbstractReturnType))
2671 // Do not allow returning a objc interface by-value.
2672 if (R->getAs<FunctionType>()->getResultType()->isObjCInterfaceType()) {
2673 Diag(D.getIdentifierLoc(),
2674 diag::err_object_cannot_be_passed_returned_by_value) << 0
2675 << R->getAs<FunctionType>()->getResultType();
2679 bool isVirtualOkay = false;
2680 FunctionDecl *NewFD;
2683 // C++ [class.friend]p5
2684 // A function can be defined in a friend declaration of a
2685 // class . . . . Such a function is implicitly inline.
2686 isInline |= IsFunctionDefinition;
2689 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
2690 // This is a C++ constructor declaration.
2691 assert(DC->isRecord() &&
2692 "Constructors can only be declared in a member context");
2694 R = CheckConstructorDeclarator(D, R, SC);
2696 // Create the new declaration
2697 NewFD = CXXConstructorDecl::Create(Context,
2698 cast<CXXRecordDecl>(DC),
2699 D.getIdentifierLoc(), Name, R, TInfo,
2700 isExplicit, isInline,
2701 /*isImplicitlyDeclared=*/false);
2702 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
2703 // This is a C++ destructor declaration.
2704 if (DC->isRecord()) {
2705 R = CheckDestructorDeclarator(D, SC);
2707 NewFD = CXXDestructorDecl::Create(Context,
2708 cast<CXXRecordDecl>(DC),
2709 D.getIdentifierLoc(), Name, R,
2711 /*isImplicitlyDeclared=*/false);
2713 isVirtualOkay = true;
2715 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
2717 // Create a FunctionDecl to satisfy the function definition parsing
2719 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
2720 Name, R, TInfo, SC, isInline,
2721 /*hasPrototype=*/true);
2724 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2725 if (!DC->isRecord()) {
2726 Diag(D.getIdentifierLoc(),
2727 diag::err_conv_function_not_member);
2731 CheckConversionDeclarator(D, R, SC);
2732 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
2733 D.getIdentifierLoc(), Name, R, TInfo,
2734 isInline, isExplicit);
2736 isVirtualOkay = true;
2737 } else if (DC->isRecord()) {
2738 // If the of the function is the same as the name of the record, then this
2739 // must be an invalid constructor that has a return type.
2740 // (The parser checks for a return type and makes the declarator a
2741 // constructor if it has no return type).
2742 // must have an invalid constructor that has a return type
2743 if (Name.getAsIdentifierInfo() &&
2744 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
2745 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
2746 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2747 << SourceRange(D.getIdentifierLoc());
2751 bool isStatic = SC == FunctionDecl::Static;
2754 // Any allocation function for a class T is a static member
2755 // (even if not explicitly declared static).
2756 if (Name.getCXXOverloadedOperator() == OO_New ||
2757 Name.getCXXOverloadedOperator() == OO_Array_New)
2760 // [class.free]p6 Any deallocation function for a class X is a static member
2761 // (even if not explicitly declared static).
2762 if (Name.getCXXOverloadedOperator() == OO_Delete ||
2763 Name.getCXXOverloadedOperator() == OO_Array_Delete)
2766 // This is a C++ method declaration.
2767 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
2768 D.getIdentifierLoc(), Name, R, TInfo,
2769 isStatic, isInline);
2771 isVirtualOkay = !isStatic;
2773 // Determine whether the function was written with a
2774 // prototype. This true when:
2775 // - we're in C++ (where every function has a prototype),
2776 // - there is a prototype in the declarator, or
2777 // - the type R of the function is some kind of typedef or other reference
2778 // to a type name (which eventually refers to a function type).
2780 getLangOptions().CPlusPlus ||
2781 (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) ||
2782 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
2784 NewFD = FunctionDecl::Create(Context, DC,
2785 D.getIdentifierLoc(),
2786 Name, R, TInfo, SC, isInline, HasPrototype);
2789 if (D.isInvalidType())
2790 NewFD->setInvalidDecl();
2792 // Set the lexical context. If the declarator has a C++
2793 // scope specifier, or is the object of a friend declaration, the
2794 // lexical context will be different from the semantic context.
2795 NewFD->setLexicalDeclContext(CurContext);
2797 // Match up the template parameter lists with the scope specifier, then
2798 // determine whether we have a template or a template specialization.
2799 FunctionTemplateDecl *FunctionTemplate = 0;
2800 bool isExplicitSpecialization = false;
2801 bool isFunctionTemplateSpecialization = false;
2802 if (TemplateParameterList *TemplateParams
2803 = MatchTemplateParametersToScopeSpecifier(
2804 D.getDeclSpec().getSourceRange().getBegin(),
2805 D.getCXXScopeSpec(),
2806 (TemplateParameterList**)TemplateParamLists.get(),
2807 TemplateParamLists.size(),
2808 isExplicitSpecialization)) {
2809 if (TemplateParams->size() > 0) {
2810 // This is a function template
2812 // Check that we can declare a template here.
2813 if (CheckTemplateDeclScope(S, TemplateParams))
2816 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
2817 NewFD->getLocation(),
2818 Name, TemplateParams,
2820 FunctionTemplate->setLexicalDeclContext(CurContext);
2821 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
2823 // This is a function template specialization.
2824 isFunctionTemplateSpecialization = true;
2827 // FIXME: Free this memory properly.
2828 TemplateParamLists.release();
2831 // C++ [dcl.fct.spec]p5:
2832 // The virtual specifier shall only be used in declarations of
2833 // nonstatic class member functions that appear within a
2834 // member-specification of a class declaration; see 10.3.
2836 if (isVirtual && !NewFD->isInvalidDecl()) {
2837 if (!isVirtualOkay) {
2838 Diag(D.getDeclSpec().getVirtualSpecLoc(),
2839 diag::err_virtual_non_function);
2840 } else if (!CurContext->isRecord()) {
2841 // 'virtual' was specified outside of the class.
2842 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class)
2843 << CodeModificationHint::CreateRemoval(
2844 D.getDeclSpec().getVirtualSpecLoc());
2846 // Okay: Add virtual to the method.
2847 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC);
2848 CurClass->setMethodAsVirtual(NewFD);
2852 // C++ [dcl.fct.spec]p6:
2853 // The explicit specifier shall be used only in the declaration of a
2854 // constructor or conversion function within its class definition; see 12.3.1
2856 if (isExplicit && !NewFD->isInvalidDecl()) {
2857 if (!CurContext->isRecord()) {
2858 // 'explicit' was specified outside of the class.
2859 Diag(D.getDeclSpec().getExplicitSpecLoc(),
2860 diag::err_explicit_out_of_class)
2861 << CodeModificationHint::CreateRemoval(
2862 D.getDeclSpec().getExplicitSpecLoc());
2863 } else if (!isa<CXXConstructorDecl>(NewFD) &&
2864 !isa<CXXConversionDecl>(NewFD)) {
2865 // 'explicit' was specified on a function that wasn't a constructor
2866 // or conversion function.
2867 Diag(D.getDeclSpec().getExplicitSpecLoc(),
2868 diag::err_explicit_non_ctor_or_conv_function)
2869 << CodeModificationHint::CreateRemoval(
2870 D.getDeclSpec().getExplicitSpecLoc());
2874 // Filter out previous declarations that don't match the scope.
2875 FilterLookupForScope(*this, Previous, DC, S, NewFD->hasLinkage());
2878 // DC is the namespace in which the function is being declared.
2879 assert((DC->isFileContext() || !Previous.empty()) &&
2880 "previously-undeclared friend function being created "
2881 "in a non-namespace context");
2883 if (FunctionTemplate) {
2884 FunctionTemplate->setObjectOfFriendDecl(
2885 /* PreviouslyDeclared= */ !Previous.empty());
2886 FunctionTemplate->setAccess(AS_public);
2889 NewFD->setObjectOfFriendDecl(/* PreviouslyDeclared= */ !Previous.empty());
2891 NewFD->setAccess(AS_public);
2894 if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) &&
2895 !CurContext->isRecord()) {
2896 // C++ [class.static]p1:
2897 // A data or function member of a class may be declared static
2898 // in a class definition, in which case it is a static member of
2901 // Complain about the 'static' specifier if it's on an out-of-line
2902 // member function definition.
2903 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2904 diag::err_static_out_of_line)
2905 << CodeModificationHint::CreateRemoval(
2906 D.getDeclSpec().getStorageClassSpecLoc());
2909 // Handle GNU asm-label extension (encoded as an attribute).
2910 if (Expr *E = (Expr*) D.getAsmLabel()) {
2911 // The parser guarantees this is a string.
2912 StringLiteral *SE = cast<StringLiteral>(E);
2913 NewFD->addAttr(::new (Context) AsmLabelAttr(Context, SE->getString()));
2916 // Copy the parameter declarations from the declarator D to the function
2917 // declaration NewFD, if they are available. First scavenge them into Params.
2918 llvm::SmallVector<ParmVarDecl*, 16> Params;
2919 if (D.getNumTypeObjects() > 0) {
2920 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2922 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
2923 // function that takes no arguments, not a function that takes a
2924 // single void argument.
2925 // We let through "const void" here because Sema::GetTypeForDeclarator
2926 // already checks for that case.
2927 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2928 FTI.ArgInfo[0].Param &&
2929 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()) {
2930 // Empty arg list, don't push any params.
2931 ParmVarDecl *Param = FTI.ArgInfo[0].Param.getAs<ParmVarDecl>();
2933 // In C++, the empty parameter-type-list must be spelled "void"; a
2934 // typedef of void is not permitted.
2935 if (getLangOptions().CPlusPlus &&
2936 Param->getType().getUnqualifiedType() != Context.VoidTy)
2937 Diag(Param->getLocation(), diag::err_param_typedef_of_void);
2938 // FIXME: Leaks decl?
2939 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
2940 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
2941 ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
2942 assert(Param->getDeclContext() != NewFD && "Was set before ?");
2943 Param->setDeclContext(NewFD);
2944 Params.push_back(Param);
2948 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
2949 // When we're declaring a function with a typedef, typeof, etc as in the
2950 // following example, we'll need to synthesize (unnamed)
2951 // parameters for use in the declaration.
2954 // typedef void fn(int);
2958 // Synthesize a parameter for each argument type.
2959 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
2960 AE = FT->arg_type_end(); AI != AE; ++AI) {
2961 ParmVarDecl *Param = ParmVarDecl::Create(Context, NewFD,
2962 SourceLocation(), 0,
2965 Param->setImplicit();
2966 Params.push_back(Param);
2969 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
2970 "Should not need args for typedef of non-prototype fn");
2972 // Finally, we know we have the right number of parameters, install them.
2973 NewFD->setParams(Params.data(), Params.size());
2975 // If the declarator is a template-id, translate the parser's template
2976 // argument list into our AST format.
2977 bool HasExplicitTemplateArgs = false;
2978 TemplateArgumentListInfo TemplateArgs;
2979 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
2980 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
2981 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
2982 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
2983 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2984 TemplateId->getTemplateArgs(),
2985 TemplateId->NumArgs);
2986 translateTemplateArguments(TemplateArgsPtr,
2988 TemplateArgsPtr.release();
2990 HasExplicitTemplateArgs = true;
2992 if (FunctionTemplate) {
2993 // FIXME: Diagnose function template with explicit template
2995 HasExplicitTemplateArgs = false;
2996 } else if (!isFunctionTemplateSpecialization &&
2997 !D.getDeclSpec().isFriendSpecified()) {
2998 // We have encountered something that the user meant to be a
2999 // specialization (because it has explicitly-specified template
3000 // arguments) but that was not introduced with a "template<>" (or had
3001 // too few of them).
3002 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
3003 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
3004 << CodeModificationHint::CreateInsertion(
3005 D.getDeclSpec().getSourceRange().getBegin(),
3007 isFunctionTemplateSpecialization = true;
3011 if (isFunctionTemplateSpecialization) {
3012 if (CheckFunctionTemplateSpecialization(NewFD,
3013 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
3015 NewFD->setInvalidDecl();
3016 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD) &&
3017 CheckMemberSpecialization(NewFD, Previous))
3018 NewFD->setInvalidDecl();
3020 // Perform semantic checking on the function declaration.
3021 bool OverloadableAttrRequired = false; // FIXME: HACK!
3022 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization,
3023 Redeclaration, /*FIXME:*/OverloadableAttrRequired);
3025 assert((NewFD->isInvalidDecl() || !Redeclaration ||
3026 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
3027 "previous declaration set still overloaded");
3029 // If we have a function template, check the template parameter
3030 // list. This will check and merge default template arguments.
3031 if (FunctionTemplate) {
3032 FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration();
3033 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
3034 PrevTemplate? PrevTemplate->getTemplateParameters() : 0,
3035 D.getDeclSpec().isFriendSpecified()? TPC_FriendFunctionTemplate
3036 : TPC_FunctionTemplate);
3039 if (D.getCXXScopeSpec().isSet() && !NewFD->isInvalidDecl()) {
3040 // Fake up an access specifier if it's supposed to be a class member.
3041 if (!Redeclaration && isa<CXXRecordDecl>(NewFD->getDeclContext()))
3042 NewFD->setAccess(AS_public);
3044 // An out-of-line member function declaration must also be a
3045 // definition (C++ [dcl.meaning]p1).
3046 // Note that this is not the case for explicit specializations of
3047 // function templates or member functions of class templates, per
3048 // C++ [temp.expl.spec]p2.
3049 if (!IsFunctionDefinition && !isFriend &&
3050 !isFunctionTemplateSpecialization && !isExplicitSpecialization) {
3051 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
3052 << D.getCXXScopeSpec().getRange();
3053 NewFD->setInvalidDecl();
3054 } else if (!Redeclaration &&
3055 !(isFriend && CurContext->isDependentContext())) {
3056 // The user tried to provide an out-of-line definition for a
3057 // function that is a member of a class or namespace, but there
3058 // was no such member function declared (C++ [class.mfct]p2,
3059 // C++ [namespace.memdef]p2). For example:
3065 // void X::f() { } // ill-formed
3067 // Complain about this problem, and attempt to suggest close
3068 // matches (e.g., those that differ only in cv-qualifiers and
3069 // whether the parameter types are references).
3070 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
3071 << Name << DC << D.getCXXScopeSpec().getRange();
3072 NewFD->setInvalidDecl();
3074 LookupResult Prev(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
3076 LookupQualifiedName(Prev, DC);
3077 assert(!Prev.isAmbiguous() &&
3078 "Cannot have an ambiguity in previous-declaration lookup");
3079 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
3080 Func != FuncEnd; ++Func) {
3081 if (isa<FunctionDecl>(*Func) &&
3082 isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
3083 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
3088 // Handle attributes. We need to have merged decls when handling attributes
3089 // (for example to check for conflicts, etc).
3090 // FIXME: This needs to happen before we merge declarations. Then,
3091 // let attribute merging cope with attribute conflicts.
3092 ProcessDeclAttributes(S, NewFD, D);
3094 // attributes declared post-definition are currently ignored
3095 if (Redeclaration && Previous.isSingleResult()) {
3096 const FunctionDecl *Def;
3097 FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
3098 if (PrevFD && PrevFD->getBody(Def) && D.hasAttributes()) {
3099 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
3100 Diag(Def->getLocation(), diag::note_previous_definition);
3104 AddKnownFunctionAttributes(NewFD);
3106 if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) {
3107 // If a function name is overloadable in C, then every function
3108 // with that name must be marked "overloadable".
3109 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
3110 << Redeclaration << NewFD;
3111 if (!Previous.empty())
3112 Diag(Previous.getRepresentativeDecl()->getLocation(),
3113 diag::note_attribute_overloadable_prev_overload);
3114 NewFD->addAttr(::new (Context) OverloadableAttr());
3117 // If this is a locally-scoped extern C function, update the
3118 // map of such names.
3119 if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
3120 && !NewFD->isInvalidDecl())
3121 RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
3123 // Set this FunctionDecl's range up to the right paren.
3124 NewFD->setLocEnd(D.getSourceRange().getEnd());
3126 if (FunctionTemplate && NewFD->isInvalidDecl())
3127 FunctionTemplate->setInvalidDecl();
3129 if (FunctionTemplate)
3130 return FunctionTemplate;
3133 // Keep track of static, non-inlined function definitions that
3134 // have not been used. We will warn later.
3135 // FIXME: Also include static functions declared but not defined.
3136 if (!NewFD->isInvalidDecl() && IsFunctionDefinition
3137 && !NewFD->isInlined() && NewFD->getLinkage() == InternalLinkage
3138 && !NewFD->isUsed())
3139 UnusedStaticFuncs.push_back(NewFD);
3144 /// \brief Perform semantic checking of a new function declaration.
3146 /// Performs semantic analysis of the new function declaration
3147 /// NewFD. This routine performs all semantic checking that does not
3148 /// require the actual declarator involved in the declaration, and is
3149 /// used both for the declaration of functions as they are parsed
3150 /// (called via ActOnDeclarator) and for the declaration of functions
3151 /// that have been instantiated via C++ template instantiation (called
3152 /// via InstantiateDecl).
3154 /// \param IsExplicitSpecialiation whether this new function declaration is
3155 /// an explicit specialization of the previous declaration.
3157 /// This sets NewFD->isInvalidDecl() to true if there was an error.
3158 void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
3159 LookupResult &Previous,
3160 bool IsExplicitSpecialization,
3161 bool &Redeclaration,
3162 bool &OverloadableAttrRequired) {
3163 // If NewFD is already known erroneous, don't do any of this checking.
3164 if (NewFD->isInvalidDecl())
3167 if (NewFD->getResultType()->isVariablyModifiedType()) {
3168 // Functions returning a variably modified type violate C99 6.7.5.2p2
3169 // because all functions have linkage.
3170 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
3171 return NewFD->setInvalidDecl();
3174 if (NewFD->isMain())
3177 // Check for a previous declaration of this name.
3178 if (Previous.empty() && NewFD->isExternC()) {
3179 // Since we did not find anything by this name and we're declaring
3180 // an extern "C" function, look for a non-visible extern "C"
3181 // declaration with the same name.
3182 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3183 = LocallyScopedExternalDecls.find(NewFD->getDeclName());
3184 if (Pos != LocallyScopedExternalDecls.end())
3185 Previous.addDecl(Pos->second);
3188 // Merge or overload the declaration with an existing declaration of
3189 // the same name, if appropriate.
3190 if (!Previous.empty()) {
3191 // Determine whether NewFD is an overload of PrevDecl or
3192 // a declaration that requires merging. If it's an overload,
3193 // there's no more work to do here; we'll just add the new
3194 // function to the scope.
3196 NamedDecl *OldDecl = 0;
3197 if (!AllowOverloadingOfFunction(Previous, Context)) {
3198 Redeclaration = true;
3199 OldDecl = Previous.getFoundDecl();
3201 if (!getLangOptions().CPlusPlus) {
3202 OverloadableAttrRequired = true;
3204 // Functions marked "overloadable" must have a prototype (that
3205 // we can't get through declaration merging).
3206 if (!NewFD->getType()->getAs<FunctionProtoType>()) {
3207 Diag(NewFD->getLocation(),
3208 diag::err_attribute_overloadable_no_prototype)
3210 Redeclaration = true;
3212 // Turn this into a variadic function with no parameters.
3213 QualType R = Context.getFunctionType(
3214 NewFD->getType()->getAs<FunctionType>()->getResultType(),
3217 return NewFD->setInvalidDecl();
3221 switch (CheckOverload(NewFD, Previous, OldDecl)) {
3223 Redeclaration = true;
3224 if (isa<UsingShadowDecl>(OldDecl) && CurContext->isRecord()) {
3225 HideUsingShadowDecl(S, cast<UsingShadowDecl>(OldDecl));
3226 Redeclaration = false;
3230 case Ovl_NonFunction:
3231 Redeclaration = true;
3235 Redeclaration = false;
3240 if (Redeclaration) {
3241 // NewFD and OldDecl represent declarations that need to be
3243 if (MergeFunctionDecl(NewFD, OldDecl))
3244 return NewFD->setInvalidDecl();
3247 Previous.addDecl(OldDecl);
3249 if (FunctionTemplateDecl *OldTemplateDecl
3250 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
3251 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
3252 FunctionTemplateDecl *NewTemplateDecl
3253 = NewFD->getDescribedFunctionTemplate();
3254 assert(NewTemplateDecl && "Template/non-template mismatch");
3255 if (CXXMethodDecl *Method
3256 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
3257 Method->setAccess(OldTemplateDecl->getAccess());
3258 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
3261 // If this is an explicit specialization of a member that is a function
3262 // template, mark it as a member specialization.
3263 if (IsExplicitSpecialization &&
3264 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
3265 NewTemplateDecl->setMemberSpecialization();
3266 assert(OldTemplateDecl->isMemberSpecialization());
3269 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
3270 NewFD->setAccess(OldDecl->getAccess());
3271 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
3276 // Semantic checking for this function declaration (in isolation).
3277 if (getLangOptions().CPlusPlus) {
3278 // C++-specific checks.
3279 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
3280 CheckConstructor(Constructor);
3281 } else if (CXXDestructorDecl *Destructor =
3282 dyn_cast<CXXDestructorDecl>(NewFD)) {
3283 CXXRecordDecl *Record = Destructor->getParent();
3284 QualType ClassType = Context.getTypeDeclType(Record);
3286 // FIXME: Shouldn't we be able to perform thisc heck even when the class
3287 // type is dependent? Both gcc and edg can handle that.
3288 if (!ClassType->isDependentType()) {
3289 DeclarationName Name
3290 = Context.DeclarationNames.getCXXDestructorName(
3291 Context.getCanonicalType(ClassType));
3292 if (NewFD->getDeclName() != Name) {
3293 Diag(NewFD->getLocation(), diag::err_destructor_name);
3294 return NewFD->setInvalidDecl();
3298 Record->setUserDeclaredDestructor(true);
3299 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
3300 // user-defined destructor.
3301 Record->setPOD(false);
3303 // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly-
3304 // declared destructor.
3305 // FIXME: C++0x: don't do this for "= default" destructors
3306 Record->setHasTrivialDestructor(false);
3307 } else if (CXXConversionDecl *Conversion
3308 = dyn_cast<CXXConversionDecl>(NewFD)) {
3309 ActOnConversionDeclarator(Conversion);
3312 // Find any virtual functions that this function overrides.
3313 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
3314 if (!Method->isFunctionTemplateSpecialization() &&
3315 !Method->getDescribedFunctionTemplate())
3316 AddOverriddenMethods(Method->getParent(), Method);
3319 // Additional checks for the destructor; make sure we do this after we
3320 // figure out whether the destructor is virtual.
3321 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
3322 if (!Destructor->getParent()->isDependentType())
3323 CheckDestructor(Destructor);
3325 // Extra checking for C++ overloaded operators (C++ [over.oper]).
3326 if (NewFD->isOverloadedOperator() &&
3327 CheckOverloadedOperatorDeclaration(NewFD))
3328 return NewFD->setInvalidDecl();
3330 // Extra checking for C++0x literal operators (C++0x [over.literal]).
3331 if (NewFD->getLiteralIdentifier() &&
3332 CheckLiteralOperatorDeclaration(NewFD))
3333 return NewFD->setInvalidDecl();
3335 // In C++, check default arguments now that we have merged decls. Unless
3336 // the lexical context is the class, because in this case this is done
3337 // during delayed parsing anyway.
3338 if (!CurContext->isRecord())
3339 CheckCXXDefaultArguments(NewFD);
3343 void Sema::CheckMain(FunctionDecl* FD) {
3344 // C++ [basic.start.main]p3: A program that declares main to be inline
3345 // or static is ill-formed.
3346 // C99 6.7.4p4: In a hosted environment, the inline function specifier
3347 // shall not appear in a declaration of main.
3348 // static main is not an error under C99, but we should warn about it.
3349 bool isInline = FD->isInlineSpecified();
3350 bool isStatic = FD->getStorageClass() == FunctionDecl::Static;
3351 if (isInline || isStatic) {
3352 unsigned diagID = diag::warn_unusual_main_decl;
3353 if (isInline || getLangOptions().CPlusPlus)
3354 diagID = diag::err_unusual_main_decl;
3356 int which = isStatic + (isInline << 1) - 1;
3357 Diag(FD->getLocation(), diagID) << which;
3360 QualType T = FD->getType();
3361 assert(T->isFunctionType() && "function decl is not of function type");
3362 const FunctionType* FT = T->getAs<FunctionType>();
3364 if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
3365 // TODO: add a replacement fixit to turn the return type into 'int'.
3366 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
3367 FD->setInvalidDecl(true);
3370 // Treat protoless main() as nullary.
3371 if (isa<FunctionNoProtoType>(FT)) return;
3373 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
3374 unsigned nparams = FTP->getNumArgs();
3375 assert(FD->getNumParams() == nparams);
3377 bool HasExtraParameters = (nparams > 3);
3379 // Darwin passes an undocumented fourth argument of type char**. If
3380 // other platforms start sprouting these, the logic below will start
3383 Context.Target.getTriple().getOS() == llvm::Triple::Darwin)
3384 HasExtraParameters = false;
3386 if (HasExtraParameters) {
3387 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
3388 FD->setInvalidDecl(true);
3392 // FIXME: a lot of the following diagnostics would be improved
3393 // if we had some location information about types.
3396 Context.getPointerType(Context.getPointerType(Context.CharTy));
3397 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
3399 for (unsigned i = 0; i < nparams; ++i) {
3400 QualType AT = FTP->getArgType(i);
3402 bool mismatch = true;
3404 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
3406 else if (Expected[i] == CharPP) {
3407 // As an extension, the following forms are okay:
3409 // char const * const *
3412 QualifierCollector qs;
3413 const PointerType* PT;
3414 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
3415 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
3416 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
3418 mismatch = !qs.empty();
3423 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
3424 // TODO: suggest replacing given type with expected type
3425 FD->setInvalidDecl(true);
3429 if (nparams == 1 && !FD->isInvalidDecl()) {
3430 Diag(FD->getLocation(), diag::warn_main_one_arg);
3434 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
3435 // FIXME: Need strict checking. In C89, we need to check for
3436 // any assignment, increment, decrement, function-calls, or
3437 // commas outside of a sizeof. In C99, it's the same list,
3438 // except that the aforementioned are allowed in unevaluated
3439 // expressions. Everything else falls under the
3440 // "may accept other forms of constant expressions" exception.
3441 // (We never end up here for C++, so the constant expression
3442 // rules there don't matter.)
3443 if (Init->isConstantInitializer(Context))
3445 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
3446 << Init->getSourceRange();
3450 void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init) {
3451 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
3454 /// AddInitializerToDecl - Adds the initializer Init to the
3455 /// declaration dcl. If DirectInit is true, this is C++ direct
3456 /// initialization rather than copy initialization.
3457 void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init, bool DirectInit) {
3458 Decl *RealDecl = dcl.getAs<Decl>();
3459 // If there is no declaration, there was an error parsing it. Just ignore
3464 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
3465 // With declarators parsed the way they are, the parser cannot
3466 // distinguish between a normal initializer and a pure-specifier.
3467 // Thus this grotesque test.
3469 Expr *Init = static_cast<Expr *>(init.get());
3470 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
3471 Context.getCanonicalType(IL->getType()) == Context.IntTy)
3472 CheckPureMethod(Method, Init->getSourceRange());
3474 Diag(Method->getLocation(), diag::err_member_function_initialization)
3475 << Method->getDeclName() << Init->getSourceRange();
3476 Method->setInvalidDecl();
3481 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3483 if (getLangOptions().CPlusPlus &&
3484 RealDecl->getLexicalDeclContext()->isRecord() &&
3485 isa<NamedDecl>(RealDecl))
3486 Diag(RealDecl->getLocation(), diag::err_member_initialization)
3487 << cast<NamedDecl>(RealDecl)->getDeclName();
3489 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3490 RealDecl->setInvalidDecl();
3494 // A definition must end up with a complete type, which means it must be
3495 // complete with the restriction that an array type might be completed by the
3496 // initializer; note that later code assumes this restriction.
3497 QualType BaseDeclType = VDecl->getType();
3498 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
3499 BaseDeclType = Array->getElementType();
3500 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
3501 diag::err_typecheck_decl_incomplete_type)) {
3502 RealDecl->setInvalidDecl();
3506 // The variable can not have an abstract class type.
3507 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
3508 diag::err_abstract_type_in_decl,
3509 AbstractVariableType))
3510 VDecl->setInvalidDecl();
3513 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
3514 Diag(VDecl->getLocation(), diag::err_redefinition)
3515 << VDecl->getDeclName();
3516 Diag(Def->getLocation(), diag::note_previous_definition);
3517 VDecl->setInvalidDecl();
3521 // Take ownership of the expression, now that we're sure we have somewhere
3523 Expr *Init = init.takeAs<Expr>();
3524 assert(Init && "missing initializer");
3526 // Capture the variable that is being initialized and the style of
3528 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
3530 // FIXME: Poor source location information.
3531 InitializationKind Kind
3532 = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(),
3533 Init->getLocStart(),
3535 : InitializationKind::CreateCopy(VDecl->getLocation(),
3536 Init->getLocStart());
3538 // Get the decls type and save a reference for later, since
3539 // CheckInitializerTypes may change it.
3540 QualType DclT = VDecl->getType(), SavT = DclT;
3541 if (VDecl->isBlockVarDecl()) {
3542 if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
3543 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
3544 VDecl->setInvalidDecl();
3545 } else if (!VDecl->isInvalidDecl()) {
3546 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
3547 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3548 MultiExprArg(*this, (void**)&Init, 1),
3550 if (Result.isInvalid()) {
3551 VDecl->setInvalidDecl();
3555 Init = Result.takeAs<Expr>();
3557 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
3558 // Don't check invalid declarations to avoid emitting useless diagnostics.
3559 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
3560 if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4.
3561 CheckForConstantInitializer(Init, DclT);
3564 } else if (VDecl->isStaticDataMember() &&
3565 VDecl->getLexicalDeclContext()->isRecord()) {
3566 // This is an in-class initialization for a static data member, e.g.,
3569 // static const int value = 17;
3572 // Attach the initializer
3573 VDecl->setInit(Init);
3575 // C++ [class.mem]p4:
3576 // A member-declarator can contain a constant-initializer only
3577 // if it declares a static member (9.4) of const integral or
3578 // const enumeration type, see 9.4.2.
3579 QualType T = VDecl->getType();
3580 if (!T->isDependentType() &&
3581 (!Context.getCanonicalType(T).isConstQualified() ||
3582 !T->isIntegralType())) {
3583 Diag(VDecl->getLocation(), diag::err_member_initialization)
3584 << VDecl->getDeclName() << Init->getSourceRange();
3585 VDecl->setInvalidDecl();
3587 // C++ [class.static.data]p4:
3588 // If a static data member is of const integral or const
3589 // enumeration type, its declaration in the class definition
3590 // can specify a constant-initializer which shall be an
3591 // integral constant expression (5.19).
3592 if (!Init->isTypeDependent() &&
3593 !Init->getType()->isIntegralType()) {
3594 // We have a non-dependent, non-integral or enumeration type.
3595 Diag(Init->getSourceRange().getBegin(),
3596 diag::err_in_class_initializer_non_integral_type)
3597 << Init->getType() << Init->getSourceRange();
3598 VDecl->setInvalidDecl();
3599 } else if (!Init->isTypeDependent() && !Init->isValueDependent()) {
3600 // Check whether the expression is a constant expression.
3603 if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) {
3604 Diag(Loc, diag::err_in_class_initializer_non_constant)
3605 << Init->getSourceRange();
3606 VDecl->setInvalidDecl();
3607 } else if (!VDecl->getType()->isDependentType())
3608 ImpCastExprToType(Init, VDecl->getType(), CastExpr::CK_IntegralCast);
3611 } else if (VDecl->isFileVarDecl()) {
3612 if (VDecl->getStorageClass() == VarDecl::Extern)
3613 Diag(VDecl->getLocation(), diag::warn_extern_init);
3614 if (!VDecl->isInvalidDecl()) {
3615 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
3616 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3617 MultiExprArg(*this, (void**)&Init, 1),
3619 if (Result.isInvalid()) {
3620 VDecl->setInvalidDecl();
3624 Init = Result.takeAs<Expr>();
3627 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
3628 // Don't check invalid declarations to avoid emitting useless diagnostics.
3629 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
3630 // C99 6.7.8p4. All file scoped initializers need to be constant.
3631 CheckForConstantInitializer(Init, DclT);
3634 // If the type changed, it means we had an incomplete type that was
3635 // completed by the initializer. For example:
3636 // int ary[] = { 1, 3, 5 };
3637 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
3638 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
3639 VDecl->setType(DclT);
3640 Init->setType(DclT);
3643 Init = MaybeCreateCXXExprWithTemporaries(Init);
3644 // Attach the initializer to the decl.
3645 VDecl->setInit(Init);
3647 if (getLangOptions().CPlusPlus) {
3648 // Make sure we mark the destructor as used if necessary.
3649 QualType InitType = VDecl->getType();
3650 while (const ArrayType *Array = Context.getAsArrayType(InitType))
3651 InitType = Context.getBaseElementType(Array);
3652 if (const RecordType *Record = InitType->getAs<RecordType>())
3653 FinalizeVarWithDestructor(VDecl, Record);
3659 void Sema::ActOnUninitializedDecl(DeclPtrTy dcl,
3660 bool TypeContainsUndeducedAuto) {
3661 Decl *RealDecl = dcl.getAs<Decl>();
3663 // If there is no declaration, there was an error parsing it. Just ignore it.
3667 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
3668 QualType Type = Var->getType();
3670 // C++0x [dcl.spec.auto]p3
3671 if (TypeContainsUndeducedAuto) {
3672 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
3673 << Var->getDeclName() << Type;
3674 Var->setInvalidDecl();
3678 switch (Var->isThisDeclarationADefinition()) {
3679 case VarDecl::Definition:
3680 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
3683 // We have an out-of-line definition of a static data member
3684 // that has an in-class initializer, so we type-check this like
3689 case VarDecl::DeclarationOnly:
3690 // It's only a declaration.
3692 // Block scope. C99 6.7p7: If an identifier for an object is
3693 // declared with no linkage (C99 6.2.2p6), the type for the
3694 // object shall be complete.
3695 if (!Type->isDependentType() && Var->isBlockVarDecl() &&
3696 !Var->getLinkage() && !Var->isInvalidDecl() &&
3697 RequireCompleteType(Var->getLocation(), Type,
3698 diag::err_typecheck_decl_incomplete_type))
3699 Var->setInvalidDecl();
3701 // Make sure that the type is not abstract.
3702 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
3703 RequireNonAbstractType(Var->getLocation(), Type,
3704 diag::err_abstract_type_in_decl,
3705 AbstractVariableType))
3706 Var->setInvalidDecl();
3709 case VarDecl::TentativeDefinition:
3710 // File scope. C99 6.9.2p2: A declaration of an identifier for an
3711 // object that has file scope without an initializer, and without a
3712 // storage-class specifier or with the storage-class specifier "static",
3713 // constitutes a tentative definition. Note: A tentative definition with
3714 // external linkage is valid (C99 6.2.2p5).
3715 if (!Var->isInvalidDecl()) {
3716 if (const IncompleteArrayType *ArrayT
3717 = Context.getAsIncompleteArrayType(Type)) {
3718 if (RequireCompleteType(Var->getLocation(),
3719 ArrayT->getElementType(),
3720 diag::err_illegal_decl_array_incomplete_type))
3721 Var->setInvalidDecl();
3722 } else if (Var->getStorageClass() == VarDecl::Static) {
3723 // C99 6.9.2p3: If the declaration of an identifier for an object is
3724 // a tentative definition and has internal linkage (C99 6.2.2p3), the
3725 // declared type shall not be an incomplete type.
3726 // NOTE: code such as the following
3728 // struct s { int a; };
3729 // is accepted by gcc. Hence here we issue a warning instead of
3730 // an error and we do not invalidate the static declaration.
3731 // NOTE: to avoid multiple warnings, only check the first declaration.
3732 if (Var->getPreviousDeclaration() == 0)
3733 RequireCompleteType(Var->getLocation(), Type,
3734 diag::ext_typecheck_decl_incomplete_type);
3738 // Record the tentative definition; we're done.
3739 if (!Var->isInvalidDecl())
3740 TentativeDefinitions.push_back(Var);
3744 // Provide a specific diagnostic for uninitialized variable
3745 // definitions with incomplete array type.
3746 if (Type->isIncompleteArrayType()) {
3747 Diag(Var->getLocation(),
3748 diag::err_typecheck_incomplete_array_needs_initializer);
3749 Var->setInvalidDecl();
3753 // Provide a specific diagnostic for uninitialized variable
3754 // definitions with reference type.
3755 if (Type->isReferenceType()) {
3756 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
3757 << Var->getDeclName()
3758 << SourceRange(Var->getLocation(), Var->getLocation());
3759 Var->setInvalidDecl();
3763 // Do not attempt to type-check the default initializer for a
3764 // variable with dependent type.
3765 if (Type->isDependentType())
3768 if (Var->isInvalidDecl())
3771 if (RequireCompleteType(Var->getLocation(),
3772 Context.getBaseElementType(Type),
3773 diag::err_typecheck_decl_incomplete_type)) {
3774 Var->setInvalidDecl();
3778 // The variable can not have an abstract class type.
3779 if (RequireNonAbstractType(Var->getLocation(), Type,
3780 diag::err_abstract_type_in_decl,
3781 AbstractVariableType)) {
3782 Var->setInvalidDecl();
3786 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
3787 InitializationKind Kind
3788 = InitializationKind::CreateDefault(Var->getLocation());
3790 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
3791 OwningExprResult Init = InitSeq.Perform(*this, Entity, Kind,
3792 MultiExprArg(*this, 0, 0));
3793 if (Init.isInvalid())
3794 Var->setInvalidDecl();
3797 Var->setInit(MaybeCreateCXXExprWithTemporaries(Init.takeAs<Expr>()));
3799 if (getLangOptions().CPlusPlus)
3800 if (const RecordType *Record
3801 = Context.getBaseElementType(Type)->getAs<RecordType>())
3802 FinalizeVarWithDestructor(Var, Record);
3807 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
3809 unsigned NumDecls) {
3810 llvm::SmallVector<Decl*, 8> Decls;
3812 if (DS.isTypeSpecOwned())
3813 Decls.push_back((Decl*)DS.getTypeRep());
3815 for (unsigned i = 0; i != NumDecls; ++i)
3816 if (Decl *D = Group[i].getAs<Decl>())
3819 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context,
3820 Decls.data(), Decls.size()));
3824 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
3825 /// to introduce parameters into function prototype scope.
3827 Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
3828 const DeclSpec &DS = D.getDeclSpec();
3830 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
3831 VarDecl::StorageClass StorageClass = VarDecl::None;
3832 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
3833 StorageClass = VarDecl::Register;
3834 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
3835 Diag(DS.getStorageClassSpecLoc(),
3836 diag::err_invalid_storage_class_in_func_decl);
3837 D.getMutableDeclSpec().ClearStorageClassSpecs();
3840 if (D.getDeclSpec().isThreadSpecified())
3841 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
3843 DiagnoseFunctionSpecifiers(D);
3845 // Check that there are no default arguments inside the type of this
3846 // parameter (C++ only).
3847 if (getLangOptions().CPlusPlus)
3848 CheckExtraCXXDefaultArguments(D);
3850 TypeSourceInfo *TInfo = 0;
3851 TagDecl *OwnedDecl = 0;
3852 QualType parmDeclType = GetTypeForDeclarator(D, S, &TInfo, &OwnedDecl);
3854 if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) {
3856 // Types shall not be defined in return or parameter types.
3857 Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
3858 << Context.getTypeDeclType(OwnedDecl);
3861 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
3862 // Can this happen for params? We already checked that they don't conflict
3863 // among each other. Here they can only shadow globals, which is ok.
3864 IdentifierInfo *II = D.getIdentifier();
3866 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
3867 if (PrevDecl->isTemplateParameter()) {
3868 // Maybe we will complain about the shadowed template parameter.
3869 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
3870 // Just pretend that we didn't see the previous declaration.
3872 } else if (S->isDeclScope(DeclPtrTy::make(PrevDecl))) {
3873 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
3875 // Recover by removing the name
3877 D.SetIdentifier(0, D.getIdentifierLoc());
3878 D.setInvalidType(true);
3883 // Parameters can not be abstract class types.
3884 // For record types, this is done by the AbstractClassUsageDiagnoser once
3885 // the class has been completely parsed.
3886 if (!CurContext->isRecord() &&
3887 RequireNonAbstractType(D.getIdentifierLoc(), parmDeclType,
3888 diag::err_abstract_type_in_decl,
3890 D.setInvalidType(true);
3892 QualType T = adjustParameterType(parmDeclType);
3894 // Temporarily put parameter variables in the translation unit, not
3895 // the enclosing context. This prevents them from accidentally
3896 // looking like class members in C++.
3897 DeclContext *DC = Context.getTranslationUnitDecl();
3900 = ParmVarDecl::Create(Context, DC, D.getIdentifierLoc(), II,
3901 T, TInfo, StorageClass, 0);
3903 if (D.isInvalidType())
3904 New->setInvalidDecl();
3906 // Parameter declarators cannot be interface types. All ObjC objects are
3907 // passed by reference.
3908 if (T->isObjCInterfaceType()) {
3909 Diag(D.getIdentifierLoc(),
3910 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
3911 New->setInvalidDecl();
3914 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
3915 if (D.getCXXScopeSpec().isSet()) {
3916 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
3917 << D.getCXXScopeSpec().getRange();
3918 New->setInvalidDecl();
3921 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
3922 // duration shall not be qualified by an address-space qualifier."
3923 // Since all parameters have automatic store duration, they can not have
3924 // an address space.
3925 if (T.getAddressSpace() != 0) {
3926 Diag(D.getIdentifierLoc(),
3927 diag::err_arg_with_address_space);
3928 New->setInvalidDecl();
3932 // Add the parameter declaration into this scope.
3933 S->AddDecl(DeclPtrTy::make(New));
3935 IdResolver.AddDecl(New);
3937 ProcessDeclAttributes(S, New, D);
3939 if (New->hasAttr<BlocksAttr>()) {
3940 Diag(New->getLocation(), diag::err_block_on_nonlocal);
3942 return DeclPtrTy::make(New);
3945 void Sema::ActOnObjCCatchParam(DeclPtrTy D) {
3946 ParmVarDecl *Param = cast<ParmVarDecl>(D.getAs<Decl>());
3947 Param->setDeclContext(CurContext);
3950 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
3951 SourceLocation LocAfterDecls) {
3952 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3953 "Not a function declarator!");
3954 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3956 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
3957 // for a K&R function.
3958 if (!FTI.hasPrototype) {
3959 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
3961 if (FTI.ArgInfo[i].Param == 0) {
3962 llvm::SmallString<256> Code;
3963 llvm::raw_svector_ostream(Code) << " int "
3964 << FTI.ArgInfo[i].Ident->getName()
3966 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
3967 << FTI.ArgInfo[i].Ident
3968 << CodeModificationHint::CreateInsertion(LocAfterDecls, Code.str());
3970 // Implicitly declare the argument as type 'int' for lack of a better
3973 const char* PrevSpec; // unused
3974 unsigned DiagID; // unused
3975 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
3977 Declarator ParamD(DS, Declarator::KNRTypeListContext);
3978 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
3979 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
3985 Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
3987 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3988 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3989 "Not a function declarator!");
3990 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3992 if (FTI.hasPrototype) {
3993 // FIXME: Diagnose arguments without names in C.
3996 Scope *ParentScope = FnBodyScope->getParent();
3998 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
3999 MultiTemplateParamsArg(*this),
4000 /*IsFunctionDefinition=*/true);
4001 return ActOnStartOfFunctionDef(FnBodyScope, DP);
4004 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
4005 // Don't warn about invalid declarations.
4006 if (FD->isInvalidDecl())
4009 // Or declarations that aren't global.
4010 if (!FD->isGlobal())
4013 // Don't warn about C++ member functions.
4014 if (isa<CXXMethodDecl>(FD))
4017 // Don't warn about 'main'.
4021 // Don't warn about inline functions.
4022 if (FD->isInlineSpecified())
4025 // Don't warn about function templates.
4026 if (FD->getDescribedFunctionTemplate())
4029 // Don't warn about function template specializations.
4030 if (FD->isFunctionTemplateSpecialization())
4033 bool MissingPrototype = true;
4034 for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
4035 Prev; Prev = Prev->getPreviousDeclaration()) {
4036 // Ignore any declarations that occur in function or method
4037 // scope, because they aren't visible from the header.
4038 if (Prev->getDeclContext()->isFunctionOrMethod())
4041 MissingPrototype = !Prev->getType()->isFunctionProtoType();
4045 return MissingPrototype;
4048 Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) {
4049 // Clear the last template instantiation error context.
4050 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
4054 FunctionDecl *FD = 0;
4056 if (FunctionTemplateDecl *FunTmpl
4057 = dyn_cast<FunctionTemplateDecl>(D.getAs<Decl>()))
4058 FD = FunTmpl->getTemplatedDecl();
4060 FD = cast<FunctionDecl>(D.getAs<Decl>());
4062 CurFunctionNeedsScopeChecking = false;
4064 // See if this is a redefinition.
4065 const FunctionDecl *Definition;
4066 if (FD->getBody(Definition)) {
4067 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
4068 Diag(Definition->getLocation(), diag::note_previous_definition);
4071 // Builtin functions cannot be defined.
4072 if (unsigned BuiltinID = FD->getBuiltinID()) {
4073 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4074 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
4075 FD->setInvalidDecl();
4079 // The return type of a function definition must be complete
4080 // (C99 6.9.1p3, C++ [dcl.fct]p6).
4081 QualType ResultType = FD->getResultType();
4082 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
4083 !FD->isInvalidDecl() &&
4084 RequireCompleteType(FD->getLocation(), ResultType,
4085 diag::err_func_def_incomplete_result))
4086 FD->setInvalidDecl();
4088 // GNU warning -Wmissing-prototypes:
4089 // Warn if a global function is defined without a previous
4090 // prototype declaration. This warning is issued even if the
4091 // definition itself provides a prototype. The aim is to detect
4092 // global functions that fail to be declared in header files.
4093 if (ShouldWarnAboutMissingPrototype(FD))
4094 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
4097 PushDeclContext(FnBodyScope, FD);
4099 // Check the validity of our function parameters
4100 CheckParmsForFunctionDef(FD);
4102 // Introduce our parameters into the function scope
4103 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
4104 ParmVarDecl *Param = FD->getParamDecl(p);
4105 Param->setOwningFunction(FD);
4107 // If this has an identifier, add it to the scope stack.
4108 if (Param->getIdentifier() && FnBodyScope)
4109 PushOnScopeChains(Param, FnBodyScope);
4112 // Checking attributes of current function definition
4113 // dllimport attribute.
4114 if (FD->getAttr<DLLImportAttr>() &&
4115 (!FD->getAttr<DLLExportAttr>())) {
4116 // dllimport attribute cannot be applied to definition.
4117 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
4118 Diag(FD->getLocation(),
4119 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
4121 FD->setInvalidDecl();
4122 return DeclPtrTy::make(FD);
4124 // If a symbol previously declared dllimport is later defined, the
4125 // attribute is ignored in subsequent references, and a warning is
4127 Diag(FD->getLocation(),
4128 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
4129 << FD->getNameAsCString() << "dllimport";
4132 return DeclPtrTy::make(FD);
4135 Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) {
4136 return ActOnFinishFunctionBody(D, move(BodyArg), false);
4139 Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg,
4140 bool IsInstantiation) {
4141 Decl *dcl = D.getAs<Decl>();
4142 Stmt *Body = BodyArg.takeAs<Stmt>();
4144 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
4145 // explosion for destrutors that can result and the compile time hit.
4146 AnalysisContext AC(dcl, false);
4147 FunctionDecl *FD = 0;
4148 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
4150 FD = FunTmpl->getTemplatedDecl();
4152 FD = dyn_cast_or_null<FunctionDecl>(dcl);
4157 // C and C++ allow for main to automagically return 0.
4158 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
4159 FD->setHasImplicitReturnZero(true);
4161 CheckFallThroughForFunctionDef(FD, Body, AC);
4163 if (!FD->isInvalidDecl())
4164 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
4166 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
4167 MaybeMarkVirtualMembersReferenced(Method->getLocation(), Method);
4169 assert(FD == getCurFunctionDecl() && "Function parsing confused");
4170 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
4171 assert(MD == getCurMethodDecl() && "Method parsing confused");
4173 CheckFallThroughForFunctionDef(MD, Body, AC);
4174 MD->setEndLoc(Body->getLocEnd());
4176 if (!MD->isInvalidDecl())
4177 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
4179 Body->Destroy(Context);
4182 if (!IsInstantiation)
4185 // Verify and clean out per-function state.
4187 assert(&getLabelMap() == &FunctionLabelMap && "Didn't pop block right?");
4189 // Check goto/label use.
4190 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
4191 I = FunctionLabelMap.begin(), E = FunctionLabelMap.end(); I != E; ++I) {
4192 LabelStmt *L = I->second;
4194 // Verify that we have no forward references left. If so, there was a goto
4195 // or address of a label taken, but no definition of it. Label fwd
4196 // definitions are indicated with a null substmt.
4197 if (L->getSubStmt() != 0)
4201 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
4203 // At this point, we have gotos that use the bogus label. Stitch it into
4204 // the function body so that they aren't leaked and that the AST is well
4207 // The whole function wasn't parsed correctly, just delete this.
4208 L->Destroy(Context);
4212 // Otherwise, the body is valid: we want to stitch the label decl into the
4213 // function somewhere so that it is properly owned and so that the goto
4214 // has a valid target. Do this by creating a new compound stmt with the
4217 // Give the label a sub-statement.
4218 L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
4220 CompoundStmt *Compound = isa<CXXTryStmt>(Body) ?
4221 cast<CXXTryStmt>(Body)->getTryBlock() :
4222 cast<CompoundStmt>(Body);
4223 std::vector<Stmt*> Elements(Compound->body_begin(), Compound->body_end());
4224 Elements.push_back(L);
4225 Compound->setStmts(Context, &Elements[0], Elements.size());
4227 FunctionLabelMap.clear();
4229 if (!Body) return D;
4231 CheckUnreachable(AC);
4233 // Verify that that gotos and switch cases don't jump into scopes illegally.
4234 if (CurFunctionNeedsScopeChecking)
4235 DiagnoseInvalidJumps(Body);
4237 // C++ constructors that have function-try-blocks can't have return
4238 // statements in the handlers of that block. (C++ [except.handle]p14)
4240 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
4241 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
4243 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl))
4244 MarkBaseAndMemberDestructorsReferenced(Destructor);
4246 // If any errors have occurred, clear out any temporaries that may have
4247 // been leftover. This ensures that these temporaries won't be picked up for
4248 // deletion in some later function.
4249 if (PP.getDiagnostics().hasErrorOccurred())
4250 ExprTemporaries.clear();
4252 assert(ExprTemporaries.empty() && "Leftover temporaries in function");
4256 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4257 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4258 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
4259 IdentifierInfo &II, Scope *S) {
4260 // Before we produce a declaration for an implicitly defined
4261 // function, see whether there was a locally-scoped declaration of
4262 // this name as a function or variable. If so, use that
4263 // (non-visible) declaration, and complain about it.
4264 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4265 = LocallyScopedExternalDecls.find(&II);
4266 if (Pos != LocallyScopedExternalDecls.end()) {
4267 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
4268 Diag(Pos->second->getLocation(), diag::note_previous_declaration);
4272 // Extension in C99. Legal in C90, but warn about it.
4273 if (II.getName().startswith("__builtin_"))
4274 Diag(Loc, diag::warn_builtin_unknown) << &II;
4275 else if (getLangOptions().C99)
4276 Diag(Loc, diag::ext_implicit_function_decl) << &II;
4278 Diag(Loc, diag::warn_implicit_function_decl) << &II;
4280 // Set a Declarator for the implicit definition: int foo();
4284 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
4285 Error = Error; // Silence warning.
4286 assert(!Error && "Error setting up implicit decl!");
4287 Declarator D(DS, Declarator::BlockContext);
4288 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
4289 0, 0, false, SourceLocation(),
4290 false, 0,0,0, Loc, Loc, D),
4292 D.SetIdentifier(&II, Loc);
4294 // Insert this function into translation-unit scope.
4296 DeclContext *PrevDC = CurContext;
4297 CurContext = Context.getTranslationUnitDecl();
4300 dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D).getAs<Decl>());
4303 CurContext = PrevDC;
4305 AddKnownFunctionAttributes(FD);
4310 /// \brief Adds any function attributes that we know a priori based on
4311 /// the declaration of this function.
4313 /// These attributes can apply both to implicitly-declared builtins
4314 /// (like __builtin___printf_chk) or to library-declared functions
4315 /// like NSLog or printf.
4316 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
4317 if (FD->isInvalidDecl())
4320 // If this is a built-in function, map its builtin attributes to
4321 // actual attributes.
4322 if (unsigned BuiltinID = FD->getBuiltinID()) {
4323 // Handle printf-formatting attributes.
4326 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
4327 if (!FD->getAttr<FormatAttr>())
4328 FD->addAttr(::new (Context) FormatAttr(Context, "printf", FormatIdx+1,
4329 HasVAListArg ? 0 : FormatIdx+2));
4332 // Mark const if we don't care about errno and that is the only
4333 // thing preventing the function from being const. This allows
4334 // IRgen to use LLVM intrinsics for such functions.
4335 if (!getLangOptions().MathErrno &&
4336 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
4337 if (!FD->getAttr<ConstAttr>())
4338 FD->addAttr(::new (Context) ConstAttr());
4341 if (Context.BuiltinInfo.isNoReturn(BuiltinID))
4342 FD->setType(Context.getNoReturnType(FD->getType()));
4343 if (Context.BuiltinInfo.isNoThrow(BuiltinID))
4344 FD->addAttr(::new (Context) NoThrowAttr());
4345 if (Context.BuiltinInfo.isConst(BuiltinID))
4346 FD->addAttr(::new (Context) ConstAttr());
4349 IdentifierInfo *Name = FD->getIdentifier();
4352 if ((!getLangOptions().CPlusPlus &&
4353 FD->getDeclContext()->isTranslationUnit()) ||
4354 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
4355 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
4356 LinkageSpecDecl::lang_c)) {
4357 // Okay: this could be a libc/libm/Objective-C function we know
4362 if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
4363 // FIXME: NSLog and NSLogv should be target specific
4364 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
4365 // FIXME: We known better than our headers.
4366 const_cast<FormatAttr *>(Format)->setType(Context, "printf");
4368 FD->addAttr(::new (Context) FormatAttr(Context, "printf", 1,
4369 Name->isStr("NSLogv") ? 0 : 2));
4370 } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
4371 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
4372 // target-specific builtins, perhaps?
4373 if (!FD->getAttr<FormatAttr>())
4374 FD->addAttr(::new (Context) FormatAttr(Context, "printf", 2,
4375 Name->isStr("vasprintf") ? 0 : 3));
4379 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
4380 TypeSourceInfo *TInfo) {
4381 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
4382 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
4385 assert(D.isInvalidType() && "no declarator info for valid type");
4386 TInfo = Context.getTrivialTypeSourceInfo(T);
4389 // Scope manipulation handled by caller.
4390 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
4391 D.getIdentifierLoc(),
4395 if (const TagType *TT = T->getAs<TagType>()) {
4396 TagDecl *TD = TT->getDecl();
4398 // If the TagDecl that the TypedefDecl points to is an anonymous decl
4399 // keep track of the TypedefDecl.
4400 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
4401 TD->setTypedefForAnonDecl(NewTD);
4404 if (D.isInvalidType())
4405 NewTD->setInvalidDecl();
4410 /// \brief Determine whether a tag with a given kind is acceptable
4411 /// as a redeclaration of the given tag declaration.
4413 /// \returns true if the new tag kind is acceptable, false otherwise.
4414 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
4415 TagDecl::TagKind NewTag,
4416 SourceLocation NewTagLoc,
4417 const IdentifierInfo &Name) {
4418 // C++ [dcl.type.elab]p3:
4419 // The class-key or enum keyword present in the
4420 // elaborated-type-specifier shall agree in kind with the
4421 // declaration to which the name in theelaborated-type-specifier
4422 // refers. This rule also applies to the form of
4423 // elaborated-type-specifier that declares a class-name or
4424 // friend class since it can be construed as referring to the
4425 // definition of the class. Thus, in any
4426 // elaborated-type-specifier, the enum keyword shall be used to
4427 // refer to an enumeration (7.2), the union class-keyshall be
4428 // used to refer to a union (clause 9), and either the class or
4429 // struct class-key shall be used to refer to a class (clause 9)
4430 // declared using the class or struct class-key.
4431 TagDecl::TagKind OldTag = Previous->getTagKind();
4432 if (OldTag == NewTag)
4435 if ((OldTag == TagDecl::TK_struct || OldTag == TagDecl::TK_class) &&
4436 (NewTag == TagDecl::TK_struct || NewTag == TagDecl::TK_class)) {
4437 // Warn about the struct/class tag mismatch.
4438 bool isTemplate = false;
4439 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
4440 isTemplate = Record->getDescribedClassTemplate();
4442 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
4443 << (NewTag == TagDecl::TK_class)
4444 << isTemplate << &Name
4445 << CodeModificationHint::CreateReplacement(SourceRange(NewTagLoc),
4446 OldTag == TagDecl::TK_class? "class" : "struct");
4447 Diag(Previous->getLocation(), diag::note_previous_use);
4453 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
4454 /// former case, Name will be non-null. In the later case, Name will be null.
4455 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
4456 /// reference/declaration/definition of a tag.
4457 Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4458 SourceLocation KWLoc, const CXXScopeSpec &SS,
4459 IdentifierInfo *Name, SourceLocation NameLoc,
4460 AttributeList *Attr, AccessSpecifier AS,
4461 MultiTemplateParamsArg TemplateParameterLists,
4462 bool &OwnedDecl, bool &IsDependent) {
4463 // If this is not a definition, it must have a name.
4464 assert((Name != 0 || TUK == TUK_Definition) &&
4465 "Nameless record must be a definition!");
4468 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
4470 // FIXME: Check explicit specializations more carefully.
4471 bool isExplicitSpecialization = false;
4472 if (TUK != TUK_Reference) {
4473 if (TemplateParameterList *TemplateParams
4474 = MatchTemplateParametersToScopeSpecifier(KWLoc, SS,
4475 (TemplateParameterList**)TemplateParameterLists.get(),
4476 TemplateParameterLists.size(),
4477 isExplicitSpecialization)) {
4478 if (TemplateParams->size() > 0) {
4479 // This is a declaration or definition of a class template (which may
4480 // be a member of another template).
4482 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
4483 SS, Name, NameLoc, Attr,
4486 TemplateParameterLists.release();
4487 return Result.get();
4489 // The "template<>" header is extraneous.
4490 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
4491 << ElaboratedType::getNameForTagKind(Kind) << Name;
4492 isExplicitSpecialization = true;
4496 TemplateParameterLists.release();
4499 DeclContext *SearchDC = CurContext;
4500 DeclContext *DC = CurContext;
4501 bool isStdBadAlloc = false;
4502 bool Invalid = false;
4504 RedeclarationKind Redecl = (TUK != TUK_Reference ? ForRedeclaration
4505 : NotForRedeclaration);
4507 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
4509 if (Name && SS.isNotEmpty()) {
4510 // We have a nested-name tag ('struct foo::bar').
4512 // Check for invalid 'foo::'.
4513 if (SS.isInvalid()) {
4518 // If this is a friend or a reference to a class in a dependent
4519 // context, don't try to make a decl for it.
4520 if (TUK == TUK_Friend || TUK == TUK_Reference) {
4521 DC = computeDeclContext(SS, false);
4528 if (RequireCompleteDeclContext(SS))
4529 return DeclPtrTy::make((Decl *)0);
4531 DC = computeDeclContext(SS, true);
4533 // Look-up name inside 'foo::'.
4534 LookupQualifiedName(Previous, DC);
4536 if (Previous.isAmbiguous())
4539 if (Previous.empty()) {
4540 // Name lookup did not find anything. However, if the
4541 // nested-name-specifier refers to the current instantiation,
4542 // and that current instantiation has any dependent base
4543 // classes, we might find something at instantiation time: treat
4544 // this as a dependent elaborated-type-specifier.
4545 if (Previous.wasNotFoundInCurrentInstantiation()) {
4550 // A tag 'foo::bar' must already exist.
4551 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
4557 // If this is a named struct, check to see if there was a previous forward
4558 // declaration or definition.
4559 // FIXME: We're looking into outer scopes here, even when we
4560 // shouldn't be. Doing so can result in ambiguities that we
4561 // shouldn't be diagnosing.
4562 LookupName(Previous, S);
4564 // Note: there used to be some attempt at recovery here.
4565 if (Previous.isAmbiguous())
4568 if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
4569 // FIXME: This makes sure that we ignore the contexts associated
4570 // with C structs, unions, and enums when looking for a matching
4571 // tag declaration or definition. See the similar lookup tweak
4572 // in Sema::LookupName; is there a better way to deal with this?
4573 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
4574 SearchDC = SearchDC->getParent();
4578 if (Previous.isSingleResult() &&
4579 Previous.getFoundDecl()->isTemplateParameter()) {
4580 // Maybe we will complain about the shadowed template parameter.
4581 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
4582 // Just pretend that we didn't see the previous declaration.
4586 if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
4587 DC->Equals(StdNamespace) && Name->isStr("bad_alloc")) {
4588 // This is a declaration of or a reference to "std::bad_alloc".
4589 isStdBadAlloc = true;
4591 if (Previous.empty() && StdBadAlloc) {
4592 // std::bad_alloc has been implicitly declared (but made invisible to
4593 // name lookup). Fill in this implicit declaration as the previous
4594 // declaration, so that the declarations get chained appropriately.
4595 Previous.addDecl(StdBadAlloc);
4599 if (!Previous.empty()) {
4600 assert(Previous.isSingleResult());
4601 NamedDecl *PrevDecl = Previous.getFoundDecl();
4602 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
4603 // If this is a use of a previous tag, or if the tag is already declared
4604 // in the same scope (so that the definition/declaration completes or
4605 // rementions the tag), reuse the decl.
4606 if (TUK == TUK_Reference || TUK == TUK_Friend ||
4607 isDeclInScope(PrevDecl, SearchDC, S)) {
4608 // Make sure that this wasn't declared as an enum and now used as a
4609 // struct or something similar.
4610 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) {
4612 = (PrevTagDecl->getTagKind() != TagDecl::TK_enum &&
4613 Kind != TagDecl::TK_enum);
4615 Diag(KWLoc, diag::err_use_with_wrong_tag)
4617 << CodeModificationHint::CreateReplacement(SourceRange(KWLoc),
4618 PrevTagDecl->getKindName());
4620 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
4621 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
4624 Kind = PrevTagDecl->getTagKind();
4626 // Recover by making this an anonymous redefinition.
4634 // If this is a use, just return the declaration we found.
4636 // FIXME: In the future, return a variant or some other clue
4637 // for the consumer of this Decl to know it doesn't own it.
4638 // For our current ASTs this shouldn't be a problem, but will
4639 // need to be changed with DeclGroups.
4640 if (TUK == TUK_Reference || TUK == TUK_Friend)
4641 return DeclPtrTy::make(PrevTagDecl);
4643 // Diagnose attempts to redefine a tag.
4644 if (TUK == TUK_Definition) {
4645 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
4646 // If we're defining a specialization and the previous definition
4647 // is from an implicit instantiation, don't emit an error
4648 // here; we'll catch this in the general case below.
4649 if (!isExplicitSpecialization ||
4650 !isa<CXXRecordDecl>(Def) ||
4651 cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
4652 == TSK_ExplicitSpecialization) {
4653 Diag(NameLoc, diag::err_redefinition) << Name;
4654 Diag(Def->getLocation(), diag::note_previous_definition);
4655 // If this is a redefinition, recover by making this
4656 // struct be anonymous, which will make any later
4657 // references get the previous definition.
4663 // If the type is currently being defined, complain
4664 // about a nested redefinition.
4665 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
4666 if (Tag->isBeingDefined()) {
4667 Diag(NameLoc, diag::err_nested_redefinition) << Name;
4668 Diag(PrevTagDecl->getLocation(),
4669 diag::note_previous_definition);
4676 // Okay, this is definition of a previously declared or referenced
4677 // tag PrevDecl. We're going to create a new Decl for it.
4680 // If we get here we have (another) forward declaration or we
4681 // have a definition. Just create a new decl.
4684 // If we get here, this is a definition of a new tag type in a nested
4685 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
4686 // new decl/type. We set PrevDecl to NULL so that the entities
4687 // have distinct types.
4690 // If we get here, we're going to create a new Decl. If PrevDecl
4691 // is non-NULL, it's a definition of the tag declared by
4692 // PrevDecl. If it's NULL, we have a new definition.
4694 // PrevDecl is a namespace, template, or anything else
4695 // that lives in the IDNS_Tag identifier namespace.
4696 if (isDeclInScope(PrevDecl, SearchDC, S)) {
4697 // The tag name clashes with a namespace name, issue an error and
4698 // recover by making this tag be anonymous.
4699 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
4700 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4705 // The existing declaration isn't relevant to us; we're in a
4706 // new scope, so clear out the previous declaration.
4710 } else if (TUK == TUK_Reference && SS.isEmpty() && Name) {
4711 // C++ [basic.scope.pdecl]p5:
4712 // -- for an elaborated-type-specifier of the form
4714 // class-key identifier
4716 // if the elaborated-type-specifier is used in the
4717 // decl-specifier-seq or parameter-declaration-clause of a
4718 // function defined in namespace scope, the identifier is
4719 // declared as a class-name in the namespace that contains
4720 // the declaration; otherwise, except as a friend
4721 // declaration, the identifier is declared in the smallest
4722 // non-class, non-function-prototype scope that contains the
4725 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
4726 // C structs and unions.
4728 // It is an error in C++ to declare (rather than define) an enum
4729 // type, including via an elaborated type specifier. We'll
4730 // diagnose that later; for now, declare the enum in the same
4731 // scope as we would have picked for any other tag type.
4733 // GNU C also supports this behavior as part of its incomplete
4734 // enum types extension, while GNU C++ does not.
4736 // Find the context where we'll be declaring the tag.
4737 // FIXME: We would like to maintain the current DeclContext as the
4739 while (SearchDC->isRecord())
4740 SearchDC = SearchDC->getParent();
4742 // Find the scope where we'll be declaring the tag.
4743 while (S->isClassScope() ||
4744 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
4745 ((S->getFlags() & Scope::DeclScope) == 0) ||
4747 ((DeclContext *)S->getEntity())->isTransparentContext()))
4750 } else if (TUK == TUK_Friend && SS.isEmpty() && Name) {
4751 // C++ [namespace.memdef]p3:
4752 // If a friend declaration in a non-local class first declares a
4753 // class or function, the friend class or function is a member of
4754 // the innermost enclosing namespace.
4755 while (!SearchDC->isFileContext())
4756 SearchDC = SearchDC->getParent();
4758 // The entity of a decl scope is a DeclContext; see PushDeclContext.
4759 while (S->getEntity() != SearchDC)
4765 TagDecl *PrevDecl = 0;
4766 if (Previous.isSingleResult())
4767 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
4769 // If there is an identifier, use the location of the identifier as the
4770 // location of the decl, otherwise use the location of the struct/union
4772 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
4774 // Otherwise, create a new declaration. If there is a previous
4775 // declaration of the same entity, the two will be linked via
4779 if (Kind == TagDecl::TK_enum) {
4780 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
4781 // enum X { A, B, C } D; D should chain to X.
4782 New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc,
4783 cast_or_null<EnumDecl>(PrevDecl));
4784 // If this is an undefined enum, warn.
4785 if (TUK != TUK_Definition && !Invalid) {
4786 unsigned DK = getLangOptions().CPlusPlus? diag::err_forward_ref_enum
4787 : diag::ext_forward_ref_enum;
4791 // struct/union/class
4793 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
4794 // struct X { int A; } D; D should chain to X.
4795 if (getLangOptions().CPlusPlus) {
4796 // FIXME: Look for a way to use RecordDecl for simple structs.
4797 New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
4798 cast_or_null<CXXRecordDecl>(PrevDecl));
4800 if (isStdBadAlloc && (!StdBadAlloc || StdBadAlloc->isImplicit()))
4801 StdBadAlloc = cast<CXXRecordDecl>(New);
4803 New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
4804 cast_or_null<RecordDecl>(PrevDecl));
4807 if (Kind != TagDecl::TK_enum) {
4808 // Handle #pragma pack: if the #pragma pack stack has non-default
4809 // alignment, make up a packed attribute for this decl. These
4810 // attributes are checked when the ASTContext lays out the
4813 // It is important for implementing the correct semantics that this
4814 // happen here (in act on tag decl). The #pragma pack stack is
4815 // maintained as a result of parser callbacks which can occur at
4816 // many points during the parsing of a struct declaration (because
4817 // the #pragma tokens are effectively skipped over during the
4818 // parsing of the struct).
4819 if (unsigned Alignment = getPragmaPackAlignment())
4820 New->addAttr(::new (Context) PragmaPackAttr(Alignment * 8));
4823 if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
4824 // C++ [dcl.typedef]p3:
4825 // [...] Similarly, in a given scope, a class or enumeration
4826 // shall not be declared with the same name as a typedef-name
4827 // that is declared in that scope and refers to a type other
4828 // than the class or enumeration itself.
4829 LookupResult Lookup(*this, Name, NameLoc, LookupOrdinaryName,
4831 LookupName(Lookup, S);
4832 TypedefDecl *PrevTypedef = Lookup.getAsSingle<TypedefDecl>();
4833 NamedDecl *PrevTypedefNamed = PrevTypedef;
4834 if (PrevTypedef && isDeclInScope(PrevTypedefNamed, SearchDC, S) &&
4835 Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
4836 Context.getCanonicalType(Context.getTypeDeclType(New))) {
4837 Diag(Loc, diag::err_tag_definition_of_typedef)
4838 << Context.getTypeDeclType(New)
4839 << PrevTypedef->getUnderlyingType();
4840 Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
4845 // If this is a specialization of a member class (of a class template),
4846 // check the specialization.
4847 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
4851 New->setInvalidDecl();
4854 ProcessDeclAttributeList(S, New, Attr);
4856 // If we're declaring or defining a tag in function prototype scope
4857 // in C, note that this type can only be used within the function.
4858 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
4859 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
4861 // Set the lexical context. If the tag has a C++ scope specifier, the
4862 // lexical context will be different from the semantic context.
4863 New->setLexicalDeclContext(CurContext);
4865 // Mark this as a friend decl if applicable.
4866 if (TUK == TUK_Friend)
4867 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty());
4869 // Set the access specifier.
4870 if (!Invalid && TUK != TUK_Friend)
4871 SetMemberAccessSpecifier(New, PrevDecl, AS);
4873 if (TUK == TUK_Definition)
4874 New->startDefinition();
4876 // If this has an identifier, add it to the scope stack.
4877 if (TUK == TUK_Friend) {
4878 // We might be replacing an existing declaration in the lookup tables;
4879 // if so, borrow its access specifier.
4881 New->setAccess(PrevDecl->getAccess());
4883 // Friend tag decls are visible in fairly strange ways.
4884 if (!CurContext->isDependentContext()) {
4885 DeclContext *DC = New->getDeclContext()->getLookupContext();
4886 DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
4887 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
4888 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
4891 S = getNonFieldDeclScope(S);
4892 PushOnScopeChains(New, S);
4894 CurContext->addDecl(New);
4897 // If this is the C FILE type, notify the AST context.
4898 if (IdentifierInfo *II = New->getIdentifier())
4899 if (!New->isInvalidDecl() &&
4900 New->getDeclContext()->getLookupContext()->isTranslationUnit() &&
4902 Context.setFILEDecl(New);
4905 return DeclPtrTy::make(New);
4908 void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) {
4909 AdjustDeclIfTemplate(TagD);
4910 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4912 // Enter the tag context.
4913 PushDeclContext(S, Tag);
4916 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, DeclPtrTy TagD,
4917 SourceLocation LBraceLoc) {
4918 AdjustDeclIfTemplate(TagD);
4919 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD.getAs<Decl>());
4921 FieldCollector->StartClass();
4923 if (!Record->getIdentifier())
4927 // [...] The class-name is also inserted into the scope of the
4928 // class itself; this is known as the injected-class-name. For
4929 // purposes of access checking, the injected-class-name is treated
4930 // as if it were a public member name.
4931 CXXRecordDecl *InjectedClassName
4932 = CXXRecordDecl::Create(Context, Record->getTagKind(),
4933 CurContext, Record->getLocation(),
4934 Record->getIdentifier(),
4935 Record->getTagKeywordLoc(),
4937 InjectedClassName->setImplicit();
4938 InjectedClassName->setAccess(AS_public);
4939 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
4940 InjectedClassName->setDescribedClassTemplate(Template);
4941 PushOnScopeChains(InjectedClassName, S);
4942 assert(InjectedClassName->isInjectedClassName() &&
4943 "Broken injected-class-name");
4946 // Traverses the class and any nested classes, making a note of any
4947 // dynamic classes that have no key function so that we can mark all of
4948 // their virtual member functions as "used" at the end of the translation
4949 // unit. This ensures that all functions needed by the vtable will get
4950 // instantiated/synthesized.
4952 RecordDynamicClassesWithNoKeyFunction(Sema &S, CXXRecordDecl *Record,
4953 SourceLocation Loc) {
4954 // We don't look at dependent or undefined classes.
4955 if (Record->isDependentContext() || !Record->isDefinition())
4958 if (Record->isDynamicClass()) {
4959 const CXXMethodDecl *KeyFunction = S.Context.getKeyFunction(Record);
4962 S.ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(Record,
4965 if ((!KeyFunction || (KeyFunction->getBody() && KeyFunction->isInlined()))
4966 && Record->getLinkage() == ExternalLinkage)
4967 S.Diag(Record->getLocation(), diag::warn_weak_vtable) << Record;
4969 for (DeclContext::decl_iterator D = Record->decls_begin(),
4970 DEnd = Record->decls_end();
4972 if (CXXRecordDecl *Nested = dyn_cast<CXXRecordDecl>(*D))
4973 RecordDynamicClassesWithNoKeyFunction(S, Nested, Loc);
4977 void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD,
4978 SourceLocation RBraceLoc) {
4979 AdjustDeclIfTemplate(TagD);
4980 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4981 Tag->setRBraceLoc(RBraceLoc);
4983 if (isa<CXXRecordDecl>(Tag))
4984 FieldCollector->FinishClass();
4986 // Exit this scope of this tag's definition.
4989 if (isa<CXXRecordDecl>(Tag) && !Tag->getDeclContext()->isRecord())
4990 RecordDynamicClassesWithNoKeyFunction(*this, cast<CXXRecordDecl>(Tag),
4993 // Notify the consumer that we've defined a tag.
4994 Consumer.HandleTagDeclDefinition(Tag);
4997 // Note that FieldName may be null for anonymous bitfields.
4998 bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
4999 QualType FieldTy, const Expr *BitWidth,
5001 // Default to true; that shouldn't confuse checks for emptiness
5005 // C99 6.7.2.1p4 - verify the field type.
5006 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
5007 if (!FieldTy->isDependentType() && !FieldTy->isIntegralType()) {
5008 // Handle incomplete types with specific error.
5009 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
5012 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
5013 << FieldName << FieldTy << BitWidth->getSourceRange();
5014 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
5015 << FieldTy << BitWidth->getSourceRange();
5018 // If the bit-width is type- or value-dependent, don't try to check
5020 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
5024 if (VerifyIntegerConstantExpression(BitWidth, &Value))
5027 if (Value != 0 && ZeroWidth)
5030 // Zero-width bitfield is ok for anonymous field.
5031 if (Value == 0 && FieldName)
5032 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
5034 if (Value.isSigned() && Value.isNegative()) {
5036 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
5037 << FieldName << Value.toString(10);
5038 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
5039 << Value.toString(10);
5042 if (!FieldTy->isDependentType()) {
5043 uint64_t TypeSize = Context.getTypeSize(FieldTy);
5044 if (Value.getZExtValue() > TypeSize) {
5046 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
5047 << FieldName << (unsigned)TypeSize;
5048 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
5049 << (unsigned)TypeSize;
5056 /// ActOnField - Each field of a struct/union/class is passed into this in order
5057 /// to create a FieldDecl object for it.
5058 Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD,
5059 SourceLocation DeclStart,
5060 Declarator &D, ExprTy *BitfieldWidth) {
5061 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()),
5062 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
5064 return DeclPtrTy::make(Res);
5067 /// HandleField - Analyze a field of a C struct or a C++ data member.
5069 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
5070 SourceLocation DeclStart,
5071 Declarator &D, Expr *BitWidth,
5072 AccessSpecifier AS) {
5073 IdentifierInfo *II = D.getIdentifier();
5074 SourceLocation Loc = DeclStart;
5075 if (II) Loc = D.getIdentifierLoc();
5077 TypeSourceInfo *TInfo = 0;
5078 QualType T = GetTypeForDeclarator(D, S, &TInfo);
5079 if (getLangOptions().CPlusPlus)
5080 CheckExtraCXXDefaultArguments(D);
5082 DiagnoseFunctionSpecifiers(D);
5084 if (D.getDeclSpec().isThreadSpecified())
5085 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
5087 NamedDecl *PrevDecl = LookupSingleName(S, II, LookupMemberName,
5090 if (PrevDecl && PrevDecl->isTemplateParameter()) {
5091 // Maybe we will complain about the shadowed template parameter.
5092 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5093 // Just pretend that we didn't see the previous declaration.
5097 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
5101 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
5102 SourceLocation TSSL = D.getSourceRange().getBegin();
5104 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, TSSL,
5106 if (NewFD->isInvalidDecl() && PrevDecl) {
5107 // Don't introduce NewFD into scope; there's already something
5108 // with the same name in the same scope.
5110 PushOnScopeChains(NewFD, S);
5112 Record->addDecl(NewFD);
5117 /// \brief Build a new FieldDecl and check its well-formedness.
5119 /// This routine builds a new FieldDecl given the fields name, type,
5120 /// record, etc. \p PrevDecl should refer to any previous declaration
5121 /// with the same name and in the same scope as the field to be
5124 /// \returns a new FieldDecl.
5126 /// \todo The Declarator argument is a hack. It will be removed once
5127 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
5128 TypeSourceInfo *TInfo,
5129 RecordDecl *Record, SourceLocation Loc,
5130 bool Mutable, Expr *BitWidth,
5131 SourceLocation TSSL,
5132 AccessSpecifier AS, NamedDecl *PrevDecl,
5134 IdentifierInfo *II = Name.getAsIdentifierInfo();
5135 bool InvalidDecl = false;
5136 if (D) InvalidDecl = D->isInvalidType();
5138 // If we receive a broken type, recover by assuming 'int' and
5139 // marking this declaration as invalid.
5145 QualType EltTy = Context.getBaseElementType(T);
5146 if (!EltTy->isDependentType() &&
5147 RequireCompleteType(Loc, EltTy, diag::err_field_incomplete))
5150 // C99 6.7.2.1p8: A member of a structure or union may have any type other
5151 // than a variably modified type.
5152 if (!InvalidDecl && T->isVariablyModifiedType()) {
5153 bool SizeIsNegative;
5154 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
5156 if (!FixedTy.isNull()) {
5157 Diag(Loc, diag::warn_illegal_constant_array_size);
5161 Diag(Loc, diag::err_typecheck_negative_array_size);
5163 Diag(Loc, diag::err_typecheck_field_variable_size);
5168 // Fields can not have abstract class types
5169 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
5170 diag::err_abstract_type_in_decl,
5174 bool ZeroWidth = false;
5175 // If this is declared as a bit-field, check the bit-field.
5176 if (!InvalidDecl && BitWidth &&
5177 VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
5179 DeleteExpr(BitWidth);
5184 FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, TInfo,
5187 NewFD->setInvalidDecl();
5189 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
5190 Diag(Loc, diag::err_duplicate_member) << II;
5191 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5192 NewFD->setInvalidDecl();
5195 if (!InvalidDecl && getLangOptions().CPlusPlus) {
5196 CXXRecordDecl* CXXRecord = cast<CXXRecordDecl>(Record);
5198 if (!T->isPODType())
5199 CXXRecord->setPOD(false);
5201 CXXRecord->setEmpty(false);
5203 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
5204 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
5206 if (!RDecl->hasTrivialConstructor())
5207 CXXRecord->setHasTrivialConstructor(false);
5208 if (!RDecl->hasTrivialCopyConstructor())
5209 CXXRecord->setHasTrivialCopyConstructor(false);
5210 if (!RDecl->hasTrivialCopyAssignment())
5211 CXXRecord->setHasTrivialCopyAssignment(false);
5212 if (!RDecl->hasTrivialDestructor())
5213 CXXRecord->setHasTrivialDestructor(false);
5215 // C++ 9.5p1: An object of a class with a non-trivial
5216 // constructor, a non-trivial copy constructor, a non-trivial
5217 // destructor, or a non-trivial copy assignment operator
5218 // cannot be a member of a union, nor can an array of such
5220 // TODO: C++0x alters this restriction significantly.
5221 if (Record->isUnion()) {
5222 // We check for copy constructors before constructors
5223 // because otherwise we'll never get complaints about
5224 // copy constructors.
5226 const CXXSpecialMember invalid = (CXXSpecialMember) -1;
5228 CXXSpecialMember member;
5229 if (!RDecl->hasTrivialCopyConstructor())
5230 member = CXXCopyConstructor;
5231 else if (!RDecl->hasTrivialConstructor())
5232 member = CXXDefaultConstructor;
5233 else if (!RDecl->hasTrivialCopyAssignment())
5234 member = CXXCopyAssignment;
5235 else if (!RDecl->hasTrivialDestructor())
5236 member = CXXDestructor;
5240 if (member != invalid) {
5241 Diag(Loc, diag::err_illegal_union_member) << Name << member;
5242 DiagnoseNontrivial(RT, member);
5243 NewFD->setInvalidDecl();
5249 // FIXME: We need to pass in the attributes given an AST
5250 // representation, not a parser representation.
5252 // FIXME: What to pass instead of TUScope?
5253 ProcessDeclAttributes(TUScope, NewFD, *D);
5255 if (T.isObjCGCWeak())
5256 Diag(Loc, diag::warn_attribute_weak_on_field);
5258 NewFD->setAccess(AS);
5260 // C++ [dcl.init.aggr]p1:
5261 // An aggregate is an array or a class (clause 9) with [...] no
5262 // private or protected non-static data members (clause 11).
5263 // A POD must be an aggregate.
5264 if (getLangOptions().CPlusPlus &&
5265 (AS == AS_private || AS == AS_protected)) {
5266 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
5267 CXXRecord->setAggregate(false);
5268 CXXRecord->setPOD(false);
5274 /// DiagnoseNontrivial - Given that a class has a non-trivial
5275 /// special member, figure out why.
5276 void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
5278 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
5280 // Check whether the member was user-declared.
5282 case CXXDefaultConstructor:
5283 if (RD->hasUserDeclaredConstructor()) {
5284 typedef CXXRecordDecl::ctor_iterator ctor_iter;
5285 for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
5286 const FunctionDecl *body = 0;
5289 !cast<CXXConstructorDecl>(body)->isImplicitlyDefined(Context)) {
5290 SourceLocation CtorLoc = ci->getLocation();
5291 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5296 assert(0 && "found no user-declared constructors");
5301 case CXXCopyConstructor:
5302 if (RD->hasUserDeclaredCopyConstructor()) {
5303 SourceLocation CtorLoc =
5304 RD->getCopyConstructor(Context, 0)->getLocation();
5305 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5310 case CXXCopyAssignment:
5311 if (RD->hasUserDeclaredCopyAssignment()) {
5312 // FIXME: this should use the location of the copy
5313 // assignment, not the type.
5314 SourceLocation TyLoc = RD->getSourceRange().getBegin();
5315 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
5321 if (RD->hasUserDeclaredDestructor()) {
5322 SourceLocation DtorLoc = RD->getDestructor(Context)->getLocation();
5323 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5329 typedef CXXRecordDecl::base_class_iterator base_iter;
5331 // Virtual bases and members inhibit trivial copying/construction,
5332 // but not trivial destruction.
5333 if (member != CXXDestructor) {
5334 // Check for virtual bases. vbases includes indirect virtual bases,
5335 // so we just iterate through the direct bases.
5336 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
5337 if (bi->isVirtual()) {
5338 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5339 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
5343 // Check for virtual methods.
5344 typedef CXXRecordDecl::method_iterator meth_iter;
5345 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
5347 if (mi->isVirtual()) {
5348 SourceLocation MLoc = mi->getSourceRange().getBegin();
5349 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
5355 bool (CXXRecordDecl::*hasTrivial)() const;
5357 case CXXDefaultConstructor:
5358 hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break;
5359 case CXXCopyConstructor:
5360 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
5361 case CXXCopyAssignment:
5362 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
5364 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
5366 assert(0 && "unexpected special member"); return;
5369 // Check for nontrivial bases (and recurse).
5370 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
5371 const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
5372 assert(BaseRT && "Don't know how to handle dependent bases");
5373 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
5374 if (!(BaseRecTy->*hasTrivial)()) {
5375 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5376 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
5377 DiagnoseNontrivial(BaseRT, member);
5382 // Check for nontrivial members (and recurse).
5383 typedef RecordDecl::field_iterator field_iter;
5384 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
5386 QualType EltTy = Context.getBaseElementType((*fi)->getType());
5387 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
5388 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
5390 if (!(EltRD->*hasTrivial)()) {
5391 SourceLocation FLoc = (*fi)->getLocation();
5392 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
5393 DiagnoseNontrivial(EltRT, member);
5399 assert(0 && "found no explanation for non-trivial member");
5402 /// TranslateIvarVisibility - Translate visibility from a token ID to an
5404 static ObjCIvarDecl::AccessControl
5405 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
5406 switch (ivarVisibility) {
5407 default: assert(0 && "Unknown visitibility kind");
5408 case tok::objc_private: return ObjCIvarDecl::Private;
5409 case tok::objc_public: return ObjCIvarDecl::Public;
5410 case tok::objc_protected: return ObjCIvarDecl::Protected;
5411 case tok::objc_package: return ObjCIvarDecl::Package;
5415 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
5416 /// in order to create an IvarDecl object for it.
5417 Sema::DeclPtrTy Sema::ActOnIvar(Scope *S,
5418 SourceLocation DeclStart,
5420 Declarator &D, ExprTy *BitfieldWidth,
5421 tok::ObjCKeywordKind Visibility) {
5423 IdentifierInfo *II = D.getIdentifier();
5424 Expr *BitWidth = (Expr*)BitfieldWidth;
5425 SourceLocation Loc = DeclStart;
5426 if (II) Loc = D.getIdentifierLoc();
5428 // FIXME: Unnamed fields can be handled in various different ways, for
5429 // example, unnamed unions inject all members into the struct namespace!
5431 TypeSourceInfo *TInfo = 0;
5432 QualType T = GetTypeForDeclarator(D, S, &TInfo);
5435 // 6.7.2.1p3, 6.7.2.1p4
5436 if (VerifyBitField(Loc, II, T, BitWidth)) {
5438 DeleteExpr(BitWidth);
5448 // C99 6.7.2.1p8: A member of a structure or union may have any type other
5449 // than a variably modified type.
5450 if (T->isVariablyModifiedType()) {
5451 Diag(Loc, diag::err_typecheck_ivar_variable_size);
5455 // Get the visibility (access control) for this ivar.
5456 ObjCIvarDecl::AccessControl ac =
5457 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
5458 : ObjCIvarDecl::None;
5459 // Must set ivar's DeclContext to its enclosing interface.
5460 Decl *EnclosingDecl = IntfDecl.getAs<Decl>();
5461 DeclContext *EnclosingContext;
5462 if (ObjCImplementationDecl *IMPDecl =
5463 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
5464 // Case of ivar declared in an implementation. Context is that of its class.
5465 ObjCInterfaceDecl* IDecl = IMPDecl->getClassInterface();
5466 assert(IDecl && "No class- ActOnIvar");
5467 EnclosingContext = cast_or_null<DeclContext>(IDecl);
5469 EnclosingContext = dyn_cast<DeclContext>(EnclosingDecl);
5470 assert(EnclosingContext && "null DeclContext for ivar - ActOnIvar");
5472 // Construct the decl.
5473 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context,
5474 EnclosingContext, Loc, II, T,
5475 TInfo, ac, (Expr *)BitfieldWidth);
5478 NamedDecl *PrevDecl = LookupSingleName(S, II, LookupMemberName,
5480 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
5481 && !isa<TagDecl>(PrevDecl)) {
5482 Diag(Loc, diag::err_duplicate_member) << II;
5483 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5484 NewID->setInvalidDecl();
5488 // Process attributes attached to the ivar.
5489 ProcessDeclAttributes(S, NewID, D);
5491 if (D.isInvalidType())
5492 NewID->setInvalidDecl();
5495 // FIXME: When interfaces are DeclContexts, we'll need to add
5496 // these to the interface.
5497 S->AddDecl(DeclPtrTy::make(NewID));
5498 IdResolver.AddDecl(NewID);
5501 return DeclPtrTy::make(NewID);
5504 void Sema::ActOnFields(Scope* S,
5505 SourceLocation RecLoc, DeclPtrTy RecDecl,
5506 DeclPtrTy *Fields, unsigned NumFields,
5507 SourceLocation LBrac, SourceLocation RBrac,
5508 AttributeList *Attr) {
5509 Decl *EnclosingDecl = RecDecl.getAs<Decl>();
5510 assert(EnclosingDecl && "missing record or interface decl");
5512 // If the decl this is being inserted into is invalid, then it may be a
5513 // redeclaration or some other bogus case. Don't try to add fields to it.
5514 if (EnclosingDecl->isInvalidDecl()) {
5515 // FIXME: Deallocate fields?
5520 // Verify that all the fields are okay.
5521 unsigned NumNamedMembers = 0;
5522 llvm::SmallVector<FieldDecl*, 32> RecFields;
5524 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
5525 for (unsigned i = 0; i != NumFields; ++i) {
5526 FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>());
5528 // Get the type for the field.
5529 Type *FDTy = FD->getType().getTypePtr();
5531 if (!FD->isAnonymousStructOrUnion()) {
5532 // Remember all fields written by the user.
5533 RecFields.push_back(FD);
5536 // If the field is already invalid for some reason, don't emit more
5537 // diagnostics about it.
5538 if (FD->isInvalidDecl()) {
5539 EnclosingDecl->setInvalidDecl();
5544 // A structure or union shall not contain a member with
5545 // incomplete or function type (hence, a structure shall not
5546 // contain an instance of itself, but may contain a pointer to
5547 // an instance of itself), except that the last member of a
5548 // structure with more than one named member may have incomplete
5549 // array type; such a structure (and any union containing,
5550 // possibly recursively, a member that is such a structure)
5551 // shall not be a member of a structure or an element of an
5553 if (FDTy->isFunctionType()) {
5554 // Field declared as a function.
5555 Diag(FD->getLocation(), diag::err_field_declared_as_function)
5556 << FD->getDeclName();
5557 FD->setInvalidDecl();
5558 EnclosingDecl->setInvalidDecl();
5560 } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 &&
5561 Record && Record->isStruct()) {
5562 // Flexible array member.
5563 if (NumNamedMembers < 1) {
5564 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
5565 << FD->getDeclName();
5566 FD->setInvalidDecl();
5567 EnclosingDecl->setInvalidDecl();
5570 // Okay, we have a legal flexible array member at the end of the struct.
5572 Record->setHasFlexibleArrayMember(true);
5573 } else if (!FDTy->isDependentType() &&
5574 RequireCompleteType(FD->getLocation(), FD->getType(),
5575 diag::err_field_incomplete)) {
5577 FD->setInvalidDecl();
5578 EnclosingDecl->setInvalidDecl();
5580 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
5581 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
5582 // If this is a member of a union, then entire union becomes "flexible".
5583 if (Record && Record->isUnion()) {
5584 Record->setHasFlexibleArrayMember(true);
5586 // If this is a struct/class and this is not the last element, reject
5587 // it. Note that GCC supports variable sized arrays in the middle of
5589 if (i != NumFields-1)
5590 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
5591 << FD->getDeclName() << FD->getType();
5593 // We support flexible arrays at the end of structs in
5594 // other structs as an extension.
5595 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
5596 << FD->getDeclName();
5598 Record->setHasFlexibleArrayMember(true);
5602 if (Record && FDTTy->getDecl()->hasObjectMember())
5603 Record->setHasObjectMember(true);
5604 } else if (FDTy->isObjCInterfaceType()) {
5605 /// A field cannot be an Objective-c object
5606 Diag(FD->getLocation(), diag::err_statically_allocated_object);
5607 FD->setInvalidDecl();
5608 EnclosingDecl->setInvalidDecl();
5610 } else if (getLangOptions().ObjC1 &&
5611 getLangOptions().getGCMode() != LangOptions::NonGC &&
5613 (FD->getType()->isObjCObjectPointerType() ||
5614 FD->getType().isObjCGCStrong()))
5615 Record->setHasObjectMember(true);
5616 // Keep track of the number of named members.
5617 if (FD->getIdentifier())
5621 // Okay, we successfully defined 'Record'.
5623 Record->completeDefinition();
5625 ObjCIvarDecl **ClsFields =
5626 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
5627 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
5628 ID->setIVarList(ClsFields, RecFields.size(), Context);
5629 ID->setLocEnd(RBrac);
5630 // Add ivar's to class's DeclContext.
5631 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
5632 ClsFields[i]->setLexicalDeclContext(ID);
5633 ID->addDecl(ClsFields[i]);
5635 // Must enforce the rule that ivars in the base classes may not be
5637 if (ID->getSuperClass()) {
5638 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
5639 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
5640 ObjCIvarDecl* Ivar = (*IVI);
5642 if (IdentifierInfo *II = Ivar->getIdentifier()) {
5643 ObjCIvarDecl* prevIvar =
5644 ID->getSuperClass()->lookupInstanceVariable(II);
5646 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
5647 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
5652 } else if (ObjCImplementationDecl *IMPDecl =
5653 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
5654 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
5655 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
5656 // Ivar declared in @implementation never belongs to the implementation.
5657 // Only it is in implementation's lexical context.
5658 ClsFields[I]->setLexicalDeclContext(IMPDecl);
5659 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
5664 ProcessDeclAttributeList(S, Record, Attr);
5667 /// \brief Determine whether the given integral value is representable within
5668 /// the given type T.
5669 static bool isRepresentableIntegerValue(ASTContext &Context,
5670 llvm::APSInt &Value,
5672 assert(T->isIntegralType() && "Integral type required!");
5673 unsigned BitWidth = Context.getTypeSize(T);
5675 if (Value.isUnsigned() || Value.isNonNegative())
5676 return Value.getActiveBits() < BitWidth;
5678 return Value.getMinSignedBits() <= BitWidth;
5681 // \brief Given an integral type, return the next larger integral type
5682 // (or a NULL type of no such type exists).
5683 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
5684 // FIXME: Int128/UInt128 support, which also needs to be introduced into
5685 // enum checking below.
5686 assert(T->isIntegralType() && "Integral type required!");
5687 const unsigned NumTypes = 4;
5688 QualType SignedIntegralTypes[NumTypes] = {
5689 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
5691 QualType UnsignedIntegralTypes[NumTypes] = {
5692 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
5693 Context.UnsignedLongLongTy
5696 unsigned BitWidth = Context.getTypeSize(T);
5697 QualType *Types = T->isSignedIntegerType()? SignedIntegralTypes
5698 : UnsignedIntegralTypes;
5699 for (unsigned I = 0; I != NumTypes; ++I)
5700 if (Context.getTypeSize(Types[I]) > BitWidth)
5706 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
5707 EnumConstantDecl *LastEnumConst,
5708 SourceLocation IdLoc,
5711 Expr *Val = (Expr *)val.get();
5713 unsigned IntWidth = Context.Target.getIntWidth();
5714 llvm::APSInt EnumVal(IntWidth);
5717 if (Enum->isDependentType())
5718 EltTy = Context.DependentTy;
5720 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
5721 SourceLocation ExpLoc;
5722 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
5725 if (!getLangOptions().CPlusPlus) {
5727 // The expression that defines the value of an enumeration constant
5728 // shall be an integer constant expression that has a value
5729 // representable as an int.
5731 // Complain if the value is not representable in an int.
5732 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
5733 Diag(IdLoc, diag::ext_enum_value_not_int)
5734 << EnumVal.toString(10) << Val->getSourceRange()
5735 << EnumVal.isNonNegative();
5736 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
5737 // Force the type of the expression to 'int'.
5738 ImpCastExprToType(Val, Context.IntTy, CastExpr::CK_IntegralCast);
5740 if (Val != val.get()) {
5747 // C++0x [dcl.enum]p5:
5748 // If the underlying type is not fixed, the type of each enumerator
5749 // is the type of its initializing value:
5750 // - If an initializer is specified for an enumerator, the
5751 // initializing value has the same type as the expression.
5752 EltTy = Val->getType();
5758 if (Enum->isDependentType())
5759 EltTy = Context.DependentTy;
5760 else if (!LastEnumConst) {
5761 // C++0x [dcl.enum]p5:
5762 // If the underlying type is not fixed, the type of each enumerator
5763 // is the type of its initializing value:
5764 // - If no initializer is specified for the first enumerator, the
5765 // initializing value has an unspecified integral type.
5767 // GCC uses 'int' for its unspecified integral type, as does
5769 EltTy = Context.IntTy;
5771 // Assign the last value + 1.
5772 EnumVal = LastEnumConst->getInitVal();
5774 EltTy = LastEnumConst->getType();
5776 // Check for overflow on increment.
5777 if (EnumVal < LastEnumConst->getInitVal()) {
5778 // C++0x [dcl.enum]p5:
5779 // If the underlying type is not fixed, the type of each enumerator
5780 // is the type of its initializing value:
5782 // - Otherwise the type of the initializing value is the same as
5783 // the type of the initializing value of the preceding enumerator
5784 // unless the incremented value is not representable in that type,
5785 // in which case the type is an unspecified integral type
5786 // sufficient to contain the incremented value. If no such type
5787 // exists, the program is ill-formed.
5788 QualType T = getNextLargerIntegralType(Context, EltTy);
5790 // There is no integral type larger enough to represent this
5791 // value. Complain, then allow the value to wrap around.
5792 EnumVal = LastEnumConst->getInitVal();
5793 EnumVal.zext(EnumVal.getBitWidth() * 2);
5794 Diag(IdLoc, diag::warn_enumerator_too_large)
5795 << EnumVal.toString(10);
5800 // Retrieve the last enumerator's value, extent that type to the
5801 // type that is supposed to be large enough to represent the incremented
5802 // value, then increment.
5803 EnumVal = LastEnumConst->getInitVal();
5804 EnumVal.setIsSigned(EltTy->isSignedIntegerType());
5805 EnumVal.zextOrTrunc(Context.getTypeSize(EltTy));
5808 // If we're not in C++, diagnose the overflow of enumerator values,
5809 // which in C99 means that the enumerator value is not representable in
5810 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
5811 // permits enumerator values that are representable in some larger
5813 if (!getLangOptions().CPlusPlus && !T.isNull())
5814 Diag(IdLoc, diag::warn_enum_value_overflow);
5815 } else if (!getLangOptions().CPlusPlus &&
5816 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
5817 // Enforce C99 6.7.2.2p2 even when we compute the next value.
5818 Diag(IdLoc, diag::ext_enum_value_not_int)
5819 << EnumVal.toString(10) << 1;
5824 if (!Enum->isDependentType()) {
5825 // Make the enumerator value match the signedness and size of the
5826 // enumerator's type.
5827 EnumVal.zextOrTrunc(Context.getTypeSize(EltTy));
5828 EnumVal.setIsSigned(EltTy->isSignedIntegerType());
5832 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
5837 Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl,
5838 DeclPtrTy lastEnumConst,
5839 SourceLocation IdLoc,
5841 SourceLocation EqualLoc, ExprTy *val) {
5842 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>());
5843 EnumConstantDecl *LastEnumConst =
5844 cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>());
5845 Expr *Val = static_cast<Expr*>(val);
5847 // The scope passed in may not be a decl scope. Zip up the scope tree until
5848 // we find one that is.
5849 S = getNonFieldDeclScope(S);
5851 // Verify that there isn't already something declared with this name in this
5853 NamedDecl *PrevDecl = LookupSingleName(S, Id, LookupOrdinaryName,
5855 if (PrevDecl && PrevDecl->isTemplateParameter()) {
5856 // Maybe we will complain about the shadowed template parameter.
5857 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
5858 // Just pretend that we didn't see the previous declaration.
5863 // When in C++, we may get a TagDecl with the same name; in this case the
5864 // enum constant will 'hide' the tag.
5865 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
5866 "Received TagDecl when not in C++!");
5867 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
5868 if (isa<EnumConstantDecl>(PrevDecl))
5869 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
5871 Diag(IdLoc, diag::err_redefinition) << Id;
5872 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5873 if (Val) Val->Destroy(Context);
5878 EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst,
5879 IdLoc, Id, Owned(Val));
5881 // Register this decl in the current scope stack.
5883 New->setAccess(TheEnumDecl->getAccess());
5884 PushOnScopeChains(New, S);
5887 return DeclPtrTy::make(New);
5890 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
5891 SourceLocation RBraceLoc, DeclPtrTy EnumDeclX,
5892 DeclPtrTy *Elements, unsigned NumElements,
5893 Scope *S, AttributeList *Attr) {
5894 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>());
5895 QualType EnumType = Context.getTypeDeclType(Enum);
5898 ProcessDeclAttributeList(S, Enum, Attr);
5900 if (Enum->isDependentType()) {
5901 for (unsigned i = 0; i != NumElements; ++i) {
5902 EnumConstantDecl *ECD =
5903 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
5906 ECD->setType(EnumType);
5909 Enum->completeDefinition(Context.DependentTy, Context.DependentTy);
5913 // TODO: If the result value doesn't fit in an int, it must be a long or long
5914 // long value. ISO C does not support this, but GCC does as an extension,
5916 unsigned IntWidth = Context.Target.getIntWidth();
5917 unsigned CharWidth = Context.Target.getCharWidth();
5918 unsigned ShortWidth = Context.Target.getShortWidth();
5920 // Verify that all the values are okay, compute the size of the values, and
5921 // reverse the list.
5922 unsigned NumNegativeBits = 0;
5923 unsigned NumPositiveBits = 0;
5925 // Keep track of whether all elements have type int.
5926 bool AllElementsInt = true;
5928 for (unsigned i = 0; i != NumElements; ++i) {
5929 EnumConstantDecl *ECD =
5930 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
5931 if (!ECD) continue; // Already issued a diagnostic.
5933 const llvm::APSInt &InitVal = ECD->getInitVal();
5935 // Keep track of the size of positive and negative values.
5936 if (InitVal.isUnsigned() || InitVal.isNonNegative())
5937 NumPositiveBits = std::max(NumPositiveBits,
5938 (unsigned)InitVal.getActiveBits());
5940 NumNegativeBits = std::max(NumNegativeBits,
5941 (unsigned)InitVal.getMinSignedBits());
5943 // Keep track of whether every enum element has type int (very commmon).
5945 AllElementsInt = ECD->getType() == Context.IntTy;
5948 // Figure out the type that should be used for this enum.
5949 // FIXME: Support -fshort-enums.
5953 // C++0x N3000 [conv.prom]p3:
5954 // An rvalue of an unscoped enumeration type whose underlying
5955 // type is not fixed can be converted to an rvalue of the first
5956 // of the following types that can represent all the values of
5957 // the enumeration: int, unsigned int, long int, unsigned long
5958 // int, long long int, or unsigned long long int.
5960 // An identifier declared as an enumeration constant has type int.
5961 // The C99 rule is modified by a gcc extension
5962 QualType BestPromotionType;
5964 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
5966 if (NumNegativeBits) {
5967 // If there is a negative value, figure out the smallest integer type (of
5968 // int/long/longlong) that fits.
5969 // If it's packed, check also if it fits a char or a short.
5970 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
5971 BestType = Context.SignedCharTy;
5972 BestWidth = CharWidth;
5973 } else if (Packed && NumNegativeBits <= ShortWidth &&
5974 NumPositiveBits < ShortWidth) {
5975 BestType = Context.ShortTy;
5976 BestWidth = ShortWidth;
5977 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5978 BestType = Context.IntTy;
5979 BestWidth = IntWidth;
5981 BestWidth = Context.Target.getLongWidth();
5983 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5984 BestType = Context.LongTy;
5986 BestWidth = Context.Target.getLongLongWidth();
5988 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5989 Diag(Enum->getLocation(), diag::warn_enum_too_large);
5990 BestType = Context.LongLongTy;
5993 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
5995 // If there is no negative value, figure out the smallest type that fits
5996 // all of the enumerator values.
5997 // If it's packed, check also if it fits a char or a short.
5998 if (Packed && NumPositiveBits <= CharWidth) {
5999 BestType = Context.UnsignedCharTy;
6000 BestPromotionType = Context.IntTy;
6001 BestWidth = CharWidth;
6002 } else if (Packed && NumPositiveBits <= ShortWidth) {
6003 BestType = Context.UnsignedShortTy;
6004 BestPromotionType = Context.IntTy;
6005 BestWidth = ShortWidth;
6006 } else if (NumPositiveBits <= IntWidth) {
6007 BestType = Context.UnsignedIntTy;
6008 BestWidth = IntWidth;
6010 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6011 ? Context.UnsignedIntTy : Context.IntTy;
6012 } else if (NumPositiveBits <=
6013 (BestWidth = Context.Target.getLongWidth())) {
6014 BestType = Context.UnsignedLongTy;
6016 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6017 ? Context.UnsignedLongTy : Context.LongTy;
6019 BestWidth = Context.Target.getLongLongWidth();
6020 assert(NumPositiveBits <= BestWidth &&
6021 "How could an initializer get larger than ULL?");
6022 BestType = Context.UnsignedLongLongTy;
6024 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6025 ? Context.UnsignedLongLongTy : Context.LongLongTy;
6029 // Loop over all of the enumerator constants, changing their types to match
6030 // the type of the enum if needed.
6031 for (unsigned i = 0; i != NumElements; ++i) {
6032 EnumConstantDecl *ECD =
6033 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
6034 if (!ECD) continue; // Already issued a diagnostic.
6036 // Standard C says the enumerators have int type, but we allow, as an
6037 // extension, the enumerators to be larger than int size. If each
6038 // enumerator value fits in an int, type it as an int, otherwise type it the
6039 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
6040 // that X has type 'int', not 'unsigned'.
6042 // Determine whether the value fits into an int.
6043 llvm::APSInt InitVal = ECD->getInitVal();
6045 // If it fits into an integer type, force it. Otherwise force it to match
6046 // the enum decl type.
6050 if (!getLangOptions().CPlusPlus &&
6051 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
6052 NewTy = Context.IntTy;
6053 NewWidth = IntWidth;
6055 } else if (ECD->getType() == BestType) {
6056 // Already the right type!
6057 if (getLangOptions().CPlusPlus)
6058 // C++ [dcl.enum]p4: Following the closing brace of an
6059 // enum-specifier, each enumerator has the type of its
6061 ECD->setType(EnumType);
6065 NewWidth = BestWidth;
6066 NewSign = BestType->isSignedIntegerType();
6069 // Adjust the APSInt value.
6070 InitVal.extOrTrunc(NewWidth);
6071 InitVal.setIsSigned(NewSign);
6072 ECD->setInitVal(InitVal);
6074 // Adjust the Expr initializer and type.
6075 if (ECD->getInitExpr())
6076 ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy,
6077 CastExpr::CK_IntegralCast,
6079 /*isLvalue=*/false));
6080 if (getLangOptions().CPlusPlus)
6081 // C++ [dcl.enum]p4: Following the closing brace of an
6082 // enum-specifier, each enumerator has the type of its
6084 ECD->setType(EnumType);
6086 ECD->setType(NewTy);
6089 Enum->completeDefinition(BestType, BestPromotionType);
6092 Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
6094 StringLiteral *AsmString = cast<StringLiteral>(expr.takeAs<Expr>());
6096 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
6098 CurContext->addDecl(New);
6099 return DeclPtrTy::make(New);
6102 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
6103 SourceLocation PragmaLoc,
6104 SourceLocation NameLoc) {
6105 Decl *PrevDecl = LookupSingleName(TUScope, Name, LookupOrdinaryName);
6108 PrevDecl->addAttr(::new (Context) WeakAttr());
6110 (void)WeakUndeclaredIdentifiers.insert(
6111 std::pair<IdentifierInfo*,WeakInfo>
6112 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
6116 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
6117 IdentifierInfo* AliasName,
6118 SourceLocation PragmaLoc,
6119 SourceLocation NameLoc,
6120 SourceLocation AliasNameLoc) {
6121 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, LookupOrdinaryName);
6122 WeakInfo W = WeakInfo(Name, NameLoc);
6125 if (!PrevDecl->hasAttr<AliasAttr>())
6126 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
6127 DeclApplyPragmaWeak(TUScope, ND, W);
6129 (void)WeakUndeclaredIdentifiers.insert(
6130 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));