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/AST/APValue.h"
18 #include "clang/AST/ASTConsumer.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/Analysis/CFG.h"
21 #include "clang/AST/CXXInheritance.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/StmtCXX.h"
26 #include "clang/AST/StmtObjC.h"
27 #include "clang/Parse/DeclSpec.h"
28 #include "clang/Parse/ParseDiagnostic.h"
29 #include "clang/Parse/Template.h"
30 #include "clang/Basic/PartialDiagnostic.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetInfo.h"
33 // FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
34 #include "clang/Lex/Preprocessor.h"
35 #include "clang/Lex/HeaderSearch.h"
36 #include "llvm/ADT/BitVector.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/ADT/Triple.h"
43 using namespace clang;
45 /// getDeclName - Return a pretty name for the specified decl if possible, or
46 /// an empty string if not. This is used for pretty crash reporting.
47 std::string Sema::getDeclName(DeclPtrTy d) {
48 Decl *D = d.getAs<Decl>();
49 if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(D))
50 return DN->getQualifiedNameAsString();
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(DeclPtrTy Ptr) {
55 return DeclGroupPtrTy::make(DeclGroupRef(Ptr.getAs<Decl>()));
58 /// \brief If the identifier refers to a type name within this scope,
59 /// return the declaration of that type.
61 /// This routine performs ordinary name lookup of the identifier II
62 /// within the given scope, with optional C++ scope specifier SS, to
63 /// determine whether the name refers to a type. If so, returns an
64 /// opaque pointer (actually a QualType) corresponding to that
65 /// type. Otherwise, returns NULL.
67 /// If name lookup results in an ambiguity, this routine will complain
68 /// and then return NULL.
69 Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
70 Scope *S, const CXXScopeSpec *SS,
72 TypeTy *ObjectTypePtr) {
73 // Determine where we will perform name lookup.
74 DeclContext *LookupCtx = 0;
76 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
77 if (ObjectType->isRecordType())
78 LookupCtx = computeDeclContext(ObjectType);
79 } else if (SS && SS->isSet()) {
80 LookupCtx = computeDeclContext(*SS, false);
83 if (isDependentScopeSpecifier(*SS)) {
85 // A qualified-id that refers to a type and in which the
86 // nested-name-specifier depends on a template-parameter (14.6.2)
87 // shall be prefixed by the keyword typename to indicate that the
88 // qualified-id denotes a type, forming an
89 // elaborated-type-specifier (7.1.5.3).
91 // We therefore do not perform any name lookup if the result would
92 // refer to a member of an unknown specialization.
96 // We know from the grammar that this name refers to a type, so build a
97 // TypenameType node to describe the type.
98 // FIXME: Record somewhere that this TypenameType node has no "typename"
99 // keyword associated with it.
100 return CheckTypenameType((NestedNameSpecifier *)SS->getScopeRep(),
101 II, SS->getRange()).getAsOpaquePtr();
107 if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(*SS))
111 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
112 // lookup for class-names.
113 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
115 LookupResult Result(*this, &II, NameLoc, Kind);
117 // Perform "qualified" name lookup into the declaration context we
118 // computed, which is either the type of the base of a member access
119 // expression or the declaration context associated with a prior
120 // nested-name-specifier.
121 LookupQualifiedName(Result, LookupCtx);
123 if (ObjectTypePtr && Result.empty()) {
124 // C++ [basic.lookup.classref]p3:
125 // If the unqualified-id is ~type-name, the type-name is looked up
126 // in the context of the entire postfix-expression. If the type T of
127 // the object expression is of a class type C, the type-name is also
128 // looked up in the scope of class C. At least one of the lookups shall
129 // find a name that refers to (possibly cv-qualified) T.
130 LookupName(Result, S);
133 // Perform unqualified name lookup.
134 LookupName(Result, S);
137 NamedDecl *IIDecl = 0;
138 switch (Result.getResultKind()) {
139 case LookupResult::NotFound:
140 case LookupResult::FoundOverloaded:
141 case LookupResult::FoundUnresolvedValue:
144 case LookupResult::Ambiguous:
145 // Recover from type-hiding ambiguities by hiding the type. We'll
146 // do the lookup again when looking for an object, and we can
147 // diagnose the error then. If we don't do this, then the error
148 // about hiding the type will be immediately followed by an error
149 // that only makes sense if the identifier was treated like a type.
150 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
151 Result.suppressDiagnostics();
155 // Look to see if we have a type anywhere in the list of results.
156 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
157 Res != ResEnd; ++Res) {
158 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
160 (*Res)->getLocation().getRawEncoding() <
161 IIDecl->getLocation().getRawEncoding())
167 // None of the entities we found is a type, so there is no way
168 // to even assume that the result is a type. In this case, don't
169 // complain about the ambiguity. The parser will either try to
170 // perform this lookup again (e.g., as an object name), which
171 // will produce the ambiguity, or will complain that it expected
173 Result.suppressDiagnostics();
177 // We found a type within the ambiguous lookup; diagnose the
178 // ambiguity and then return that type. This might be the right
179 // answer, or it might not be, but it suppresses any attempt to
180 // perform the name lookup again.
183 case LookupResult::Found:
184 IIDecl = Result.getFoundDecl();
188 assert(IIDecl && "Didn't find decl");
191 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
192 DiagnoseUseOfDecl(IIDecl, NameLoc);
194 // C++ [temp.local]p2:
195 // Within the scope of a class template specialization or
196 // partial specialization, when the injected-class-name is
197 // not followed by a <, it is equivalent to the
198 // injected-class-name followed by the template-argument s
199 // of the class template specialization or partial
200 // specialization enclosed in <>.
201 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD))
202 if (RD->isInjectedClassName())
203 if (ClassTemplateDecl *Template = RD->getDescribedClassTemplate())
204 T = Template->getInjectedClassNameType(Context);
207 T = Context.getTypeDeclType(TD);
210 T = getQualifiedNameType(*SS, T);
212 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
213 T = Context.getObjCInterfaceType(IDecl);
214 } else if (UnresolvedUsingTypenameDecl *UUDecl =
215 dyn_cast<UnresolvedUsingTypenameDecl>(IIDecl)) {
216 // FIXME: preserve source structure information.
217 T = Context.getTypenameType(UUDecl->getTargetNestedNameSpecifier(), &II);
219 // If it's not plausibly a type, suppress diagnostics.
220 Result.suppressDiagnostics();
224 return T.getAsOpaquePtr();
227 /// isTagName() - This method is called *for error recovery purposes only*
228 /// to determine if the specified name is a valid tag name ("struct foo"). If
229 /// so, this returns the TST for the tag corresponding to it (TST_enum,
230 /// TST_union, TST_struct, TST_class). This is used to diagnose cases in C
231 /// where the user forgot to specify the tag.
232 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
233 // Do a tag name lookup in this scope.
234 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
235 LookupName(R, S, false);
236 R.suppressDiagnostics();
237 if (R.getResultKind() == LookupResult::Found)
238 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
239 switch (TD->getTagKind()) {
240 case TagDecl::TK_struct: return DeclSpec::TST_struct;
241 case TagDecl::TK_union: return DeclSpec::TST_union;
242 case TagDecl::TK_class: return DeclSpec::TST_class;
243 case TagDecl::TK_enum: return DeclSpec::TST_enum;
247 return DeclSpec::TST_unspecified;
250 bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
251 SourceLocation IILoc,
253 const CXXScopeSpec *SS,
254 TypeTy *&SuggestedType) {
255 // We don't have anything to suggest (yet).
258 // There may have been a typo in the name of the type. Look up typo
259 // results, in case we have something that we can suggest.
260 LookupResult Lookup(*this, &II, IILoc, LookupOrdinaryName,
261 NotForRedeclaration);
263 // FIXME: It would be nice if we could correct for typos in built-in
264 // names, such as "itn" for "int".
266 if (CorrectTypo(Lookup, S, SS) && Lookup.isSingleResult()) {
267 NamedDecl *Result = Lookup.getAsSingle<NamedDecl>();
268 if ((isa<TypeDecl>(Result) || isa<ObjCInterfaceDecl>(Result)) &&
269 !Result->isInvalidDecl()) {
270 // We found a similarly-named type or interface; suggest that.
271 if (!SS || !SS->isSet())
272 Diag(IILoc, diag::err_unknown_typename_suggest)
273 << &II << Lookup.getLookupName()
274 << CodeModificationHint::CreateReplacement(SourceRange(IILoc),
275 Result->getNameAsString());
276 else if (DeclContext *DC = computeDeclContext(*SS, false))
277 Diag(IILoc, diag::err_unknown_nested_typename_suggest)
278 << &II << DC << Lookup.getLookupName() << SS->getRange()
279 << CodeModificationHint::CreateReplacement(SourceRange(IILoc),
280 Result->getNameAsString());
282 llvm_unreachable("could not have corrected a typo here");
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->isUsed() || D->hasAttr<UnusedAttr>())
516 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
517 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
518 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
519 if (!RD->hasTrivialConstructor())
521 if (!RD->hasTrivialDestructor())
527 return (isa<VarDecl>(D) && !isa<ParmVarDecl>(D) &&
528 !isa<ImplicitParamDecl>(D) &&
529 D->getDeclContext()->isFunctionOrMethod());
532 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
533 if (S->decl_empty()) return;
534 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
535 "Scope shouldn't contain decls!");
537 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
539 Decl *TmpD = (*I).getAs<Decl>();
540 assert(TmpD && "This decl didn't get pushed??");
542 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
543 NamedDecl *D = cast<NamedDecl>(TmpD);
545 if (!D->getDeclName()) continue;
547 // Diagnose unused variables in this scope.
548 if (ShouldDiagnoseUnusedDecl(D))
549 Diag(D->getLocation(), diag::warn_unused_variable) << D->getDeclName();
551 // Remove this name from our lexical scope.
552 IdResolver.RemoveDecl(D);
556 /// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
557 /// return 0 if one not found.
558 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
559 // The third "scope" argument is 0 since we aren't enabling lazy built-in
560 // creation from this context.
561 NamedDecl *IDecl = LookupSingleName(TUScope, Id, LookupOrdinaryName);
563 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
566 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
567 /// from S, where a non-field would be declared. This routine copes
568 /// with the difference between C and C++ scoping rules in structs and
569 /// unions. For example, the following code is well-formed in C but
570 /// ill-formed in C++:
581 /// For the declaration of BAR, this routine will return a different
582 /// scope. The scope S will be the scope of the unnamed enumeration
583 /// within S6. In C++, this routine will return the scope associated
584 /// with S6, because the enumeration's scope is a transparent
585 /// context but structures can contain non-field names. In C, this
586 /// routine will return the translation unit scope, since the
587 /// enumeration's scope is a transparent context and structures cannot
588 /// contain non-field names.
589 Scope *Sema::getNonFieldDeclScope(Scope *S) {
590 while (((S->getFlags() & Scope::DeclScope) == 0) ||
592 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
593 (S->isClassScope() && !getLangOptions().CPlusPlus))
598 void Sema::InitBuiltinVaListType() {
599 if (!Context.getBuiltinVaListType().isNull())
602 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
603 NamedDecl *VaDecl = LookupSingleName(TUScope, VaIdent, LookupOrdinaryName);
604 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
605 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
608 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
609 /// file scope. lazily create a decl for it. ForRedeclaration is true
610 /// if we're creating this built-in in anticipation of redeclaring the
612 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
613 Scope *S, bool ForRedeclaration,
614 SourceLocation Loc) {
615 Builtin::ID BID = (Builtin::ID)bid;
617 if (Context.BuiltinInfo.hasVAListUse(BID))
618 InitBuiltinVaListType();
620 ASTContext::GetBuiltinTypeError Error;
621 QualType R = Context.GetBuiltinType(BID, Error);
623 case ASTContext::GE_None:
627 case ASTContext::GE_Missing_stdio:
628 if (ForRedeclaration)
629 Diag(Loc, diag::err_implicit_decl_requires_stdio)
630 << Context.BuiltinInfo.GetName(BID);
633 case ASTContext::GE_Missing_setjmp:
634 if (ForRedeclaration)
635 Diag(Loc, diag::err_implicit_decl_requires_setjmp)
636 << Context.BuiltinInfo.GetName(BID);
640 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
641 Diag(Loc, diag::ext_implicit_lib_function_decl)
642 << Context.BuiltinInfo.GetName(BID)
644 if (Context.BuiltinInfo.getHeaderName(BID) &&
645 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl)
646 != Diagnostic::Ignored)
647 Diag(Loc, diag::note_please_include_header)
648 << Context.BuiltinInfo.getHeaderName(BID)
649 << Context.BuiltinInfo.GetName(BID);
652 FunctionDecl *New = FunctionDecl::Create(Context,
653 Context.getTranslationUnitDecl(),
654 Loc, II, R, /*TInfo=*/0,
655 FunctionDecl::Extern, false,
656 /*hasPrototype=*/true);
659 // Create Decl objects for each parameter, adding them to the
661 if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
662 llvm::SmallVector<ParmVarDecl*, 16> Params;
663 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
664 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
665 FT->getArgType(i), /*TInfo=*/0,
667 New->setParams(Context, Params.data(), Params.size());
670 AddKnownFunctionAttributes(New);
672 // TUScope is the translation-unit scope to insert this function into.
673 // FIXME: This is hideous. We need to teach PushOnScopeChains to
674 // relate Scopes to DeclContexts, and probably eliminate CurContext
675 // entirely, but we're not there yet.
676 DeclContext *SavedContext = CurContext;
677 CurContext = Context.getTranslationUnitDecl();
678 PushOnScopeChains(New, TUScope);
679 CurContext = SavedContext;
683 /// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
684 /// same name and scope as a previous declaration 'Old'. Figure out
685 /// how to resolve this situation, merging decls or emitting
686 /// diagnostics as appropriate. If there was an error, set New to be invalid.
688 void Sema::MergeTypeDefDecl(TypedefDecl *New, LookupResult &OldDecls) {
689 // If the new decl is known invalid already, don't bother doing any
691 if (New->isInvalidDecl()) return;
693 // Allow multiple definitions for ObjC built-in typedefs.
694 // FIXME: Verify the underlying types are equivalent!
695 if (getLangOptions().ObjC1) {
696 const IdentifierInfo *TypeID = New->getIdentifier();
697 switch (TypeID->getLength()) {
700 if (!TypeID->isStr("id"))
702 Context.ObjCIdRedefinitionType = New->getUnderlyingType();
703 // Install the built-in type for 'id', ignoring the current definition.
704 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
707 if (!TypeID->isStr("Class"))
709 Context.ObjCClassRedefinitionType = New->getUnderlyingType();
710 // Install the built-in type for 'Class', ignoring the current definition.
711 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
714 if (!TypeID->isStr("SEL"))
716 Context.ObjCSelRedefinitionType = New->getUnderlyingType();
717 // Install the built-in type for 'SEL', ignoring the current definition.
718 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
721 if (!TypeID->isStr("Protocol"))
723 Context.setObjCProtoType(New->getUnderlyingType());
726 // Fall through - the typedef name was not a builtin type.
729 // Verify the old decl was also a type.
730 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
732 Diag(New->getLocation(), diag::err_redefinition_different_kind)
733 << New->getDeclName();
735 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
736 if (OldD->getLocation().isValid())
737 Diag(OldD->getLocation(), diag::note_previous_definition);
739 return New->setInvalidDecl();
742 // If the old declaration is invalid, just give up here.
743 if (Old->isInvalidDecl())
744 return New->setInvalidDecl();
746 // Determine the "old" type we'll use for checking and diagnostics.
748 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
749 OldType = OldTypedef->getUnderlyingType();
751 OldType = Context.getTypeDeclType(Old);
753 // If the typedef types are not identical, reject them in all languages and
754 // with any extensions enabled.
756 if (OldType != New->getUnderlyingType() &&
757 Context.getCanonicalType(OldType) !=
758 Context.getCanonicalType(New->getUnderlyingType())) {
759 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
760 << New->getUnderlyingType() << OldType;
761 if (Old->getLocation().isValid())
762 Diag(Old->getLocation(), diag::note_previous_definition);
763 return New->setInvalidDecl();
766 // The types match. Link up the redeclaration chain if the old
767 // declaration was a typedef.
768 // FIXME: this is a potential source of wierdness if the type
769 // spellings don't match exactly.
770 if (isa<TypedefDecl>(Old))
771 New->setPreviousDeclaration(cast<TypedefDecl>(Old));
773 if (getLangOptions().Microsoft)
776 // C++ [dcl.typedef]p2:
777 // In a given non-class scope, a typedef specifier can be used to
778 // redefine the name of any type declared in that scope to refer
779 // to the type to which it already refers.
780 if (getLangOptions().CPlusPlus) {
781 if (!isa<CXXRecordDecl>(CurContext))
783 Diag(New->getLocation(), diag::err_redefinition)
784 << New->getDeclName();
785 Diag(Old->getLocation(), diag::note_previous_definition);
786 return New->setInvalidDecl();
789 // If we have a redefinition of a typedef in C, emit a warning. This warning
790 // is normally mapped to an error, but can be controlled with
791 // -Wtypedef-redefinition. If either the original or the redefinition is
792 // in a system header, don't emit this for compatibility with GCC.
793 if (PP.getDiagnostics().getSuppressSystemWarnings() &&
794 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
795 Context.getSourceManager().isInSystemHeader(New->getLocation())))
798 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
799 << New->getDeclName();
800 Diag(Old->getLocation(), diag::note_previous_definition);
804 /// DeclhasAttr - returns true if decl Declaration already has the target
807 DeclHasAttr(const Decl *decl, const Attr *target) {
808 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
809 if (attr->getKind() == target->getKind())
815 /// MergeAttributes - append attributes from the Old decl to the New one.
816 static void MergeAttributes(Decl *New, Decl *Old, ASTContext &C) {
817 for (const Attr *attr = Old->getAttrs(); attr; attr = attr->getNext()) {
818 if (!DeclHasAttr(New, attr) && attr->isMerged()) {
819 Attr *NewAttr = attr->clone(C);
820 NewAttr->setInherited(true);
821 New->addAttr(NewAttr);
826 /// Used in MergeFunctionDecl to keep track of function parameters in
828 struct GNUCompatibleParamWarning {
829 ParmVarDecl *OldParm;
830 ParmVarDecl *NewParm;
831 QualType PromotedType;
835 /// getSpecialMember - get the special member enum for a method.
836 static Sema::CXXSpecialMember getSpecialMember(ASTContext &Ctx,
837 const CXXMethodDecl *MD) {
838 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
839 if (Ctor->isDefaultConstructor())
840 return Sema::CXXDefaultConstructor;
841 if (Ctor->isCopyConstructor())
842 return Sema::CXXCopyConstructor;
845 if (isa<CXXDestructorDecl>(MD))
846 return Sema::CXXDestructor;
848 assert(MD->isCopyAssignment() && "Must have copy assignment operator");
849 return Sema::CXXCopyAssignment;
852 /// MergeFunctionDecl - We just parsed a function 'New' from
853 /// declarator D which has the same name and scope as a previous
854 /// declaration 'Old'. Figure out how to resolve this situation,
855 /// merging decls or emitting diagnostics as appropriate.
857 /// In C++, New and Old must be declarations that are not
858 /// overloaded. Use IsOverload to determine whether New and Old are
859 /// overloaded, and to select the Old declaration that New should be
862 /// Returns true if there was an error, false otherwise.
863 bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
864 // Verify the old decl was also a function.
865 FunctionDecl *Old = 0;
866 if (FunctionTemplateDecl *OldFunctionTemplate
867 = dyn_cast<FunctionTemplateDecl>(OldD))
868 Old = OldFunctionTemplate->getTemplatedDecl();
870 Old = dyn_cast<FunctionDecl>(OldD);
872 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
873 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
874 Diag(Shadow->getTargetDecl()->getLocation(),
875 diag::note_using_decl_target);
876 Diag(Shadow->getUsingDecl()->getLocation(),
877 diag::note_using_decl) << 0;
881 Diag(New->getLocation(), diag::err_redefinition_different_kind)
882 << New->getDeclName();
883 Diag(OldD->getLocation(), diag::note_previous_definition);
887 // Determine whether the previous declaration was a definition,
888 // implicit declaration, or a declaration.
890 if (Old->isThisDeclarationADefinition())
891 PrevDiag = diag::note_previous_definition;
892 else if (Old->isImplicit())
893 PrevDiag = diag::note_previous_implicit_declaration;
895 PrevDiag = diag::note_previous_declaration;
897 QualType OldQType = Context.getCanonicalType(Old->getType());
898 QualType NewQType = Context.getCanonicalType(New->getType());
900 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
901 New->getStorageClass() == FunctionDecl::Static &&
902 Old->getStorageClass() != FunctionDecl::Static) {
903 Diag(New->getLocation(), diag::err_static_non_static)
905 Diag(Old->getLocation(), PrevDiag);
909 if (getLangOptions().CPlusPlus) {
911 // Certain function declarations cannot be overloaded:
912 // -- Function declarations that differ only in the return type
913 // cannot be overloaded.
914 QualType OldReturnType
915 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
916 QualType NewReturnType
917 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
918 if (OldReturnType != NewReturnType) {
919 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
920 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
924 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
925 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
926 if (OldMethod && NewMethod) {
927 if (!NewMethod->getFriendObjectKind() &&
928 NewMethod->getLexicalDeclContext()->isRecord()) {
929 // -- Member function declarations with the same name and the
930 // same parameter types cannot be overloaded if any of them
931 // is a static member function declaration.
932 if (OldMethod->isStatic() || NewMethod->isStatic()) {
933 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
934 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
938 // C++ [class.mem]p1:
939 // [...] A member shall not be declared twice in the
940 // member-specification, except that a nested class or member
941 // class template can be declared and then later defined.
943 if (isa<CXXConstructorDecl>(OldMethod))
944 NewDiag = diag::err_constructor_redeclared;
945 else if (isa<CXXDestructorDecl>(NewMethod))
946 NewDiag = diag::err_destructor_redeclared;
947 else if (isa<CXXConversionDecl>(NewMethod))
948 NewDiag = diag::err_conv_function_redeclared;
950 NewDiag = diag::err_member_redeclared;
952 Diag(New->getLocation(), NewDiag);
953 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
955 if (OldMethod->isImplicit()) {
956 Diag(NewMethod->getLocation(),
957 diag::err_definition_of_implicitly_declared_member)
958 << New << getSpecialMember(Context, OldMethod);
960 Diag(OldMethod->getLocation(),
961 diag::note_previous_implicit_declaration);
968 // All declarations for a function shall agree exactly in both the
969 // return type and the parameter-type-list.
970 // attributes should be ignored when comparing.
971 if (Context.getNoReturnType(OldQType, false) ==
972 Context.getNoReturnType(NewQType, false))
973 return MergeCompatibleFunctionDecls(New, Old);
975 // Fall through for conflicting redeclarations and redefinitions.
978 // C: Function types need to be compatible, not identical. This handles
979 // duplicate function decls like "void f(int); void f(enum X);" properly.
980 if (!getLangOptions().CPlusPlus &&
981 Context.typesAreCompatible(OldQType, NewQType)) {
982 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
983 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
984 const FunctionProtoType *OldProto = 0;
985 if (isa<FunctionNoProtoType>(NewFuncType) &&
986 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
987 // The old declaration provided a function prototype, but the
988 // new declaration does not. Merge in the prototype.
989 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
990 llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
991 OldProto->arg_type_end());
992 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
993 ParamTypes.data(), ParamTypes.size(),
994 OldProto->isVariadic(),
995 OldProto->getTypeQuals());
996 New->setType(NewQType);
997 New->setHasInheritedPrototype();
999 // Synthesize a parameter for each argument type.
1000 llvm::SmallVector<ParmVarDecl*, 16> Params;
1001 for (FunctionProtoType::arg_type_iterator
1002 ParamType = OldProto->arg_type_begin(),
1003 ParamEnd = OldProto->arg_type_end();
1004 ParamType != ParamEnd; ++ParamType) {
1005 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
1006 SourceLocation(), 0,
1007 *ParamType, /*TInfo=*/0,
1009 Param->setImplicit();
1010 Params.push_back(Param);
1013 New->setParams(Context, Params.data(), Params.size());
1016 return MergeCompatibleFunctionDecls(New, Old);
1019 // GNU C permits a K&R definition to follow a prototype declaration
1020 // if the declared types of the parameters in the K&R definition
1021 // match the types in the prototype declaration, even when the
1022 // promoted types of the parameters from the K&R definition differ
1023 // from the types in the prototype. GCC then keeps the types from
1026 // If a variadic prototype is followed by a non-variadic K&R definition,
1027 // the K&R definition becomes variadic. This is sort of an edge case, but
1028 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
1030 if (!getLangOptions().CPlusPlus &&
1031 Old->hasPrototype() && !New->hasPrototype() &&
1032 New->getType()->getAs<FunctionProtoType>() &&
1033 Old->getNumParams() == New->getNumParams()) {
1034 llvm::SmallVector<QualType, 16> ArgTypes;
1035 llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
1036 const FunctionProtoType *OldProto
1037 = Old->getType()->getAs<FunctionProtoType>();
1038 const FunctionProtoType *NewProto
1039 = New->getType()->getAs<FunctionProtoType>();
1041 // Determine whether this is the GNU C extension.
1042 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
1043 NewProto->getResultType());
1044 bool LooseCompatible = !MergedReturn.isNull();
1045 for (unsigned Idx = 0, End = Old->getNumParams();
1046 LooseCompatible && Idx != End; ++Idx) {
1047 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
1048 ParmVarDecl *NewParm = New->getParamDecl(Idx);
1049 if (Context.typesAreCompatible(OldParm->getType(),
1050 NewProto->getArgType(Idx))) {
1051 ArgTypes.push_back(NewParm->getType());
1052 } else if (Context.typesAreCompatible(OldParm->getType(),
1053 NewParm->getType())) {
1054 GNUCompatibleParamWarning Warn
1055 = { OldParm, NewParm, NewProto->getArgType(Idx) };
1056 Warnings.push_back(Warn);
1057 ArgTypes.push_back(NewParm->getType());
1059 LooseCompatible = false;
1062 if (LooseCompatible) {
1063 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
1064 Diag(Warnings[Warn].NewParm->getLocation(),
1065 diag::ext_param_promoted_not_compatible_with_prototype)
1066 << Warnings[Warn].PromotedType
1067 << Warnings[Warn].OldParm->getType();
1068 Diag(Warnings[Warn].OldParm->getLocation(),
1069 diag::note_previous_declaration);
1072 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
1074 OldProto->isVariadic(), 0));
1075 return MergeCompatibleFunctionDecls(New, Old);
1078 // Fall through to diagnose conflicting types.
1081 // A function that has already been declared has been redeclared or defined
1082 // with a different type- show appropriate diagnostic
1083 if (unsigned BuiltinID = Old->getBuiltinID()) {
1084 // The user has declared a builtin function with an incompatible
1086 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
1087 // The function the user is redeclaring is a library-defined
1088 // function like 'malloc' or 'printf'. Warn about the
1089 // redeclaration, then pretend that we don't know about this
1090 // library built-in.
1091 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
1092 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
1093 << Old << Old->getType();
1094 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
1095 Old->setInvalidDecl();
1099 PrevDiag = diag::note_previous_builtin_declaration;
1102 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
1103 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1107 /// \brief Completes the merge of two function declarations that are
1108 /// known to be compatible.
1110 /// This routine handles the merging of attributes and other
1111 /// properties of function declarations form the old declaration to
1112 /// the new declaration, once we know that New is in fact a
1113 /// redeclaration of Old.
1116 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
1117 // Merge the attributes
1118 MergeAttributes(New, Old, Context);
1120 // Merge the storage class.
1121 if (Old->getStorageClass() != FunctionDecl::Extern &&
1122 Old->getStorageClass() != FunctionDecl::None)
1123 New->setStorageClass(Old->getStorageClass());
1125 // Merge "pure" flag.
1129 // Merge the "deleted" flag.
1130 if (Old->isDeleted())
1133 if (getLangOptions().CPlusPlus)
1134 return MergeCXXFunctionDecl(New, Old);
1139 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
1140 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
1141 /// situation, merging decls or emitting diagnostics as appropriate.
1143 /// Tentative definition rules (C99 6.9.2p2) are checked by
1144 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
1145 /// definitions here, since the initializer hasn't been attached.
1147 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
1148 // If the new decl is already invalid, don't do any other checking.
1149 if (New->isInvalidDecl())
1152 // Verify the old decl was also a variable.
1154 if (!Previous.isSingleResult() ||
1155 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
1156 Diag(New->getLocation(), diag::err_redefinition_different_kind)
1157 << New->getDeclName();
1158 Diag(Previous.getRepresentativeDecl()->getLocation(),
1159 diag::note_previous_definition);
1160 return New->setInvalidDecl();
1163 MergeAttributes(New, Old, Context);
1167 if (getLangOptions().CPlusPlus) {
1168 if (Context.hasSameType(New->getType(), Old->getType()))
1169 MergedT = New->getType();
1170 // C++ [basic.link]p10:
1171 // [...] the types specified by all declarations referring to a given
1172 // object or function shall be identical, except that declarations for an
1173 // array object can specify array types that differ by the presence or
1174 // absence of a major array bound (8.3.4).
1175 else if (Old->getType()->isIncompleteArrayType() &&
1176 New->getType()->isArrayType()) {
1177 CanQual<ArrayType> OldArray
1178 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1179 CanQual<ArrayType> NewArray
1180 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1181 if (OldArray->getElementType() == NewArray->getElementType())
1182 MergedT = New->getType();
1183 } else if (Old->getType()->isArrayType() &&
1184 New->getType()->isIncompleteArrayType()) {
1185 CanQual<ArrayType> OldArray
1186 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1187 CanQual<ArrayType> NewArray
1188 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1189 if (OldArray->getElementType() == NewArray->getElementType())
1190 MergedT = Old->getType();
1193 MergedT = Context.mergeTypes(New->getType(), Old->getType());
1195 if (MergedT.isNull()) {
1196 Diag(New->getLocation(), diag::err_redefinition_different_type)
1197 << New->getDeclName();
1198 Diag(Old->getLocation(), diag::note_previous_definition);
1199 return New->setInvalidDecl();
1201 New->setType(MergedT);
1203 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
1204 if (New->getStorageClass() == VarDecl::Static &&
1205 (Old->getStorageClass() == VarDecl::None || Old->hasExternalStorage())) {
1206 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
1207 Diag(Old->getLocation(), diag::note_previous_definition);
1208 return New->setInvalidDecl();
1211 // For an identifier declared with the storage-class specifier
1212 // extern in a scope in which a prior declaration of that
1213 // identifier is visible,23) if the prior declaration specifies
1214 // internal or external linkage, the linkage of the identifier at
1215 // the later declaration is the same as the linkage specified at
1216 // the prior declaration. If no prior declaration is visible, or
1217 // if the prior declaration specifies no linkage, then the
1218 // identifier has external linkage.
1219 if (New->hasExternalStorage() && Old->hasLinkage())
1221 else if (New->getStorageClass() != VarDecl::Static &&
1222 Old->getStorageClass() == VarDecl::Static) {
1223 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
1224 Diag(Old->getLocation(), diag::note_previous_definition);
1225 return New->setInvalidDecl();
1228 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
1230 // FIXME: The test for external storage here seems wrong? We still
1231 // need to check for mismatches.
1232 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
1233 // Don't complain about out-of-line definitions of static members.
1234 !(Old->getLexicalDeclContext()->isRecord() &&
1235 !New->getLexicalDeclContext()->isRecord())) {
1236 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
1237 Diag(Old->getLocation(), diag::note_previous_definition);
1238 return New->setInvalidDecl();
1241 if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
1242 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
1243 Diag(Old->getLocation(), diag::note_previous_definition);
1244 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
1245 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
1246 Diag(Old->getLocation(), diag::note_previous_definition);
1249 // Keep a chain of previous declarations.
1250 New->setPreviousDeclaration(Old);
1253 /// CheckFallThrough - Check that we don't fall off the end of a
1254 /// Statement that should return a value.
1256 /// \returns AlwaysFallThrough iff we always fall off the end of the statement,
1257 /// MaybeFallThrough iff we might or might not fall off the end,
1258 /// NeverFallThroughOrReturn iff we never fall off the end of the statement or
1259 /// return. We assume NeverFallThrough iff we never fall off the end of the
1260 /// statement but we may return. We assume that functions not marked noreturn
1262 Sema::ControlFlowKind Sema::CheckFallThrough(Stmt *Root) {
1263 // FIXME: Eventually share this CFG object when we have other warnings based
1264 // of the CFG. This can be done using AnalysisContext.
1265 llvm::OwningPtr<CFG> cfg (CFG::buildCFG(Root, &Context));
1267 // FIXME: They should never return 0, fix that, delete this code.
1269 // FIXME: This should be NeverFallThrough
1270 return NeverFallThroughOrReturn;
1271 // The CFG leaves in dead things, and we don't want to dead code paths to
1272 // confuse us, so we mark all live things first.
1273 std::queue<CFGBlock*> workq;
1274 llvm::BitVector live(cfg->getNumBlockIDs());
1276 workq.push(&cfg->getEntry());
1278 while (!workq.empty()) {
1279 CFGBlock *item = workq.front();
1281 live.set(item->getBlockID());
1282 for (CFGBlock::succ_iterator I=item->succ_begin(),
1286 if ((*I) && !live[(*I)->getBlockID()]) {
1287 live.set((*I)->getBlockID());
1293 // Now we know what is live, we check the live precessors of the exit block
1294 // and look for fall through paths, being careful to ignore normal returns,
1295 // and exceptional paths.
1296 bool HasLiveReturn = false;
1297 bool HasFakeEdge = false;
1298 bool HasPlainEdge = false;
1299 for (CFGBlock::pred_iterator I=cfg->getExit().pred_begin(),
1300 E = cfg->getExit().pred_end();
1304 if (!live[B.getBlockID()])
1306 if (B.size() == 0) {
1307 // A labeled empty statement, or the entry block...
1308 HasPlainEdge = true;
1311 Stmt *S = B[B.size()-1];
1312 if (isa<ReturnStmt>(S)) {
1313 HasLiveReturn = true;
1316 if (isa<ObjCAtThrowStmt>(S)) {
1320 if (isa<CXXThrowExpr>(S)) {
1324 bool NoReturnEdge = false;
1325 if (CallExpr *C = dyn_cast<CallExpr>(S)) {
1326 Expr *CEE = C->getCallee()->IgnoreParenCasts();
1327 if (CEE->getType().getNoReturnAttr()) {
1328 NoReturnEdge = true;
1330 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) {
1331 ValueDecl *VD = DRE->getDecl();
1332 if (VD->hasAttr<NoReturnAttr>()) {
1333 NoReturnEdge = true;
1338 // FIXME: Add noreturn message sends.
1339 if (NoReturnEdge == false)
1340 HasPlainEdge = true;
1342 if (!HasPlainEdge) {
1344 return NeverFallThrough;
1345 return NeverFallThroughOrReturn;
1347 if (HasFakeEdge || HasLiveReturn)
1348 return MaybeFallThrough;
1349 // This says AlwaysFallThrough for calls to functions that are not marked
1350 // noreturn, that don't return. If people would like this warning to be more
1351 // accurate, such functions should be marked as noreturn.
1352 return AlwaysFallThrough;
1355 /// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
1356 /// function that should return a value. Check that we don't fall off the end
1357 /// of a noreturn function. We assume that functions and blocks not marked
1358 /// noreturn will return.
1359 void Sema::CheckFallThroughForFunctionDef(Decl *D, Stmt *Body) {
1360 // FIXME: Would be nice if we had a better way to control cascading errors,
1361 // but for now, avoid them. The problem is that when Parse sees:
1362 // int foo() { return a; }
1363 // The return is eaten and the Sema code sees just:
1365 // which this code would then warn about.
1366 if (getDiagnostics().hasErrorOccurred())
1369 bool ReturnsVoid = false;
1370 bool HasNoReturn = false;
1371 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1372 // If the result type of the function is a dependent type, we don't know
1373 // whether it will be void or not, so don't
1374 if (FD->getResultType()->isDependentType())
1376 if (FD->getResultType()->isVoidType())
1378 if (FD->hasAttr<NoReturnAttr>())
1380 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
1381 if (MD->getResultType()->isVoidType())
1383 if (MD->hasAttr<NoReturnAttr>())
1387 // Short circuit for compilation speed.
1388 if ((Diags.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function)
1389 == Diagnostic::Ignored || ReturnsVoid)
1390 && (Diags.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr)
1391 == Diagnostic::Ignored || !HasNoReturn)
1392 && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
1393 == Diagnostic::Ignored || !ReturnsVoid))
1395 // FIXME: Function try block
1396 if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
1397 switch (CheckFallThrough(Body)) {
1398 case MaybeFallThrough:
1400 Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
1401 else if (!ReturnsVoid)
1402 Diag(Compound->getRBracLoc(),diag::warn_maybe_falloff_nonvoid_function);
1404 case AlwaysFallThrough:
1406 Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
1407 else if (!ReturnsVoid)
1408 Diag(Compound->getRBracLoc(), diag::warn_falloff_nonvoid_function);
1410 case NeverFallThroughOrReturn:
1411 if (ReturnsVoid && !HasNoReturn)
1412 Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_function);
1414 case NeverFallThrough:
1420 /// CheckFallThroughForBlock - Check that we don't fall off the end of a block
1421 /// that should return a value. Check that we don't fall off the end of a
1422 /// noreturn block. We assume that functions and blocks not marked noreturn
1424 void Sema::CheckFallThroughForBlock(QualType BlockTy, Stmt *Body) {
1425 // FIXME: Would be nice if we had a better way to control cascading errors,
1426 // but for now, avoid them. The problem is that when Parse sees:
1427 // int foo() { return a; }
1428 // The return is eaten and the Sema code sees just:
1430 // which this code would then warn about.
1431 if (getDiagnostics().hasErrorOccurred())
1433 bool ReturnsVoid = false;
1434 bool HasNoReturn = false;
1435 if (const FunctionType *FT =BlockTy->getPointeeType()->getAs<FunctionType>()){
1436 if (FT->getResultType()->isVoidType())
1438 if (FT->getNoReturnAttr())
1442 // Short circuit for compilation speed.
1445 && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
1446 == Diagnostic::Ignored || !ReturnsVoid))
1448 // FIXME: Funtion try block
1449 if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
1450 switch (CheckFallThrough(Body)) {
1451 case MaybeFallThrough:
1453 Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
1454 else if (!ReturnsVoid)
1455 Diag(Compound->getRBracLoc(), diag::err_maybe_falloff_nonvoid_block);
1457 case AlwaysFallThrough:
1459 Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
1460 else if (!ReturnsVoid)
1461 Diag(Compound->getRBracLoc(), diag::err_falloff_nonvoid_block);
1463 case NeverFallThroughOrReturn:
1465 Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_block);
1467 case NeverFallThrough:
1473 /// CheckParmsForFunctionDef - Check that the parameters of the given
1474 /// function are appropriate for the definition of a function. This
1475 /// takes care of any checks that cannot be performed on the
1476 /// declaration itself, e.g., that the types of each of the function
1477 /// parameters are complete.
1478 bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
1479 bool HasInvalidParm = false;
1480 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1481 ParmVarDecl *Param = FD->getParamDecl(p);
1483 // C99 6.7.5.3p4: the parameters in a parameter type list in a
1484 // function declarator that is part of a function definition of
1485 // that function shall not have incomplete type.
1487 // This is also C++ [dcl.fct]p6.
1488 if (!Param->isInvalidDecl() &&
1489 RequireCompleteType(Param->getLocation(), Param->getType(),
1490 diag::err_typecheck_decl_incomplete_type)) {
1491 Param->setInvalidDecl();
1492 HasInvalidParm = true;
1495 // C99 6.9.1p5: If the declarator includes a parameter type list, the
1496 // declaration of each parameter shall include an identifier.
1497 if (Param->getIdentifier() == 0 &&
1498 !Param->isImplicit() &&
1499 !getLangOptions().CPlusPlus)
1500 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
1503 return HasInvalidParm;
1506 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
1507 /// no declarator (e.g. "struct foo;") is parsed.
1508 Sema::DeclPtrTy Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
1509 // FIXME: Error on auto/register at file scope
1510 // FIXME: Error on inline/virtual/explicit
1511 // FIXME: Warn on useless __thread
1512 // FIXME: Warn on useless const/volatile
1513 // FIXME: Warn on useless static/extern/typedef/private_extern/mutable
1514 // FIXME: Warn on useless attributes
1517 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
1518 DS.getTypeSpecType() == DeclSpec::TST_struct ||
1519 DS.getTypeSpecType() == DeclSpec::TST_union ||
1520 DS.getTypeSpecType() == DeclSpec::TST_enum) {
1521 TagD = static_cast<Decl *>(DS.getTypeRep());
1523 if (!TagD) // We probably had an error
1526 // Note that the above type specs guarantee that the
1527 // type rep is a Decl, whereas in many of the others
1529 Tag = dyn_cast<TagDecl>(TagD);
1532 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1533 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
1534 // or incomplete types shall not be restrict-qualified."
1535 if (TypeQuals & DeclSpec::TQ_restrict)
1536 Diag(DS.getRestrictSpecLoc(),
1537 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
1538 << DS.getSourceRange();
1541 if (DS.isFriendSpecified()) {
1542 // If we're dealing with a class template decl, assume that the
1543 // template routines are handling it.
1544 if (TagD && isa<ClassTemplateDecl>(TagD))
1546 return ActOnFriendTypeDecl(S, DS, MultiTemplateParamsArg(*this, 0, 0));
1549 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
1550 // If there are attributes in the DeclSpec, apply them to the record.
1551 if (const AttributeList *AL = DS.getAttributes())
1552 ProcessDeclAttributeList(S, Record, AL);
1554 if (!Record->getDeclName() && Record->isDefinition() &&
1555 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
1556 if (getLangOptions().CPlusPlus ||
1557 Record->getDeclContext()->isRecord())
1558 return BuildAnonymousStructOrUnion(S, DS, Record);
1560 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
1561 << DS.getSourceRange();
1564 // Microsoft allows unnamed struct/union fields. Don't complain
1566 // FIXME: Should we support Microsoft's extensions in this area?
1567 if (Record->getDeclName() && getLangOptions().Microsoft)
1568 return DeclPtrTy::make(Tag);
1571 if (!DS.isMissingDeclaratorOk() &&
1572 DS.getTypeSpecType() != DeclSpec::TST_error) {
1573 // Warn about typedefs of enums without names, since this is an
1574 // extension in both Microsoft an GNU.
1575 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
1576 Tag && isa<EnumDecl>(Tag)) {
1577 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
1578 << DS.getSourceRange();
1579 return DeclPtrTy::make(Tag);
1582 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
1583 << DS.getSourceRange();
1587 return DeclPtrTy::make(Tag);
1590 /// We are trying to inject an anonymous member into the given scope;
1591 /// check if there's an existing declaration that can't be overloaded.
1593 /// \return true if this is a forbidden redeclaration
1594 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
1596 DeclarationName Name,
1597 SourceLocation NameLoc,
1598 unsigned diagnostic) {
1599 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
1600 Sema::ForRedeclaration);
1601 if (!SemaRef.LookupName(R, S)) return false;
1603 if (R.getAsSingle<TagDecl>())
1606 // Pick a representative declaration.
1607 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
1609 SemaRef.Diag(NameLoc, diagnostic) << Name;
1610 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
1615 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
1616 /// anonymous struct or union AnonRecord into the owning context Owner
1617 /// and scope S. This routine will be invoked just after we realize
1618 /// that an unnamed union or struct is actually an anonymous union or
1625 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
1626 /// // f into the surrounding scope.x
1629 /// This routine is recursive, injecting the names of nested anonymous
1630 /// structs/unions into the owning context and scope as well.
1631 bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
1632 RecordDecl *AnonRecord) {
1634 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
1635 : diag::err_anonymous_struct_member_redecl;
1637 bool Invalid = false;
1638 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
1639 FEnd = AnonRecord->field_end();
1641 if ((*F)->getDeclName()) {
1642 if (CheckAnonMemberRedeclaration(*this, S, (*F)->getDeclName(),
1643 (*F)->getLocation(), diagKind)) {
1644 // C++ [class.union]p2:
1645 // The names of the members of an anonymous union shall be
1646 // distinct from the names of any other entity in the
1647 // scope in which the anonymous union is declared.
1650 // C++ [class.union]p2:
1651 // For the purpose of name lookup, after the anonymous union
1652 // definition, the members of the anonymous union are
1653 // considered to have been defined in the scope in which the
1654 // anonymous union is declared.
1655 Owner->makeDeclVisibleInContext(*F);
1656 S->AddDecl(DeclPtrTy::make(*F));
1657 IdResolver.AddDecl(*F);
1659 } else if (const RecordType *InnerRecordType
1660 = (*F)->getType()->getAs<RecordType>()) {
1661 RecordDecl *InnerRecord = InnerRecordType->getDecl();
1662 if (InnerRecord->isAnonymousStructOrUnion())
1663 Invalid = Invalid ||
1664 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
1671 /// ActOnAnonymousStructOrUnion - Handle the declaration of an
1672 /// anonymous structure or union. Anonymous unions are a C++ feature
1673 /// (C++ [class.union]) and a GNU C extension; anonymous structures
1674 /// are a GNU C and GNU C++ extension.
1675 Sema::DeclPtrTy Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1676 RecordDecl *Record) {
1677 DeclContext *Owner = Record->getDeclContext();
1679 // Diagnose whether this anonymous struct/union is an extension.
1680 if (Record->isUnion() && !getLangOptions().CPlusPlus)
1681 Diag(Record->getLocation(), diag::ext_anonymous_union);
1682 else if (!Record->isUnion())
1683 Diag(Record->getLocation(), diag::ext_anonymous_struct);
1685 // C and C++ require different kinds of checks for anonymous
1687 bool Invalid = false;
1688 if (getLangOptions().CPlusPlus) {
1689 const char* PrevSpec = 0;
1691 // C++ [class.union]p3:
1692 // Anonymous unions declared in a named namespace or in the
1693 // global namespace shall be declared static.
1694 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
1695 (isa<TranslationUnitDecl>(Owner) ||
1696 (isa<NamespaceDecl>(Owner) &&
1697 cast<NamespaceDecl>(Owner)->getDeclName()))) {
1698 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
1701 // Recover by adding 'static'.
1702 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(),
1705 // C++ [class.union]p3:
1706 // A storage class is not allowed in a declaration of an
1707 // anonymous union in a class scope.
1708 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1709 isa<RecordDecl>(Owner)) {
1710 Diag(DS.getStorageClassSpecLoc(),
1711 diag::err_anonymous_union_with_storage_spec);
1714 // Recover by removing the storage specifier.
1715 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
1719 // C++ [class.union]p2:
1720 // The member-specification of an anonymous union shall only
1721 // define non-static data members. [Note: nested types and
1722 // functions cannot be declared within an anonymous union. ]
1723 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
1724 MemEnd = Record->decls_end();
1725 Mem != MemEnd; ++Mem) {
1726 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
1727 // C++ [class.union]p3:
1728 // An anonymous union shall not have private or protected
1729 // members (clause 11).
1730 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
1731 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
1732 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
1735 } else if ((*Mem)->isImplicit()) {
1736 // Any implicit members are fine.
1737 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
1738 // This is a type that showed up in an
1739 // elaborated-type-specifier inside the anonymous struct or
1740 // union, but which actually declares a type outside of the
1741 // anonymous struct or union. It's okay.
1742 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
1743 if (!MemRecord->isAnonymousStructOrUnion() &&
1744 MemRecord->getDeclName()) {
1745 // This is a nested type declaration.
1746 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
1747 << (int)Record->isUnion();
1751 // We have something that isn't a non-static data
1752 // member. Complain about it.
1753 unsigned DK = diag::err_anonymous_record_bad_member;
1754 if (isa<TypeDecl>(*Mem))
1755 DK = diag::err_anonymous_record_with_type;
1756 else if (isa<FunctionDecl>(*Mem))
1757 DK = diag::err_anonymous_record_with_function;
1758 else if (isa<VarDecl>(*Mem))
1759 DK = diag::err_anonymous_record_with_static;
1760 Diag((*Mem)->getLocation(), DK)
1761 << (int)Record->isUnion();
1767 if (!Record->isUnion() && !Owner->isRecord()) {
1768 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
1769 << (int)getLangOptions().CPlusPlus;
1773 // Mock up a declarator.
1774 Declarator Dc(DS, Declarator::TypeNameContext);
1775 TypeSourceInfo *TInfo = 0;
1776 GetTypeForDeclarator(Dc, S, &TInfo);
1777 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
1779 // Create a declaration for this anonymous struct/union.
1780 NamedDecl *Anon = 0;
1781 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
1782 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
1783 /*IdentifierInfo=*/0,
1784 Context.getTypeDeclType(Record),
1786 /*BitWidth=*/0, /*Mutable=*/false);
1787 Anon->setAccess(AS_public);
1788 if (getLangOptions().CPlusPlus)
1789 FieldCollector->Add(cast<FieldDecl>(Anon));
1791 VarDecl::StorageClass SC;
1792 switch (DS.getStorageClassSpec()) {
1793 default: assert(0 && "Unknown storage class!");
1794 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1795 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1796 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1797 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1798 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1799 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1800 case DeclSpec::SCS_mutable:
1801 // mutable can only appear on non-static class members, so it's always
1803 Diag(Record->getLocation(), diag::err_mutable_nonmember);
1809 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
1810 /*IdentifierInfo=*/0,
1811 Context.getTypeDeclType(Record),
1815 Anon->setImplicit();
1817 // Add the anonymous struct/union object to the current
1818 // context. We'll be referencing this object when we refer to one of
1820 Owner->addDecl(Anon);
1822 // Inject the members of the anonymous struct/union into the owning
1823 // context and into the identifier resolver chain for name lookup
1825 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
1828 // Mark this as an anonymous struct/union type. Note that we do not
1829 // do this until after we have already checked and injected the
1830 // members of this anonymous struct/union type, because otherwise
1831 // the members could be injected twice: once by DeclContext when it
1832 // builds its lookup table, and once by
1833 // InjectAnonymousStructOrUnionMembers.
1834 Record->setAnonymousStructOrUnion(true);
1837 Anon->setInvalidDecl();
1839 return DeclPtrTy::make(Anon);
1843 /// GetNameForDeclarator - Determine the full declaration name for the
1844 /// given Declarator.
1845 DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1846 return GetNameFromUnqualifiedId(D.getName());
1849 /// \brief Retrieves the canonicalized name from a parsed unqualified-id.
1850 DeclarationName Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
1851 switch (Name.getKind()) {
1852 case UnqualifiedId::IK_Identifier:
1853 return DeclarationName(Name.Identifier);
1855 case UnqualifiedId::IK_OperatorFunctionId:
1856 return Context.DeclarationNames.getCXXOperatorName(
1857 Name.OperatorFunctionId.Operator);
1859 case UnqualifiedId::IK_LiteralOperatorId:
1860 return Context.DeclarationNames.getCXXLiteralOperatorName(
1863 case UnqualifiedId::IK_ConversionFunctionId: {
1864 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId);
1866 return DeclarationName();
1868 return Context.DeclarationNames.getCXXConversionFunctionName(
1869 Context.getCanonicalType(Ty));
1872 case UnqualifiedId::IK_ConstructorName: {
1873 QualType Ty = GetTypeFromParser(Name.ConstructorName);
1875 return DeclarationName();
1877 return Context.DeclarationNames.getCXXConstructorName(
1878 Context.getCanonicalType(Ty));
1881 case UnqualifiedId::IK_DestructorName: {
1882 QualType Ty = GetTypeFromParser(Name.DestructorName);
1884 return DeclarationName();
1886 return Context.DeclarationNames.getCXXDestructorName(
1887 Context.getCanonicalType(Ty));
1890 case UnqualifiedId::IK_TemplateId: {
1892 = TemplateName::getFromVoidPointer(Name.TemplateId->Template);
1893 return Context.getNameForTemplate(TName);
1897 assert(false && "Unknown name kind");
1898 return DeclarationName();
1901 /// isNearlyMatchingFunction - Determine whether the C++ functions
1902 /// Declaration and Definition are "nearly" matching. This heuristic
1903 /// is used to improve diagnostics in the case where an out-of-line
1904 /// function definition doesn't match any declaration within
1905 /// the class or namespace.
1906 static bool isNearlyMatchingFunction(ASTContext &Context,
1907 FunctionDecl *Declaration,
1908 FunctionDecl *Definition) {
1909 if (Declaration->param_size() != Definition->param_size())
1911 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1912 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1913 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1915 if (!Context.hasSameUnqualifiedType(DeclParamTy.getNonReferenceType(),
1916 DefParamTy.getNonReferenceType()))
1924 Sema::HandleDeclarator(Scope *S, Declarator &D,
1925 MultiTemplateParamsArg TemplateParamLists,
1926 bool IsFunctionDefinition) {
1927 DeclarationName Name = GetNameForDeclarator(D);
1929 // All of these full declarators require an identifier. If it doesn't have
1930 // one, the ParsedFreeStandingDeclSpec action should be used.
1932 if (!D.isInvalidType()) // Reject this if we think it is valid.
1933 Diag(D.getDeclSpec().getSourceRange().getBegin(),
1934 diag::err_declarator_need_ident)
1935 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
1939 // The scope passed in may not be a decl scope. Zip up the scope tree until
1940 // we find one that is.
1941 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1942 (S->getFlags() & Scope::TemplateParamScope) != 0)
1945 // If this is an out-of-line definition of a member of a class template
1946 // or class template partial specialization, we may need to rebuild the
1947 // type specifier in the declarator. See RebuildTypeInCurrentInstantiation()
1948 // for more information.
1949 // FIXME: cope with decltype(expr) and typeof(expr) once the rebuilder can
1950 // handle expressions properly.
1951 DeclSpec &DS = const_cast<DeclSpec&>(D.getDeclSpec());
1952 if (D.getCXXScopeSpec().isSet() && !D.getCXXScopeSpec().isInvalid() &&
1953 isDependentScopeSpecifier(D.getCXXScopeSpec()) &&
1954 (DS.getTypeSpecType() == DeclSpec::TST_typename ||
1955 DS.getTypeSpecType() == DeclSpec::TST_typeofType ||
1956 DS.getTypeSpecType() == DeclSpec::TST_typeofExpr ||
1957 DS.getTypeSpecType() == DeclSpec::TST_decltype)) {
1958 if (DeclContext *DC = computeDeclContext(D.getCXXScopeSpec(), true)) {
1959 // FIXME: Preserve type source info.
1960 QualType T = GetTypeFromParser(DS.getTypeRep());
1962 DeclContext *SavedContext = CurContext;
1964 T = RebuildTypeInCurrentInstantiation(T, D.getIdentifierLoc(), Name);
1965 CurContext = SavedContext;
1969 DS.UpdateTypeRep(T.getAsOpaquePtr());
1976 TypeSourceInfo *TInfo = 0;
1977 QualType R = GetTypeForDeclarator(D, S, &TInfo);
1979 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
1982 // See if this is a redefinition of a variable in the same scope.
1983 if (D.getCXXScopeSpec().isInvalid()) {
1986 } else if (!D.getCXXScopeSpec().isSet()) {
1987 bool IsLinkageLookup = false;
1989 // If the declaration we're planning to build will be a function
1990 // or object with linkage, then look for another declaration with
1991 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
1992 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1994 else if (R->isFunctionType()) {
1995 if (CurContext->isFunctionOrMethod() ||
1996 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
1997 IsLinkageLookup = true;
1998 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
1999 IsLinkageLookup = true;
2000 else if (CurContext->getLookupContext()->isTranslationUnit() &&
2001 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
2002 IsLinkageLookup = true;
2004 if (IsLinkageLookup)
2005 Previous.clear(LookupRedeclarationWithLinkage);
2008 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
2009 } else { // Something like "int foo::x;"
2010 DC = computeDeclContext(D.getCXXScopeSpec(), true);
2013 // If we could not compute the declaration context, it's because the
2014 // declaration context is dependent but does not refer to a class,
2015 // class template, or class template partial specialization. Complain
2016 // and return early, to avoid the coming semantic disaster.
2017 Diag(D.getIdentifierLoc(),
2018 diag::err_template_qualified_declarator_no_match)
2019 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
2020 << D.getCXXScopeSpec().getRange();
2024 if (!DC->isDependentContext() &&
2025 RequireCompleteDeclContext(D.getCXXScopeSpec()))
2028 LookupQualifiedName(Previous, DC);
2030 // Don't consider using declarations as previous declarations for
2031 // out-of-line members.
2032 RemoveUsingDecls(Previous);
2035 // Members (including explicit specializations of templates) of a named
2036 // namespace can also be defined outside that namespace by explicit
2037 // qualification of the name being defined, provided that the entity being
2038 // defined was already declared in the namespace and the definition appears
2039 // after the point of declaration in a namespace that encloses the
2040 // declarations namespace.
2042 // Note that we only check the context at this point. We don't yet
2043 // have enough information to make sure that PrevDecl is actually
2044 // the declaration we want to match. For example, given:
2051 // void X::f(int) { } // ill-formed
2053 // In this case, PrevDecl will point to the overload set
2054 // containing the two f's declared in X, but neither of them
2057 // First check whether we named the global scope.
2058 if (isa<TranslationUnitDecl>(DC)) {
2059 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
2060 << Name << D.getCXXScopeSpec().getRange();
2062 DeclContext *Cur = CurContext;
2063 while (isa<LinkageSpecDecl>(Cur))
2064 Cur = Cur->getParent();
2065 if (!Cur->Encloses(DC)) {
2066 // The qualifying scope doesn't enclose the original declaration.
2067 // Emit diagnostic based on current scope.
2068 SourceLocation L = D.getIdentifierLoc();
2069 SourceRange R = D.getCXXScopeSpec().getRange();
2070 if (isa<FunctionDecl>(Cur))
2071 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
2073 Diag(L, diag::err_invalid_declarator_scope)
2074 << Name << cast<NamedDecl>(DC) << R;
2080 if (Previous.isSingleResult() &&
2081 Previous.getFoundDecl()->isTemplateParameter()) {
2082 // Maybe we will complain about the shadowed template parameter.
2083 if (!D.isInvalidType())
2084 if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
2085 Previous.getFoundDecl()))
2088 // Just pretend that we didn't see the previous declaration.
2092 // In C++, the previous declaration we find might be a tag type
2093 // (class or enum). In this case, the new declaration will hide the
2094 // tag type. Note that this does does not apply if we're declaring a
2095 // typedef (C++ [dcl.typedef]p4).
2096 if (Previous.isSingleTagDecl() &&
2097 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
2100 bool Redeclaration = false;
2101 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
2102 if (TemplateParamLists.size()) {
2103 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
2107 New = ActOnTypedefDeclarator(S, D, DC, R, TInfo, Previous, Redeclaration);
2108 } else if (R->isFunctionType()) {
2109 New = ActOnFunctionDeclarator(S, D, DC, R, TInfo, Previous,
2110 move(TemplateParamLists),
2111 IsFunctionDefinition, Redeclaration);
2113 New = ActOnVariableDeclarator(S, D, DC, R, TInfo, Previous,
2114 move(TemplateParamLists),
2121 // If this has an identifier and is not an invalid redeclaration or
2122 // function template specialization, add it to the scope stack.
2123 if (Name && !(Redeclaration && New->isInvalidDecl()))
2124 PushOnScopeChains(New, S);
2126 return DeclPtrTy::make(New);
2129 /// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2130 /// types into constant array types in certain situations which would otherwise
2131 /// be errors (for GCC compatibility).
2132 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2133 ASTContext &Context,
2134 bool &SizeIsNegative) {
2135 // This method tries to turn a variable array into a constant
2136 // array even when the size isn't an ICE. This is necessary
2137 // for compatibility with code that depends on gcc's buggy
2138 // constant expression folding, like struct {char x[(int)(char*)2];}
2139 SizeIsNegative = false;
2141 QualifierCollector Qs;
2142 const Type *Ty = Qs.strip(T);
2144 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
2145 QualType Pointee = PTy->getPointeeType();
2146 QualType FixedType =
2147 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative);
2148 if (FixedType.isNull()) return FixedType;
2149 FixedType = Context.getPointerType(FixedType);
2150 return Qs.apply(FixedType);
2153 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2156 // FIXME: We should probably handle this case
2157 if (VLATy->getElementType()->isVariablyModifiedType())
2160 Expr::EvalResult EvalResult;
2161 if (!VLATy->getSizeExpr() ||
2162 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
2163 !EvalResult.Val.isInt())
2166 llvm::APSInt &Res = EvalResult.Val.getInt();
2167 if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) {
2168 // TODO: preserve the size expression in declarator info
2169 return Context.getConstantArrayType(VLATy->getElementType(),
2170 Res, ArrayType::Normal, 0);
2173 SizeIsNegative = true;
2177 /// \brief Register the given locally-scoped external C declaration so
2178 /// that it can be found later for redeclarations
2180 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
2181 const LookupResult &Previous,
2183 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
2184 "Decl is not a locally-scoped decl!");
2185 // Note that we have a locally-scoped external with this name.
2186 LocallyScopedExternalDecls[ND->getDeclName()] = ND;
2188 if (!Previous.isSingleResult())
2191 NamedDecl *PrevDecl = Previous.getFoundDecl();
2193 // If there was a previous declaration of this variable, it may be
2194 // in our identifier chain. Update the identifier chain with the new
2196 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
2197 // The previous declaration was found on the identifer resolver
2198 // chain, so remove it from its scope.
2199 while (S && !S->isDeclScope(DeclPtrTy::make(PrevDecl)))
2203 S->RemoveDecl(DeclPtrTy::make(PrevDecl));
2207 /// \brief Diagnose function specifiers on a declaration of an identifier that
2208 /// does not identify a function.
2209 void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
2210 // FIXME: We should probably indicate the identifier in question to avoid
2211 // confusion for constructs like "inline int a(), b;"
2212 if (D.getDeclSpec().isInlineSpecified())
2213 Diag(D.getDeclSpec().getInlineSpecLoc(),
2214 diag::err_inline_non_function);
2216 if (D.getDeclSpec().isVirtualSpecified())
2217 Diag(D.getDeclSpec().getVirtualSpecLoc(),
2218 diag::err_virtual_non_function);
2220 if (D.getDeclSpec().isExplicitSpecified())
2221 Diag(D.getDeclSpec().getExplicitSpecLoc(),
2222 diag::err_explicit_non_function);
2226 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2227 QualType R, TypeSourceInfo *TInfo,
2228 LookupResult &Previous, bool &Redeclaration) {
2229 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
2230 if (D.getCXXScopeSpec().isSet()) {
2231 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
2232 << D.getCXXScopeSpec().getRange();
2234 // Pretend we didn't see the scope specifier.
2238 if (getLangOptions().CPlusPlus) {
2239 // Check that there are no default arguments (C++ only).
2240 CheckExtraCXXDefaultArguments(D);
2243 DiagnoseFunctionSpecifiers(D);
2245 if (D.getDeclSpec().isThreadSpecified())
2246 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2248 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, TInfo);
2249 if (!NewTD) return 0;
2251 // Handle attributes prior to checking for duplicates in MergeVarDecl
2252 ProcessDeclAttributes(S, NewTD, D);
2254 // Merge the decl with the existing one if appropriate. If the decl is
2255 // in an outer scope, it isn't the same thing.
2256 FilterLookupForScope(*this, Previous, DC, S, /*ConsiderLinkage*/ false);
2257 if (!Previous.empty()) {
2258 Redeclaration = true;
2259 MergeTypeDefDecl(NewTD, Previous);
2262 // C99 6.7.7p2: If a typedef name specifies a variably modified type
2263 // then it shall have block scope.
2264 QualType T = NewTD->getUnderlyingType();
2265 if (T->isVariablyModifiedType()) {
2266 CurFunctionNeedsScopeChecking = true;
2268 if (S->getFnParent() == 0) {
2269 bool SizeIsNegative;
2271 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
2272 if (!FixedTy.isNull()) {
2273 Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size);
2274 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
2277 Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size);
2278 else if (T->isVariableArrayType())
2279 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
2281 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
2282 NewTD->setInvalidDecl();
2287 // If this is the C FILE type, notify the AST context.
2288 if (IdentifierInfo *II = NewTD->getIdentifier())
2289 if (!NewTD->isInvalidDecl() &&
2290 NewTD->getDeclContext()->getLookupContext()->isTranslationUnit()) {
2291 if (II->isStr("FILE"))
2292 Context.setFILEDecl(NewTD);
2293 else if (II->isStr("jmp_buf"))
2294 Context.setjmp_bufDecl(NewTD);
2295 else if (II->isStr("sigjmp_buf"))
2296 Context.setsigjmp_bufDecl(NewTD);
2302 /// \brief Determines whether the given declaration is an out-of-scope
2303 /// previous declaration.
2305 /// This routine should be invoked when name lookup has found a
2306 /// previous declaration (PrevDecl) that is not in the scope where a
2307 /// new declaration by the same name is being introduced. If the new
2308 /// declaration occurs in a local scope, previous declarations with
2309 /// linkage may still be considered previous declarations (C99
2310 /// 6.2.2p4-5, C++ [basic.link]p6).
2312 /// \param PrevDecl the previous declaration found by name
2315 /// \param DC the context in which the new declaration is being
2318 /// \returns true if PrevDecl is an out-of-scope previous declaration
2319 /// for a new delcaration with the same name.
2321 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
2322 ASTContext &Context) {
2326 if (!PrevDecl->hasLinkage())
2329 if (Context.getLangOptions().CPlusPlus) {
2330 // C++ [basic.link]p6:
2331 // If there is a visible declaration of an entity with linkage
2332 // having the same name and type, ignoring entities declared
2333 // outside the innermost enclosing namespace scope, the block
2334 // scope declaration declares that same entity and receives the
2335 // linkage of the previous declaration.
2336 DeclContext *OuterContext = DC->getLookupContext();
2337 if (!OuterContext->isFunctionOrMethod())
2338 // This rule only applies to block-scope declarations.
2341 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
2342 if (PrevOuterContext->isRecord())
2343 // We found a member function: ignore it.
2346 // Find the innermost enclosing namespace for the new and
2347 // previous declarations.
2348 while (!OuterContext->isFileContext())
2349 OuterContext = OuterContext->getParent();
2350 while (!PrevOuterContext->isFileContext())
2351 PrevOuterContext = PrevOuterContext->getParent();
2353 // The previous declaration is in a different namespace, so it
2354 // isn't the same function.
2355 if (OuterContext->getPrimaryContext() !=
2356 PrevOuterContext->getPrimaryContext())
2366 Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2367 QualType R, TypeSourceInfo *TInfo,
2368 LookupResult &Previous,
2369 MultiTemplateParamsArg TemplateParamLists,
2370 bool &Redeclaration) {
2371 DeclarationName Name = GetNameForDeclarator(D);
2373 // Check that there are no default arguments (C++ only).
2374 if (getLangOptions().CPlusPlus)
2375 CheckExtraCXXDefaultArguments(D);
2378 VarDecl::StorageClass SC;
2379 switch (D.getDeclSpec().getStorageClassSpec()) {
2380 default: assert(0 && "Unknown storage class!");
2381 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
2382 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
2383 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
2384 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
2385 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
2386 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
2387 case DeclSpec::SCS_mutable:
2388 // mutable can only appear on non-static class members, so it's always
2390 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
2396 IdentifierInfo *II = Name.getAsIdentifierInfo();
2398 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
2399 << Name.getAsString();
2403 DiagnoseFunctionSpecifiers(D);
2405 if (!DC->isRecord() && S->getFnParent() == 0) {
2406 // C99 6.9p2: The storage-class specifiers auto and register shall not
2407 // appear in the declaration specifiers in an external declaration.
2408 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
2410 // If this is a register variable with an asm label specified, then this
2411 // is a GNU extension.
2412 if (SC == VarDecl::Register && D.getAsmLabel())
2413 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
2415 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
2419 if (DC->isRecord() && !CurContext->isRecord()) {
2420 // This is an out-of-line definition of a static data member.
2421 if (SC == VarDecl::Static) {
2422 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2423 diag::err_static_out_of_line)
2424 << CodeModificationHint::CreateRemoval(
2425 D.getDeclSpec().getStorageClassSpecLoc());
2426 } else if (SC == VarDecl::None)
2427 SC = VarDecl::Static;
2429 if (SC == VarDecl::Static) {
2430 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
2431 if (RD->isLocalClass())
2432 Diag(D.getIdentifierLoc(),
2433 diag::err_static_data_member_not_allowed_in_local_class)
2434 << Name << RD->getDeclName();
2438 // Match up the template parameter lists with the scope specifier, then
2439 // determine whether we have a template or a template specialization.
2440 bool isExplicitSpecialization = false;
2441 if (TemplateParameterList *TemplateParams
2442 = MatchTemplateParametersToScopeSpecifier(
2443 D.getDeclSpec().getSourceRange().getBegin(),
2444 D.getCXXScopeSpec(),
2445 (TemplateParameterList**)TemplateParamLists.get(),
2446 TemplateParamLists.size(),
2447 isExplicitSpecialization)) {
2448 if (TemplateParams->size() > 0) {
2449 // There is no such thing as a variable template.
2450 Diag(D.getIdentifierLoc(), diag::err_template_variable)
2452 << SourceRange(TemplateParams->getTemplateLoc(),
2453 TemplateParams->getRAngleLoc());
2456 // There is an extraneous 'template<>' for this variable. Complain
2457 // about it, but allow the declaration of the variable.
2458 Diag(TemplateParams->getTemplateLoc(),
2459 diag::err_template_variable_noparams)
2461 << SourceRange(TemplateParams->getTemplateLoc(),
2462 TemplateParams->getRAngleLoc());
2464 isExplicitSpecialization = true;
2468 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
2471 if (D.isInvalidType())
2472 NewVD->setInvalidDecl();
2474 if (D.getDeclSpec().isThreadSpecified()) {
2475 if (NewVD->hasLocalStorage())
2476 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
2477 else if (!Context.Target.isTLSSupported())
2478 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
2480 NewVD->setThreadSpecified(true);
2483 // Set the lexical context. If the declarator has a C++ scope specifier, the
2484 // lexical context will be different from the semantic context.
2485 NewVD->setLexicalDeclContext(CurContext);
2487 // Handle attributes prior to checking for duplicates in MergeVarDecl
2488 ProcessDeclAttributes(S, NewVD, D);
2490 // Handle GNU asm-label extension (encoded as an attribute).
2491 if (Expr *E = (Expr*) D.getAsmLabel()) {
2492 // The parser guarantees this is a string.
2493 StringLiteral *SE = cast<StringLiteral>(E);
2494 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getString()));
2497 // Don't consider existing declarations that are in a different
2498 // scope and are out-of-semantic-context declarations (if the new
2499 // declaration has linkage).
2500 FilterLookupForScope(*this, Previous, DC, S, NewVD->hasLinkage());
2502 // Merge the decl with the existing one if appropriate.
2503 if (!Previous.empty()) {
2504 if (Previous.isSingleResult() &&
2505 isa<FieldDecl>(Previous.getFoundDecl()) &&
2506 D.getCXXScopeSpec().isSet()) {
2507 // The user tried to define a non-static data member
2508 // out-of-line (C++ [dcl.meaning]p1).
2509 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
2510 << D.getCXXScopeSpec().getRange();
2512 NewVD->setInvalidDecl();
2514 } else if (D.getCXXScopeSpec().isSet()) {
2515 // No previous declaration in the qualifying scope.
2516 Diag(D.getIdentifierLoc(), diag::err_no_member)
2517 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
2518 << D.getCXXScopeSpec().getRange();
2519 NewVD->setInvalidDecl();
2522 CheckVariableDeclaration(NewVD, Previous, Redeclaration);
2524 // This is an explicit specialization of a static data member. Check it.
2525 if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
2526 CheckMemberSpecialization(NewVD, Previous))
2527 NewVD->setInvalidDecl();
2529 // attributes declared post-definition are currently ignored
2530 if (Previous.isSingleResult()) {
2531 const VarDecl *Def = 0;
2532 VarDecl *PrevDecl = dyn_cast<VarDecl>(Previous.getFoundDecl());
2533 if (PrevDecl && PrevDecl->getDefinition(Def) && D.hasAttributes()) {
2534 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
2535 Diag(Def->getLocation(), diag::note_previous_definition);
2539 // If this is a locally-scoped extern C variable, update the map of
2541 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
2542 !NewVD->isInvalidDecl())
2543 RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
2548 /// \brief Perform semantic checking on a newly-created variable
2551 /// This routine performs all of the type-checking required for a
2552 /// variable declaration once it has been built. It is used both to
2553 /// check variables after they have been parsed and their declarators
2554 /// have been translated into a declaration, and to check variables
2555 /// that have been instantiated from a template.
2557 /// Sets NewVD->isInvalidDecl() if an error was encountered.
2558 void Sema::CheckVariableDeclaration(VarDecl *NewVD,
2559 LookupResult &Previous,
2560 bool &Redeclaration) {
2561 // If the decl is already known invalid, don't check it.
2562 if (NewVD->isInvalidDecl())
2565 QualType T = NewVD->getType();
2567 if (T->isObjCInterfaceType()) {
2568 Diag(NewVD->getLocation(), diag::err_statically_allocated_object);
2569 return NewVD->setInvalidDecl();
2572 // Emit an error if an address space was applied to decl with local storage.
2573 // This includes arrays of objects with address space qualifiers, but not
2574 // automatic variables that point to other address spaces.
2575 // ISO/IEC TR 18037 S5.1.2
2576 if (NewVD->hasLocalStorage() && (T.getAddressSpace() != 0)) {
2577 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
2578 return NewVD->setInvalidDecl();
2581 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
2582 && !NewVD->hasAttr<BlocksAttr>())
2583 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
2585 bool isVM = T->isVariablyModifiedType();
2586 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
2587 NewVD->hasAttr<BlocksAttr>())
2588 CurFunctionNeedsScopeChecking = true;
2590 if ((isVM && NewVD->hasLinkage()) ||
2591 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
2592 bool SizeIsNegative;
2594 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
2596 if (FixedTy.isNull() && T->isVariableArrayType()) {
2597 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
2598 // FIXME: This won't give the correct result for
2600 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
2602 if (NewVD->isFileVarDecl())
2603 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
2605 else if (NewVD->getStorageClass() == VarDecl::Static)
2606 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
2609 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
2611 return NewVD->setInvalidDecl();
2614 if (FixedTy.isNull()) {
2615 if (NewVD->isFileVarDecl())
2616 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
2618 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
2619 return NewVD->setInvalidDecl();
2622 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
2623 NewVD->setType(FixedTy);
2626 if (Previous.empty() && NewVD->isExternC()) {
2627 // Since we did not find anything by this name and we're declaring
2628 // an extern "C" variable, look for a non-visible extern "C"
2629 // declaration with the same name.
2630 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
2631 = LocallyScopedExternalDecls.find(NewVD->getDeclName());
2632 if (Pos != LocallyScopedExternalDecls.end())
2633 Previous.addDecl(Pos->second);
2636 if (T->isVoidType() && !NewVD->hasExternalStorage()) {
2637 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
2639 return NewVD->setInvalidDecl();
2642 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
2643 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
2644 return NewVD->setInvalidDecl();
2647 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
2648 Diag(NewVD->getLocation(), diag::err_block_on_vm);
2649 return NewVD->setInvalidDecl();
2652 if (!Previous.empty()) {
2653 Redeclaration = true;
2654 MergeVarDecl(NewVD, Previous);
2658 /// \brief Data used with FindOverriddenMethod
2659 struct FindOverriddenMethodData {
2661 CXXMethodDecl *Method;
2664 /// \brief Member lookup function that determines whether a given C++
2665 /// method overrides a method in a base class, to be used with
2666 /// CXXRecordDecl::lookupInBases().
2667 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
2670 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
2672 FindOverriddenMethodData *Data
2673 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
2675 DeclarationName Name = Data->Method->getDeclName();
2677 // FIXME: Do we care about other names here too?
2678 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
2679 // We really want to find the base class constructor here.
2680 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
2681 CanQualType CT = Data->S->Context.getCanonicalType(T);
2683 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
2686 for (Path.Decls = BaseRecord->lookup(Name);
2687 Path.Decls.first != Path.Decls.second;
2688 ++Path.Decls.first) {
2689 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*Path.Decls.first)) {
2690 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD))
2698 /// AddOverriddenMethods - See if a method overrides any in the base classes,
2699 /// and if so, check that it's a valid override and remember it.
2700 void Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2701 // Look for virtual methods in base classes that this method might override.
2703 FindOverriddenMethodData Data;
2706 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
2707 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
2708 E = Paths.found_decls_end(); I != E; ++I) {
2709 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
2710 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
2711 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
2712 !CheckOverridingFunctionAttributes(MD, OldMD))
2713 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
2720 Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2721 QualType R, TypeSourceInfo *TInfo,
2722 LookupResult &Previous,
2723 MultiTemplateParamsArg TemplateParamLists,
2724 bool IsFunctionDefinition, bool &Redeclaration) {
2725 assert(R.getTypePtr()->isFunctionType());
2727 DeclarationName Name = GetNameForDeclarator(D);
2728 FunctionDecl::StorageClass SC = FunctionDecl::None;
2729 switch (D.getDeclSpec().getStorageClassSpec()) {
2730 default: assert(0 && "Unknown storage class!");
2731 case DeclSpec::SCS_auto:
2732 case DeclSpec::SCS_register:
2733 case DeclSpec::SCS_mutable:
2734 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2735 diag::err_typecheck_sclass_func);
2738 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
2739 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
2740 case DeclSpec::SCS_static: {
2741 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
2743 // The declaration of an identifier for a function that has
2744 // block scope shall have no explicit storage-class specifier
2745 // other than extern
2746 // See also (C++ [dcl.stc]p4).
2747 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2748 diag::err_static_block_func);
2749 SC = FunctionDecl::None;
2751 SC = FunctionDecl::Static;
2754 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
2757 if (D.getDeclSpec().isThreadSpecified())
2758 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2760 bool isFriend = D.getDeclSpec().isFriendSpecified();
2761 bool isInline = D.getDeclSpec().isInlineSpecified();
2762 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
2763 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
2765 // Check that the return type is not an abstract class type.
2766 // For record types, this is done by the AbstractClassUsageDiagnoser once
2767 // the class has been completely parsed.
2768 if (!DC->isRecord() &&
2769 RequireNonAbstractType(D.getIdentifierLoc(),
2770 R->getAs<FunctionType>()->getResultType(),
2771 diag::err_abstract_type_in_decl,
2772 AbstractReturnType))
2775 // Do not allow returning a objc interface by-value.
2776 if (R->getAs<FunctionType>()->getResultType()->isObjCInterfaceType()) {
2777 Diag(D.getIdentifierLoc(),
2778 diag::err_object_cannot_be_passed_returned_by_value) << 0
2779 << R->getAs<FunctionType>()->getResultType();
2783 bool isVirtualOkay = false;
2784 FunctionDecl *NewFD;
2787 // C++ [class.friend]p5
2788 // A function can be defined in a friend declaration of a
2789 // class . . . . Such a function is implicitly inline.
2790 isInline |= IsFunctionDefinition;
2793 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
2794 // This is a C++ constructor declaration.
2795 assert(DC->isRecord() &&
2796 "Constructors can only be declared in a member context");
2798 R = CheckConstructorDeclarator(D, R, SC);
2800 // Create the new declaration
2801 NewFD = CXXConstructorDecl::Create(Context,
2802 cast<CXXRecordDecl>(DC),
2803 D.getIdentifierLoc(), Name, R, TInfo,
2804 isExplicit, isInline,
2805 /*isImplicitlyDeclared=*/false);
2806 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
2807 // This is a C++ destructor declaration.
2808 if (DC->isRecord()) {
2809 R = CheckDestructorDeclarator(D, SC);
2811 NewFD = CXXDestructorDecl::Create(Context,
2812 cast<CXXRecordDecl>(DC),
2813 D.getIdentifierLoc(), Name, R,
2815 /*isImplicitlyDeclared=*/false);
2817 isVirtualOkay = true;
2819 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
2821 // Create a FunctionDecl to satisfy the function definition parsing
2823 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
2824 Name, R, TInfo, SC, isInline,
2825 /*hasPrototype=*/true);
2828 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2829 if (!DC->isRecord()) {
2830 Diag(D.getIdentifierLoc(),
2831 diag::err_conv_function_not_member);
2835 CheckConversionDeclarator(D, R, SC);
2836 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
2837 D.getIdentifierLoc(), Name, R, TInfo,
2838 isInline, isExplicit);
2840 isVirtualOkay = true;
2841 } else if (DC->isRecord()) {
2842 // If the of the function is the same as the name of the record, then this
2843 // must be an invalid constructor that has a return type.
2844 // (The parser checks for a return type and makes the declarator a
2845 // constructor if it has no return type).
2846 // must have an invalid constructor that has a return type
2847 if (Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
2848 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
2849 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2850 << SourceRange(D.getIdentifierLoc());
2854 bool isStatic = SC == FunctionDecl::Static;
2857 // Any allocation function for a class T is a static member
2858 // (even if not explicitly declared static).
2859 if (Name.getCXXOverloadedOperator() == OO_New ||
2860 Name.getCXXOverloadedOperator() == OO_Array_New)
2863 // [class.free]p6 Any deallocation function for a class X is a static member
2864 // (even if not explicitly declared static).
2865 if (Name.getCXXOverloadedOperator() == OO_Delete ||
2866 Name.getCXXOverloadedOperator() == OO_Array_Delete)
2869 // This is a C++ method declaration.
2870 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
2871 D.getIdentifierLoc(), Name, R, TInfo,
2872 isStatic, isInline);
2874 isVirtualOkay = !isStatic;
2876 // Determine whether the function was written with a
2877 // prototype. This true when:
2878 // - we're in C++ (where every function has a prototype),
2879 // - there is a prototype in the declarator, or
2880 // - the type R of the function is some kind of typedef or other reference
2881 // to a type name (which eventually refers to a function type).
2883 getLangOptions().CPlusPlus ||
2884 (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) ||
2885 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
2887 NewFD = FunctionDecl::Create(Context, DC,
2888 D.getIdentifierLoc(),
2889 Name, R, TInfo, SC, isInline, HasPrototype);
2892 if (D.isInvalidType())
2893 NewFD->setInvalidDecl();
2895 // Set the lexical context. If the declarator has a C++
2896 // scope specifier, or is the object of a friend declaration, the
2897 // lexical context will be different from the semantic context.
2898 NewFD->setLexicalDeclContext(CurContext);
2900 // Match up the template parameter lists with the scope specifier, then
2901 // determine whether we have a template or a template specialization.
2902 FunctionTemplateDecl *FunctionTemplate = 0;
2903 bool isExplicitSpecialization = false;
2904 bool isFunctionTemplateSpecialization = false;
2905 if (TemplateParameterList *TemplateParams
2906 = MatchTemplateParametersToScopeSpecifier(
2907 D.getDeclSpec().getSourceRange().getBegin(),
2908 D.getCXXScopeSpec(),
2909 (TemplateParameterList**)TemplateParamLists.get(),
2910 TemplateParamLists.size(),
2911 isExplicitSpecialization)) {
2912 if (TemplateParams->size() > 0) {
2913 // This is a function template
2915 // Check that we can declare a template here.
2916 if (CheckTemplateDeclScope(S, TemplateParams))
2919 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
2920 NewFD->getLocation(),
2921 Name, TemplateParams,
2923 FunctionTemplate->setLexicalDeclContext(CurContext);
2924 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
2926 // This is a function template specialization.
2927 isFunctionTemplateSpecialization = true;
2930 // FIXME: Free this memory properly.
2931 TemplateParamLists.release();
2934 // C++ [dcl.fct.spec]p5:
2935 // The virtual specifier shall only be used in declarations of
2936 // nonstatic class member functions that appear within a
2937 // member-specification of a class declaration; see 10.3.
2939 if (isVirtual && !NewFD->isInvalidDecl()) {
2940 if (!isVirtualOkay) {
2941 Diag(D.getDeclSpec().getVirtualSpecLoc(),
2942 diag::err_virtual_non_function);
2943 } else if (!CurContext->isRecord()) {
2944 // 'virtual' was specified outside of the class.
2945 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class)
2946 << CodeModificationHint::CreateRemoval(
2947 D.getDeclSpec().getVirtualSpecLoc());
2949 // Okay: Add virtual to the method.
2950 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC);
2951 CurClass->setMethodAsVirtual(NewFD);
2955 // Filter out previous declarations that don't match the scope.
2956 FilterLookupForScope(*this, Previous, DC, S, NewFD->hasLinkage());
2959 // DC is the namespace in which the function is being declared.
2960 assert((DC->isFileContext() || !Previous.empty()) &&
2961 "previously-undeclared friend function being created "
2962 "in a non-namespace context");
2964 if (FunctionTemplate) {
2965 FunctionTemplate->setObjectOfFriendDecl(
2966 /* PreviouslyDeclared= */ !Previous.empty());
2967 FunctionTemplate->setAccess(AS_public);
2970 NewFD->setObjectOfFriendDecl(/* PreviouslyDeclared= */ !Previous.empty());
2972 NewFD->setAccess(AS_public);
2975 if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) &&
2976 !CurContext->isRecord()) {
2977 // C++ [class.static]p1:
2978 // A data or function member of a class may be declared static
2979 // in a class definition, in which case it is a static member of
2982 // Complain about the 'static' specifier if it's on an out-of-line
2983 // member function definition.
2984 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2985 diag::err_static_out_of_line)
2986 << CodeModificationHint::CreateRemoval(
2987 D.getDeclSpec().getStorageClassSpecLoc());
2990 // Handle GNU asm-label extension (encoded as an attribute).
2991 if (Expr *E = (Expr*) D.getAsmLabel()) {
2992 // The parser guarantees this is a string.
2993 StringLiteral *SE = cast<StringLiteral>(E);
2994 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getString()));
2997 // Copy the parameter declarations from the declarator D to the function
2998 // declaration NewFD, if they are available. First scavenge them into Params.
2999 llvm::SmallVector<ParmVarDecl*, 16> Params;
3000 if (D.getNumTypeObjects() > 0) {
3001 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3003 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
3004 // function that takes no arguments, not a function that takes a
3005 // single void argument.
3006 // We let through "const void" here because Sema::GetTypeForDeclarator
3007 // already checks for that case.
3008 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3009 FTI.ArgInfo[0].Param &&
3010 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()) {
3011 // Empty arg list, don't push any params.
3012 ParmVarDecl *Param = FTI.ArgInfo[0].Param.getAs<ParmVarDecl>();
3014 // In C++, the empty parameter-type-list must be spelled "void"; a
3015 // typedef of void is not permitted.
3016 if (getLangOptions().CPlusPlus &&
3017 Param->getType().getUnqualifiedType() != Context.VoidTy)
3018 Diag(Param->getLocation(), diag::err_param_typedef_of_void);
3019 // FIXME: Leaks decl?
3020 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
3021 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
3022 ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
3023 assert(Param->getDeclContext() != NewFD && "Was set before ?");
3024 Param->setDeclContext(NewFD);
3025 Params.push_back(Param);
3029 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
3030 // When we're declaring a function with a typedef, typeof, etc as in the
3031 // following example, we'll need to synthesize (unnamed)
3032 // parameters for use in the declaration.
3035 // typedef void fn(int);
3039 // Synthesize a parameter for each argument type.
3040 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
3041 AE = FT->arg_type_end(); AI != AE; ++AI) {
3042 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC,
3043 SourceLocation(), 0,
3046 Param->setImplicit();
3047 Params.push_back(Param);
3050 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
3051 "Should not need args for typedef of non-prototype fn");
3053 // Finally, we know we have the right number of parameters, install them.
3054 NewFD->setParams(Context, Params.data(), Params.size());
3056 // If the declarator is a template-id, translate the parser's template
3057 // argument list into our AST format.
3058 bool HasExplicitTemplateArgs = false;
3059 TemplateArgumentListInfo TemplateArgs;
3060 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
3061 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3062 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
3063 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
3064 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3065 TemplateId->getTemplateArgs(),
3066 TemplateId->NumArgs);
3067 translateTemplateArguments(TemplateArgsPtr,
3069 TemplateArgsPtr.release();
3071 HasExplicitTemplateArgs = true;
3073 if (FunctionTemplate) {
3074 // FIXME: Diagnose function template with explicit template
3076 HasExplicitTemplateArgs = false;
3077 } else if (!isFunctionTemplateSpecialization &&
3078 !D.getDeclSpec().isFriendSpecified()) {
3079 // We have encountered something that the user meant to be a
3080 // specialization (because it has explicitly-specified template
3081 // arguments) but that was not introduced with a "template<>" (or had
3082 // too few of them).
3083 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
3084 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
3085 << CodeModificationHint::CreateInsertion(
3086 D.getDeclSpec().getSourceRange().getBegin(),
3088 isFunctionTemplateSpecialization = true;
3092 if (isFunctionTemplateSpecialization) {
3093 if (CheckFunctionTemplateSpecialization(NewFD,
3094 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
3096 NewFD->setInvalidDecl();
3097 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD) &&
3098 CheckMemberSpecialization(NewFD, Previous))
3099 NewFD->setInvalidDecl();
3101 // Perform semantic checking on the function declaration.
3102 bool OverloadableAttrRequired = false; // FIXME: HACK!
3103 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization,
3104 Redeclaration, /*FIXME:*/OverloadableAttrRequired);
3106 assert((NewFD->isInvalidDecl() || !Redeclaration ||
3107 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
3108 "previous declaration set still overloaded");
3110 // If we have a function template, check the template parameter
3111 // list. This will check and merge default template arguments.
3112 if (FunctionTemplate) {
3113 FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration();
3114 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
3115 PrevTemplate? PrevTemplate->getTemplateParameters() : 0,
3116 D.getDeclSpec().isFriendSpecified()? TPC_FriendFunctionTemplate
3117 : TPC_FunctionTemplate);
3120 if (D.getCXXScopeSpec().isSet() && !NewFD->isInvalidDecl()) {
3121 // An out-of-line member function declaration must also be a
3122 // definition (C++ [dcl.meaning]p1).
3123 // Note that this is not the case for explicit specializations of
3124 // function templates or member functions of class templates, per
3125 // C++ [temp.expl.spec]p2.
3126 if (!IsFunctionDefinition && !isFriend &&
3127 !isFunctionTemplateSpecialization && !isExplicitSpecialization) {
3128 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
3129 << D.getCXXScopeSpec().getRange();
3130 NewFD->setInvalidDecl();
3131 } else if (!Redeclaration) {
3132 // The user tried to provide an out-of-line definition for a
3133 // function that is a member of a class or namespace, but there
3134 // was no such member function declared (C++ [class.mfct]p2,
3135 // C++ [namespace.memdef]p2). For example:
3141 // void X::f() { } // ill-formed
3143 // Complain about this problem, and attempt to suggest close
3144 // matches (e.g., those that differ only in cv-qualifiers and
3145 // whether the parameter types are references).
3146 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
3147 << Name << DC << D.getCXXScopeSpec().getRange();
3148 NewFD->setInvalidDecl();
3150 LookupResult Prev(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
3152 LookupQualifiedName(Prev, DC);
3153 assert(!Prev.isAmbiguous() &&
3154 "Cannot have an ambiguity in previous-declaration lookup");
3155 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
3156 Func != FuncEnd; ++Func) {
3157 if (isa<FunctionDecl>(*Func) &&
3158 isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
3159 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
3164 // Handle attributes. We need to have merged decls when handling attributes
3165 // (for example to check for conflicts, etc).
3166 // FIXME: This needs to happen before we merge declarations. Then,
3167 // let attribute merging cope with attribute conflicts.
3168 ProcessDeclAttributes(S, NewFD, D);
3170 // attributes declared post-definition are currently ignored
3171 if (Redeclaration && Previous.isSingleResult()) {
3172 const FunctionDecl *Def;
3173 FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
3174 if (PrevFD && PrevFD->getBody(Def) && D.hasAttributes()) {
3175 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
3176 Diag(Def->getLocation(), diag::note_previous_definition);
3180 AddKnownFunctionAttributes(NewFD);
3182 if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) {
3183 // If a function name is overloadable in C, then every function
3184 // with that name must be marked "overloadable".
3185 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
3186 << Redeclaration << NewFD;
3187 if (!Previous.empty())
3188 Diag(Previous.getRepresentativeDecl()->getLocation(),
3189 diag::note_attribute_overloadable_prev_overload);
3190 NewFD->addAttr(::new (Context) OverloadableAttr());
3193 // If this is a locally-scoped extern C function, update the
3194 // map of such names.
3195 if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
3196 && !NewFD->isInvalidDecl())
3197 RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
3199 // Set this FunctionDecl's range up to the right paren.
3200 NewFD->setLocEnd(D.getSourceRange().getEnd());
3202 if (FunctionTemplate && NewFD->isInvalidDecl())
3203 FunctionTemplate->setInvalidDecl();
3205 if (FunctionTemplate)
3206 return FunctionTemplate;
3211 /// \brief Perform semantic checking of a new function declaration.
3213 /// Performs semantic analysis of the new function declaration
3214 /// NewFD. This routine performs all semantic checking that does not
3215 /// require the actual declarator involved in the declaration, and is
3216 /// used both for the declaration of functions as they are parsed
3217 /// (called via ActOnDeclarator) and for the declaration of functions
3218 /// that have been instantiated via C++ template instantiation (called
3219 /// via InstantiateDecl).
3221 /// \param IsExplicitSpecialiation whether this new function declaration is
3222 /// an explicit specialization of the previous declaration.
3224 /// This sets NewFD->isInvalidDecl() to true if there was an error.
3225 void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
3226 LookupResult &Previous,
3227 bool IsExplicitSpecialization,
3228 bool &Redeclaration,
3229 bool &OverloadableAttrRequired) {
3230 // If NewFD is already known erroneous, don't do any of this checking.
3231 if (NewFD->isInvalidDecl())
3234 if (NewFD->getResultType()->isVariablyModifiedType()) {
3235 // Functions returning a variably modified type violate C99 6.7.5.2p2
3236 // because all functions have linkage.
3237 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
3238 return NewFD->setInvalidDecl();
3241 if (NewFD->isMain())
3244 // Check for a previous declaration of this name.
3245 if (Previous.empty() && NewFD->isExternC()) {
3246 // Since we did not find anything by this name and we're declaring
3247 // an extern "C" function, look for a non-visible extern "C"
3248 // declaration with the same name.
3249 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3250 = LocallyScopedExternalDecls.find(NewFD->getDeclName());
3251 if (Pos != LocallyScopedExternalDecls.end())
3252 Previous.addDecl(Pos->second);
3255 // Merge or overload the declaration with an existing declaration of
3256 // the same name, if appropriate.
3257 if (!Previous.empty()) {
3258 // Determine whether NewFD is an overload of PrevDecl or
3259 // a declaration that requires merging. If it's an overload,
3260 // there's no more work to do here; we'll just add the new
3261 // function to the scope.
3263 NamedDecl *OldDecl = 0;
3264 if (!AllowOverloadingOfFunction(Previous, Context)) {
3265 Redeclaration = true;
3266 OldDecl = Previous.getFoundDecl();
3268 if (!getLangOptions().CPlusPlus) {
3269 OverloadableAttrRequired = true;
3271 // Functions marked "overloadable" must have a prototype (that
3272 // we can't get through declaration merging).
3273 if (!NewFD->getType()->getAs<FunctionProtoType>()) {
3274 Diag(NewFD->getLocation(),
3275 diag::err_attribute_overloadable_no_prototype)
3277 Redeclaration = true;
3279 // Turn this into a variadic function with no parameters.
3280 QualType R = Context.getFunctionType(
3281 NewFD->getType()->getAs<FunctionType>()->getResultType(),
3284 return NewFD->setInvalidDecl();
3288 switch (CheckOverload(NewFD, Previous, OldDecl)) {
3290 Redeclaration = true;
3291 if (isa<UsingShadowDecl>(OldDecl) && CurContext->isRecord()) {
3292 HideUsingShadowDecl(S, cast<UsingShadowDecl>(OldDecl));
3293 Redeclaration = false;
3297 case Ovl_NonFunction:
3298 Redeclaration = true;
3302 Redeclaration = false;
3307 if (Redeclaration) {
3308 // NewFD and OldDecl represent declarations that need to be
3310 if (MergeFunctionDecl(NewFD, OldDecl))
3311 return NewFD->setInvalidDecl();
3314 Previous.addDecl(OldDecl);
3316 if (FunctionTemplateDecl *OldTemplateDecl
3317 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
3318 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
3319 FunctionTemplateDecl *NewTemplateDecl
3320 = NewFD->getDescribedFunctionTemplate();
3321 assert(NewTemplateDecl && "Template/non-template mismatch");
3322 if (CXXMethodDecl *Method
3323 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
3324 Method->setAccess(OldTemplateDecl->getAccess());
3325 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
3328 // If this is an explicit specialization of a member that is a function
3329 // template, mark it as a member specialization.
3330 if (IsExplicitSpecialization &&
3331 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
3332 NewTemplateDecl->setMemberSpecialization();
3333 assert(OldTemplateDecl->isMemberSpecialization());
3336 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
3337 NewFD->setAccess(OldDecl->getAccess());
3338 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
3343 // Semantic checking for this function declaration (in isolation).
3344 if (getLangOptions().CPlusPlus) {
3345 // C++-specific checks.
3346 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
3347 CheckConstructor(Constructor);
3348 } else if (CXXDestructorDecl *Destructor =
3349 dyn_cast<CXXDestructorDecl>(NewFD)) {
3350 CXXRecordDecl *Record = Destructor->getParent();
3351 QualType ClassType = Context.getTypeDeclType(Record);
3353 // FIXME: Shouldn't we be able to perform thisc heck even when the class
3354 // type is dependent? Both gcc and edg can handle that.
3355 if (!ClassType->isDependentType()) {
3356 DeclarationName Name
3357 = Context.DeclarationNames.getCXXDestructorName(
3358 Context.getCanonicalType(ClassType));
3359 if (NewFD->getDeclName() != Name) {
3360 Diag(NewFD->getLocation(), diag::err_destructor_name);
3361 return NewFD->setInvalidDecl();
3365 Record->setUserDeclaredDestructor(true);
3366 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
3367 // user-defined destructor.
3368 Record->setPOD(false);
3370 // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly-
3371 // declared destructor.
3372 // FIXME: C++0x: don't do this for "= default" destructors
3373 Record->setHasTrivialDestructor(false);
3374 } else if (CXXConversionDecl *Conversion
3375 = dyn_cast<CXXConversionDecl>(NewFD)) {
3376 ActOnConversionDeclarator(Conversion);
3379 // Find any virtual functions that this function overrides.
3380 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
3381 if (!Method->isFunctionTemplateSpecialization() &&
3382 !Method->getDescribedFunctionTemplate())
3383 AddOverriddenMethods(Method->getParent(), Method);
3386 // Additional checks for the destructor; make sure we do this after we
3387 // figure out whether the destructor is virtual.
3388 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
3389 if (!Destructor->getParent()->isDependentType())
3390 CheckDestructor(Destructor);
3392 // Extra checking for C++ overloaded operators (C++ [over.oper]).
3393 if (NewFD->isOverloadedOperator() &&
3394 CheckOverloadedOperatorDeclaration(NewFD))
3395 return NewFD->setInvalidDecl();
3397 // In C++, check default arguments now that we have merged decls. Unless
3398 // the lexical context is the class, because in this case this is done
3399 // during delayed parsing anyway.
3400 if (!CurContext->isRecord())
3401 CheckCXXDefaultArguments(NewFD);
3405 void Sema::CheckMain(FunctionDecl* FD) {
3406 // C++ [basic.start.main]p3: A program that declares main to be inline
3407 // or static is ill-formed.
3408 // C99 6.7.4p4: In a hosted environment, the inline function specifier
3409 // shall not appear in a declaration of main.
3410 // static main is not an error under C99, but we should warn about it.
3411 bool isInline = FD->isInlineSpecified();
3412 bool isStatic = FD->getStorageClass() == FunctionDecl::Static;
3413 if (isInline || isStatic) {
3414 unsigned diagID = diag::warn_unusual_main_decl;
3415 if (isInline || getLangOptions().CPlusPlus)
3416 diagID = diag::err_unusual_main_decl;
3418 int which = isStatic + (isInline << 1) - 1;
3419 Diag(FD->getLocation(), diagID) << which;
3422 QualType T = FD->getType();
3423 assert(T->isFunctionType() && "function decl is not of function type");
3424 const FunctionType* FT = T->getAs<FunctionType>();
3426 if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
3427 // TODO: add a replacement fixit to turn the return type into 'int'.
3428 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
3429 FD->setInvalidDecl(true);
3432 // Treat protoless main() as nullary.
3433 if (isa<FunctionNoProtoType>(FT)) return;
3435 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
3436 unsigned nparams = FTP->getNumArgs();
3437 assert(FD->getNumParams() == nparams);
3439 bool HasExtraParameters = (nparams > 3);
3441 // Darwin passes an undocumented fourth argument of type char**. If
3442 // other platforms start sprouting these, the logic below will start
3445 Context.Target.getTriple().getOS() == llvm::Triple::Darwin)
3446 HasExtraParameters = false;
3448 if (HasExtraParameters) {
3449 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
3450 FD->setInvalidDecl(true);
3454 // FIXME: a lot of the following diagnostics would be improved
3455 // if we had some location information about types.
3458 Context.getPointerType(Context.getPointerType(Context.CharTy));
3459 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
3461 for (unsigned i = 0; i < nparams; ++i) {
3462 QualType AT = FTP->getArgType(i);
3464 bool mismatch = true;
3466 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
3468 else if (Expected[i] == CharPP) {
3469 // As an extension, the following forms are okay:
3471 // char const * const *
3474 QualifierCollector qs;
3475 const PointerType* PT;
3476 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
3477 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
3478 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
3480 mismatch = !qs.empty();
3485 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
3486 // TODO: suggest replacing given type with expected type
3487 FD->setInvalidDecl(true);
3491 if (nparams == 1 && !FD->isInvalidDecl()) {
3492 Diag(FD->getLocation(), diag::warn_main_one_arg);
3496 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
3497 // FIXME: Need strict checking. In C89, we need to check for
3498 // any assignment, increment, decrement, function-calls, or
3499 // commas outside of a sizeof. In C99, it's the same list,
3500 // except that the aforementioned are allowed in unevaluated
3501 // expressions. Everything else falls under the
3502 // "may accept other forms of constant expressions" exception.
3503 // (We never end up here for C++, so the constant expression
3504 // rules there don't matter.)
3505 if (Init->isConstantInitializer(Context))
3507 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
3508 << Init->getSourceRange();
3512 void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init) {
3513 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
3516 /// AddInitializerToDecl - Adds the initializer Init to the
3517 /// declaration dcl. If DirectInit is true, this is C++ direct
3518 /// initialization rather than copy initialization.
3519 void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init, bool DirectInit) {
3520 Decl *RealDecl = dcl.getAs<Decl>();
3521 // If there is no declaration, there was an error parsing it. Just ignore
3526 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
3527 // With declarators parsed the way they are, the parser cannot
3528 // distinguish between a normal initializer and a pure-specifier.
3529 // Thus this grotesque test.
3531 Expr *Init = static_cast<Expr *>(init.get());
3532 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
3533 Context.getCanonicalType(IL->getType()) == Context.IntTy)
3534 CheckPureMethod(Method, Init->getSourceRange());
3536 Diag(Method->getLocation(), diag::err_member_function_initialization)
3537 << Method->getDeclName() << Init->getSourceRange();
3538 Method->setInvalidDecl();
3543 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3545 if (getLangOptions().CPlusPlus &&
3546 RealDecl->getLexicalDeclContext()->isRecord() &&
3547 isa<NamedDecl>(RealDecl))
3548 Diag(RealDecl->getLocation(), diag::err_member_initialization)
3549 << cast<NamedDecl>(RealDecl)->getDeclName();
3551 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3552 RealDecl->setInvalidDecl();
3556 // A definition must end up with a complete type, which means it must be
3557 // complete with the restriction that an array type might be completed by the
3558 // initializer; note that later code assumes this restriction.
3559 QualType BaseDeclType = VDecl->getType();
3560 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
3561 BaseDeclType = Array->getElementType();
3562 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
3563 diag::err_typecheck_decl_incomplete_type)) {
3564 RealDecl->setInvalidDecl();
3568 // The variable can not have an abstract class type.
3569 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
3570 diag::err_abstract_type_in_decl,
3571 AbstractVariableType))
3572 VDecl->setInvalidDecl();
3574 const VarDecl *Def = 0;
3575 if (VDecl->getDefinition(Def)) {
3576 Diag(VDecl->getLocation(), diag::err_redefinition)
3577 << VDecl->getDeclName();
3578 Diag(Def->getLocation(), diag::note_previous_definition);
3579 VDecl->setInvalidDecl();
3583 // Take ownership of the expression, now that we're sure we have somewhere
3585 Expr *Init = init.takeAs<Expr>();
3586 assert(Init && "missing initializer");
3588 // Capture the variable that is being initialized and the style of
3590 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
3592 // FIXME: Poor source location information.
3593 InitializationKind Kind
3594 = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(),
3595 Init->getLocStart(),
3597 : InitializationKind::CreateCopy(VDecl->getLocation(),
3598 Init->getLocStart());
3600 // Get the decls type and save a reference for later, since
3601 // CheckInitializerTypes may change it.
3602 QualType DclT = VDecl->getType(), SavT = DclT;
3603 if (VDecl->isBlockVarDecl()) {
3604 if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
3605 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
3606 VDecl->setInvalidDecl();
3607 } else if (!VDecl->isInvalidDecl()) {
3608 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
3609 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3610 MultiExprArg(*this, (void**)&Init, 1),
3612 if (Result.isInvalid()) {
3613 VDecl->setInvalidDecl();
3617 Init = Result.takeAs<Expr>();
3619 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
3620 // Don't check invalid declarations to avoid emitting useless diagnostics.
3621 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
3622 if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4.
3623 CheckForConstantInitializer(Init, DclT);
3626 } else if (VDecl->isStaticDataMember() &&
3627 VDecl->getLexicalDeclContext()->isRecord()) {
3628 // This is an in-class initialization for a static data member, e.g.,
3631 // static const int value = 17;
3634 // Attach the initializer
3635 VDecl->setInit(Context, Init);
3637 // C++ [class.mem]p4:
3638 // A member-declarator can contain a constant-initializer only
3639 // if it declares a static member (9.4) of const integral or
3640 // const enumeration type, see 9.4.2.
3641 QualType T = VDecl->getType();
3642 if (!T->isDependentType() &&
3643 (!Context.getCanonicalType(T).isConstQualified() ||
3644 !T->isIntegralType())) {
3645 Diag(VDecl->getLocation(), diag::err_member_initialization)
3646 << VDecl->getDeclName() << Init->getSourceRange();
3647 VDecl->setInvalidDecl();
3649 // C++ [class.static.data]p4:
3650 // If a static data member is of const integral or const
3651 // enumeration type, its declaration in the class definition
3652 // can specify a constant-initializer which shall be an
3653 // integral constant expression (5.19).
3654 if (!Init->isTypeDependent() &&
3655 !Init->getType()->isIntegralType()) {
3656 // We have a non-dependent, non-integral or enumeration type.
3657 Diag(Init->getSourceRange().getBegin(),
3658 diag::err_in_class_initializer_non_integral_type)
3659 << Init->getType() << Init->getSourceRange();
3660 VDecl->setInvalidDecl();
3661 } else if (!Init->isTypeDependent() && !Init->isValueDependent()) {
3662 // Check whether the expression is a constant expression.
3665 if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) {
3666 Diag(Loc, diag::err_in_class_initializer_non_constant)
3667 << Init->getSourceRange();
3668 VDecl->setInvalidDecl();
3669 } else if (!VDecl->getType()->isDependentType())
3670 ImpCastExprToType(Init, VDecl->getType(), CastExpr::CK_IntegralCast);
3673 } else if (VDecl->isFileVarDecl()) {
3674 if (VDecl->getStorageClass() == VarDecl::Extern)
3675 Diag(VDecl->getLocation(), diag::warn_extern_init);
3676 if (!VDecl->isInvalidDecl()) {
3677 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
3678 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3679 MultiExprArg(*this, (void**)&Init, 1),
3681 if (Result.isInvalid()) {
3682 VDecl->setInvalidDecl();
3686 Init = Result.takeAs<Expr>();
3689 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
3690 // Don't check invalid declarations to avoid emitting useless diagnostics.
3691 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
3692 // C99 6.7.8p4. All file scoped initializers need to be constant.
3693 CheckForConstantInitializer(Init, DclT);
3696 // If the type changed, it means we had an incomplete type that was
3697 // completed by the initializer. For example:
3698 // int ary[] = { 1, 3, 5 };
3699 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
3700 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
3701 VDecl->setType(DclT);
3702 Init->setType(DclT);
3705 Init = MaybeCreateCXXExprWithTemporaries(Init);
3706 // Attach the initializer to the decl.
3707 VDecl->setInit(Context, Init);
3709 // If the previous declaration of VDecl was a tentative definition,
3710 // remove it from the set of tentative definitions.
3711 if (VDecl->getPreviousDeclaration() &&
3712 VDecl->getPreviousDeclaration()->isTentativeDefinition(Context)) {
3713 bool Deleted = TentativeDefinitions.erase(VDecl->getDeclName());
3714 assert(Deleted && "Unrecorded tentative definition?"); Deleted=Deleted;
3717 if (getLangOptions().CPlusPlus) {
3718 // Make sure we mark the destructor as used if necessary.
3719 QualType InitType = VDecl->getType();
3720 if (const ArrayType *Array = Context.getAsArrayType(InitType))
3721 InitType = Context.getBaseElementType(Array);
3722 if (InitType->isRecordType())
3723 FinalizeVarWithDestructor(VDecl, InitType);
3729 void Sema::ActOnUninitializedDecl(DeclPtrTy dcl,
3730 bool TypeContainsUndeducedAuto) {
3731 Decl *RealDecl = dcl.getAs<Decl>();
3733 // If there is no declaration, there was an error parsing it. Just ignore it.
3737 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
3738 QualType Type = Var->getType();
3740 // Record tentative definitions.
3741 if (Var->isTentativeDefinition(Context)) {
3742 std::pair<llvm::DenseMap<DeclarationName, VarDecl *>::iterator, bool>
3744 TentativeDefinitions.insert(std::make_pair(Var->getDeclName(), Var));
3746 // Keep the latest definition in the map. If we see 'int i; int i;' we
3747 // want the second one in the map.
3748 InsertPair.first->second = Var;
3750 // However, for the list, we don't care about the order, just make sure
3751 // that there are no dupes for a given declaration name.
3752 if (InsertPair.second)
3753 TentativeDefinitionList.push_back(Var->getDeclName());
3756 // C++ [dcl.init.ref]p3:
3757 // The initializer can be omitted for a reference only in a
3758 // parameter declaration (8.3.5), in the declaration of a
3759 // function return type, in the declaration of a class member
3760 // within its class declaration (9.2), and where the extern
3761 // specifier is explicitly used.
3762 if (Type->isReferenceType() && !Var->hasExternalStorage()) {
3763 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
3764 << Var->getDeclName()
3765 << SourceRange(Var->getLocation(), Var->getLocation());
3766 Var->setInvalidDecl();
3770 // C++0x [dcl.spec.auto]p3
3771 if (TypeContainsUndeducedAuto) {
3772 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
3773 << Var->getDeclName() << Type;
3774 Var->setInvalidDecl();
3778 // An array without size is an incomplete type, and there are no special
3779 // rules in C++ to make such a definition acceptable.
3780 if (getLangOptions().CPlusPlus && Type->isIncompleteArrayType() &&
3781 !Var->hasExternalStorage()) {
3782 Diag(Var->getLocation(),
3783 diag::err_typecheck_incomplete_array_needs_initializer);
3784 Var->setInvalidDecl();
3788 // C++ [temp.expl.spec]p15:
3789 // An explicit specialization of a static data member of a template is a
3790 // definition if the declaration includes an initializer; otherwise, it
3791 // is a declaration.
3792 if (Var->isStaticDataMember() &&
3793 Var->getInstantiatedFromStaticDataMember() &&
3794 Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3797 // C++ [dcl.init]p9:
3798 // If no initializer is specified for an object, and the object
3799 // is of (possibly cv-qualified) non-POD class type (or array
3800 // thereof), the object shall be default-initialized; if the
3801 // object is of const-qualified type, the underlying class type
3802 // shall have a user-declared default constructor.
3804 // FIXME: Diagnose the "user-declared default constructor" bit.
3805 if (getLangOptions().CPlusPlus) {
3806 QualType InitType = Type;
3807 if (const ArrayType *Array = Context.getAsArrayType(Type))
3808 InitType = Context.getBaseElementType(Array);
3809 if ((!Var->hasExternalStorage() && !Var->isExternC()) &&
3810 InitType->isRecordType() && !InitType->isDependentType()) {
3811 if (!RequireCompleteType(Var->getLocation(), InitType,
3812 diag::err_invalid_incomplete_type_use)) {
3813 InitializedEntity Entity
3814 = InitializedEntity::InitializeVariable(Var);
3815 InitializationKind Kind
3816 = InitializationKind::CreateDefault(Var->getLocation());
3818 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
3819 OwningExprResult Init = InitSeq.Perform(*this, Entity, Kind,
3820 MultiExprArg(*this, 0, 0));
3821 if (Init.isInvalid())
3822 Var->setInvalidDecl();
3824 Var->setInit(Context,
3825 MaybeCreateCXXExprWithTemporaries(Init.takeAs<Expr>()));
3826 FinalizeVarWithDestructor(Var, InitType);
3829 Var->setInvalidDecl();
3833 // The variable can not have an abstract class type.
3834 if (RequireNonAbstractType(Var->getLocation(), Type,
3835 diag::err_abstract_type_in_decl,
3836 AbstractVariableType))
3837 Var->setInvalidDecl();
3841 // FIXME: Temporarily disabled because we are not properly parsing
3842 // linkage specifications on declarations, e.g.,
3844 // extern "C" const CGPoint CGPointerZero;
3846 // C++ [dcl.init]p9:
3848 // If no initializer is specified for an object, and the
3849 // object is of (possibly cv-qualified) non-POD class type (or
3850 // array thereof), the object shall be default-initialized; if
3851 // the object is of const-qualified type, the underlying class
3852 // type shall have a user-declared default
3853 // constructor. Otherwise, if no initializer is specified for
3854 // an object, the object and its subobjects, if any, have an
3855 // indeterminate initial value; if the object or any of its
3856 // subobjects are of const-qualified type, the program is
3859 // This isn't technically an error in C, so we don't diagnose it.
3861 // FIXME: Actually perform the POD/user-defined default
3862 // constructor check.
3863 if (getLangOptions().CPlusPlus &&
3864 Context.getCanonicalType(Type).isConstQualified() &&
3865 !Var->hasExternalStorage())
3866 Diag(Var->getLocation(), diag::err_const_var_requires_init)
3868 << SourceRange(Var->getLocation(), Var->getLocation());
3873 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
3875 unsigned NumDecls) {
3876 llvm::SmallVector<Decl*, 8> Decls;
3878 if (DS.isTypeSpecOwned())
3879 Decls.push_back((Decl*)DS.getTypeRep());
3881 for (unsigned i = 0; i != NumDecls; ++i)
3882 if (Decl *D = Group[i].getAs<Decl>())
3885 // Perform semantic analysis that depends on having fully processed both
3886 // the declarator and initializer.
3887 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
3888 VarDecl *IDecl = dyn_cast<VarDecl>(Decls[i]);
3891 QualType T = IDecl->getType();
3893 // Block scope. C99 6.7p7: If an identifier for an object is declared with
3894 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
3895 if (IDecl->isBlockVarDecl() && !IDecl->hasExternalStorage()) {
3896 if (T->isDependentType()) {
3897 // If T is dependent, we should not require a complete type.
3898 // (RequireCompleteType shouldn't be called with dependent types.)
3899 // But we still can at least check if we've got an array of unspecified
3900 // size without an initializer.
3901 if (!IDecl->isInvalidDecl() && T->isIncompleteArrayType() &&
3902 !IDecl->getInit()) {
3903 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
3905 IDecl->setInvalidDecl();
3907 } else if (!IDecl->isInvalidDecl()) {
3908 // If T is an incomplete array type with an initializer list that is
3909 // dependent on something, its size has not been fixed. We could attempt
3910 // to fix the size for such arrays, but we would still have to check
3911 // here for initializers containing a C++0x vararg expansion, e.g.
3912 // template <typename... Args> void f(Args... args) {
3913 // int vals[] = { args };
3915 const IncompleteArrayType *IAT = Context.getAsIncompleteArrayType(T);
3916 Expr *Init = IDecl->getInit();
3918 (Init->isTypeDependent() || Init->isValueDependent())) {
3919 // Check that the member type of the array is complete, at least.
3920 if (RequireCompleteType(IDecl->getLocation(), IAT->getElementType(),
3921 diag::err_typecheck_decl_incomplete_type))
3922 IDecl->setInvalidDecl();
3923 } else if (RequireCompleteType(IDecl->getLocation(), T,
3924 diag::err_typecheck_decl_incomplete_type))
3925 IDecl->setInvalidDecl();
3928 // File scope. C99 6.9.2p2: A declaration of an identifier for an
3929 // object that has file scope without an initializer, and without a
3930 // storage-class specifier or with the storage-class specifier "static",
3931 // constitutes a tentative definition. Note: A tentative definition with
3932 // external linkage is valid (C99 6.2.2p5).
3933 if (IDecl->isTentativeDefinition(Context) && !IDecl->isInvalidDecl()) {
3934 if (const IncompleteArrayType *ArrayT
3935 = Context.getAsIncompleteArrayType(T)) {
3936 if (RequireCompleteType(IDecl->getLocation(),
3937 ArrayT->getElementType(),
3938 diag::err_illegal_decl_array_incomplete_type))
3939 IDecl->setInvalidDecl();
3940 } else if (IDecl->getStorageClass() == VarDecl::Static) {
3941 // C99 6.9.2p3: If the declaration of an identifier for an object is
3942 // a tentative definition and has internal linkage (C99 6.2.2p3), the
3943 // declared type shall not be an incomplete type.
3944 // NOTE: code such as the following
3946 // struct s { int a; };
3947 // is accepted by gcc. Hence here we issue a warning instead of
3948 // an error and we do not invalidate the static declaration.
3949 // NOTE: to avoid multiple warnings, only check the first declaration.
3950 if (IDecl->getPreviousDeclaration() == 0)
3951 RequireCompleteType(IDecl->getLocation(), T,
3952 diag::ext_typecheck_decl_incomplete_type);
3956 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context,
3957 Decls.data(), Decls.size()));
3961 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
3962 /// to introduce parameters into function prototype scope.
3964 Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
3965 const DeclSpec &DS = D.getDeclSpec();
3967 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
3968 VarDecl::StorageClass StorageClass = VarDecl::None;
3969 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
3970 StorageClass = VarDecl::Register;
3971 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
3972 Diag(DS.getStorageClassSpecLoc(),
3973 diag::err_invalid_storage_class_in_func_decl);
3974 D.getMutableDeclSpec().ClearStorageClassSpecs();
3977 if (D.getDeclSpec().isThreadSpecified())
3978 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
3980 DiagnoseFunctionSpecifiers(D);
3982 // Check that there are no default arguments inside the type of this
3983 // parameter (C++ only).
3984 if (getLangOptions().CPlusPlus)
3985 CheckExtraCXXDefaultArguments(D);
3987 TypeSourceInfo *TInfo = 0;
3988 TagDecl *OwnedDecl = 0;
3989 QualType parmDeclType = GetTypeForDeclarator(D, S, &TInfo, &OwnedDecl);
3991 if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) {
3993 // Types shall not be defined in return or parameter types.
3994 Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
3995 << Context.getTypeDeclType(OwnedDecl);
3998 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
3999 // Can this happen for params? We already checked that they don't conflict
4000 // among each other. Here they can only shadow globals, which is ok.
4001 IdentifierInfo *II = D.getIdentifier();
4003 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
4004 if (PrevDecl->isTemplateParameter()) {
4005 // Maybe we will complain about the shadowed template parameter.
4006 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
4007 // Just pretend that we didn't see the previous declaration.
4009 } else if (S->isDeclScope(DeclPtrTy::make(PrevDecl))) {
4010 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
4012 // Recover by removing the name
4014 D.SetIdentifier(0, D.getIdentifierLoc());
4019 // Parameters can not be abstract class types.
4020 // For record types, this is done by the AbstractClassUsageDiagnoser once
4021 // the class has been completely parsed.
4022 if (!CurContext->isRecord() &&
4023 RequireNonAbstractType(D.getIdentifierLoc(), parmDeclType,
4024 diag::err_abstract_type_in_decl,
4026 D.setInvalidType(true);
4028 QualType T = adjustParameterType(parmDeclType);
4031 = ParmVarDecl::Create(Context, CurContext, D.getIdentifierLoc(), II,
4032 T, TInfo, StorageClass, 0);
4034 if (D.isInvalidType())
4035 New->setInvalidDecl();
4037 // Parameter declarators cannot be interface types. All ObjC objects are
4038 // passed by reference.
4039 if (T->isObjCInterfaceType()) {
4040 Diag(D.getIdentifierLoc(),
4041 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
4042 New->setInvalidDecl();
4045 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
4046 if (D.getCXXScopeSpec().isSet()) {
4047 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
4048 << D.getCXXScopeSpec().getRange();
4049 New->setInvalidDecl();
4052 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
4053 // duration shall not be qualified by an address-space qualifier."
4054 // Since all parameters have automatic store duration, they can not have
4055 // an address space.
4056 if (T.getAddressSpace() != 0) {
4057 Diag(D.getIdentifierLoc(),
4058 diag::err_arg_with_address_space);
4059 New->setInvalidDecl();
4063 // Add the parameter declaration into this scope.
4064 S->AddDecl(DeclPtrTy::make(New));
4066 IdResolver.AddDecl(New);
4068 ProcessDeclAttributes(S, New, D);
4070 if (New->hasAttr<BlocksAttr>()) {
4071 Diag(New->getLocation(), diag::err_block_on_nonlocal);
4073 return DeclPtrTy::make(New);
4076 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
4077 SourceLocation LocAfterDecls) {
4078 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4079 "Not a function declarator!");
4080 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
4082 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
4083 // for a K&R function.
4084 if (!FTI.hasPrototype) {
4085 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
4087 if (FTI.ArgInfo[i].Param == 0) {
4088 llvm::SmallString<256> Code;
4089 llvm::raw_svector_ostream(Code) << " int "
4090 << FTI.ArgInfo[i].Ident->getName()
4092 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
4093 << FTI.ArgInfo[i].Ident
4094 << CodeModificationHint::CreateInsertion(LocAfterDecls, Code.str());
4096 // Implicitly declare the argument as type 'int' for lack of a better
4099 const char* PrevSpec; // unused
4100 unsigned DiagID; // unused
4101 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
4103 Declarator ParamD(DS, Declarator::KNRTypeListContext);
4104 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
4105 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
4111 Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
4113 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4114 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4115 "Not a function declarator!");
4116 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
4118 if (FTI.hasPrototype) {
4119 // FIXME: Diagnose arguments without names in C.
4122 Scope *ParentScope = FnBodyScope->getParent();
4124 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
4125 MultiTemplateParamsArg(*this),
4126 /*IsFunctionDefinition=*/true);
4127 return ActOnStartOfFunctionDef(FnBodyScope, DP);
4130 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
4131 // Don't warn about invalid declarations.
4132 if (FD->isInvalidDecl())
4135 // Or declarations that aren't global.
4136 if (!FD->isGlobal())
4139 // Don't warn about C++ member functions.
4140 if (isa<CXXMethodDecl>(FD))
4143 // Don't warn about 'main'.
4147 // Don't warn about inline functions.
4148 if (FD->isInlineSpecified())
4151 // Don't warn about function templates.
4152 if (FD->getDescribedFunctionTemplate())
4155 // Don't warn about function template specializations.
4156 if (FD->isFunctionTemplateSpecialization())
4159 bool MissingPrototype = true;
4160 for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
4161 Prev; Prev = Prev->getPreviousDeclaration()) {
4162 // Ignore any declarations that occur in function or method
4163 // scope, because they aren't visible from the header.
4164 if (Prev->getDeclContext()->isFunctionOrMethod())
4167 MissingPrototype = !Prev->getType()->isFunctionProtoType();
4171 return MissingPrototype;
4174 Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) {
4175 // Clear the last template instantiation error context.
4176 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
4180 FunctionDecl *FD = 0;
4182 if (FunctionTemplateDecl *FunTmpl
4183 = dyn_cast<FunctionTemplateDecl>(D.getAs<Decl>()))
4184 FD = FunTmpl->getTemplatedDecl();
4186 FD = cast<FunctionDecl>(D.getAs<Decl>());
4188 CurFunctionNeedsScopeChecking = false;
4190 // See if this is a redefinition.
4191 const FunctionDecl *Definition;
4192 if (FD->getBody(Definition)) {
4193 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
4194 Diag(Definition->getLocation(), diag::note_previous_definition);
4197 // Builtin functions cannot be defined.
4198 if (unsigned BuiltinID = FD->getBuiltinID()) {
4199 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4200 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
4201 FD->setInvalidDecl();
4205 // The return type of a function definition must be complete
4206 // (C99 6.9.1p3, C++ [dcl.fct]p6).
4207 QualType ResultType = FD->getResultType();
4208 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
4209 !FD->isInvalidDecl() &&
4210 RequireCompleteType(FD->getLocation(), ResultType,
4211 diag::err_func_def_incomplete_result))
4212 FD->setInvalidDecl();
4214 // GNU warning -Wmissing-prototypes:
4215 // Warn if a global function is defined without a previous
4216 // prototype declaration. This warning is issued even if the
4217 // definition itself provides a prototype. The aim is to detect
4218 // global functions that fail to be declared in header files.
4219 if (ShouldWarnAboutMissingPrototype(FD))
4220 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
4223 PushDeclContext(FnBodyScope, FD);
4225 // Check the validity of our function parameters
4226 CheckParmsForFunctionDef(FD);
4228 // Introduce our parameters into the function scope
4229 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
4230 ParmVarDecl *Param = FD->getParamDecl(p);
4231 Param->setOwningFunction(FD);
4233 // If this has an identifier, add it to the scope stack.
4234 if (Param->getIdentifier() && FnBodyScope)
4235 PushOnScopeChains(Param, FnBodyScope);
4238 // Checking attributes of current function definition
4239 // dllimport attribute.
4240 if (FD->getAttr<DLLImportAttr>() &&
4241 (!FD->getAttr<DLLExportAttr>())) {
4242 // dllimport attribute cannot be applied to definition.
4243 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
4244 Diag(FD->getLocation(),
4245 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
4247 FD->setInvalidDecl();
4248 return DeclPtrTy::make(FD);
4250 // If a symbol previously declared dllimport is later defined, the
4251 // attribute is ignored in subsequent references, and a warning is
4253 Diag(FD->getLocation(),
4254 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
4255 << FD->getNameAsCString() << "dllimport";
4258 return DeclPtrTy::make(FD);
4261 Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) {
4262 return ActOnFinishFunctionBody(D, move(BodyArg), false);
4265 Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg,
4266 bool IsInstantiation) {
4267 Decl *dcl = D.getAs<Decl>();
4268 Stmt *Body = BodyArg.takeAs<Stmt>();
4270 FunctionDecl *FD = 0;
4271 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
4273 FD = FunTmpl->getTemplatedDecl();
4275 FD = dyn_cast_or_null<FunctionDecl>(dcl);
4280 // C and C++ allow for main to automagically return 0.
4281 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
4282 FD->setHasImplicitReturnZero(true);
4284 CheckFallThroughForFunctionDef(FD, Body);
4286 if (!FD->isInvalidDecl())
4287 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
4289 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
4290 MaybeMarkVirtualMembersReferenced(Method->getLocation(), Method);
4292 assert(FD == getCurFunctionDecl() && "Function parsing confused");
4293 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
4294 assert(MD == getCurMethodDecl() && "Method parsing confused");
4296 CheckFallThroughForFunctionDef(MD, Body);
4297 MD->setEndLoc(Body->getLocEnd());
4299 if (!MD->isInvalidDecl())
4300 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
4302 Body->Destroy(Context);
4305 if (!IsInstantiation)
4308 // Verify and clean out per-function state.
4310 assert(&getLabelMap() == &FunctionLabelMap && "Didn't pop block right?");
4312 // Check goto/label use.
4313 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
4314 I = FunctionLabelMap.begin(), E = FunctionLabelMap.end(); I != E; ++I) {
4315 LabelStmt *L = I->second;
4317 // Verify that we have no forward references left. If so, there was a goto
4318 // or address of a label taken, but no definition of it. Label fwd
4319 // definitions are indicated with a null substmt.
4320 if (L->getSubStmt() != 0)
4324 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
4326 // At this point, we have gotos that use the bogus label. Stitch it into
4327 // the function body so that they aren't leaked and that the AST is well
4330 // The whole function wasn't parsed correctly, just delete this.
4331 L->Destroy(Context);
4335 // Otherwise, the body is valid: we want to stitch the label decl into the
4336 // function somewhere so that it is properly owned and so that the goto
4337 // has a valid target. Do this by creating a new compound stmt with the
4340 // Give the label a sub-statement.
4341 L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
4343 CompoundStmt *Compound = isa<CXXTryStmt>(Body) ?
4344 cast<CXXTryStmt>(Body)->getTryBlock() :
4345 cast<CompoundStmt>(Body);
4346 std::vector<Stmt*> Elements(Compound->body_begin(), Compound->body_end());
4347 Elements.push_back(L);
4348 Compound->setStmts(Context, &Elements[0], Elements.size());
4350 FunctionLabelMap.clear();
4352 if (!Body) return D;
4354 // Verify that that gotos and switch cases don't jump into scopes illegally.
4355 if (CurFunctionNeedsScopeChecking)
4356 DiagnoseInvalidJumps(Body);
4358 // C++ constructors that have function-try-blocks can't have return
4359 // statements in the handlers of that block. (C++ [except.handle]p14)
4361 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
4362 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
4364 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl))
4365 MarkBaseAndMemberDestructorsReferenced(Destructor);
4367 // If any errors have occurred, clear out any temporaries that may have
4368 // been leftover. This ensures that these temporaries won't be picked up for
4369 // deletion in some later function.
4370 if (PP.getDiagnostics().hasErrorOccurred())
4371 ExprTemporaries.clear();
4373 assert(ExprTemporaries.empty() && "Leftover temporaries in function");
4377 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4378 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4379 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
4380 IdentifierInfo &II, Scope *S) {
4381 // Before we produce a declaration for an implicitly defined
4382 // function, see whether there was a locally-scoped declaration of
4383 // this name as a function or variable. If so, use that
4384 // (non-visible) declaration, and complain about it.
4385 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4386 = LocallyScopedExternalDecls.find(&II);
4387 if (Pos != LocallyScopedExternalDecls.end()) {
4388 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
4389 Diag(Pos->second->getLocation(), diag::note_previous_declaration);
4393 // Extension in C99. Legal in C90, but warn about it.
4394 if (II.getName().startswith("__builtin_"))
4395 Diag(Loc, diag::warn_builtin_unknown) << &II;
4396 else if (getLangOptions().C99)
4397 Diag(Loc, diag::ext_implicit_function_decl) << &II;
4399 Diag(Loc, diag::warn_implicit_function_decl) << &II;
4401 // Set a Declarator for the implicit definition: int foo();
4405 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
4406 Error = Error; // Silence warning.
4407 assert(!Error && "Error setting up implicit decl!");
4408 Declarator D(DS, Declarator::BlockContext);
4409 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
4410 0, 0, false, SourceLocation(),
4411 false, 0,0,0, Loc, Loc, D),
4413 D.SetIdentifier(&II, Loc);
4415 // Insert this function into translation-unit scope.
4417 DeclContext *PrevDC = CurContext;
4418 CurContext = Context.getTranslationUnitDecl();
4421 dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D).getAs<Decl>());
4424 CurContext = PrevDC;
4426 AddKnownFunctionAttributes(FD);
4431 /// \brief Adds any function attributes that we know a priori based on
4432 /// the declaration of this function.
4434 /// These attributes can apply both to implicitly-declared builtins
4435 /// (like __builtin___printf_chk) or to library-declared functions
4436 /// like NSLog or printf.
4437 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
4438 if (FD->isInvalidDecl())
4441 // If this is a built-in function, map its builtin attributes to
4442 // actual attributes.
4443 if (unsigned BuiltinID = FD->getBuiltinID()) {
4444 // Handle printf-formatting attributes.
4447 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
4448 if (!FD->getAttr<FormatAttr>())
4449 FD->addAttr(::new (Context) FormatAttr("printf", FormatIdx + 1,
4450 HasVAListArg ? 0 : FormatIdx + 2));
4453 // Mark const if we don't care about errno and that is the only
4454 // thing preventing the function from being const. This allows
4455 // IRgen to use LLVM intrinsics for such functions.
4456 if (!getLangOptions().MathErrno &&
4457 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
4458 if (!FD->getAttr<ConstAttr>())
4459 FD->addAttr(::new (Context) ConstAttr());
4462 if (Context.BuiltinInfo.isNoReturn(BuiltinID))
4463 FD->addAttr(::new (Context) NoReturnAttr());
4464 if (Context.BuiltinInfo.isNoThrow(BuiltinID))
4465 FD->addAttr(::new (Context) NoThrowAttr());
4466 if (Context.BuiltinInfo.isConst(BuiltinID))
4467 FD->addAttr(::new (Context) ConstAttr());
4470 IdentifierInfo *Name = FD->getIdentifier();
4473 if ((!getLangOptions().CPlusPlus &&
4474 FD->getDeclContext()->isTranslationUnit()) ||
4475 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
4476 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
4477 LinkageSpecDecl::lang_c)) {
4478 // Okay: this could be a libc/libm/Objective-C function we know
4483 if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
4484 // FIXME: NSLog and NSLogv should be target specific
4485 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
4486 // FIXME: We known better than our headers.
4487 const_cast<FormatAttr *>(Format)->setType("printf");
4489 FD->addAttr(::new (Context) FormatAttr("printf", 1,
4490 Name->isStr("NSLogv") ? 0 : 2));
4491 } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
4492 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
4493 // target-specific builtins, perhaps?
4494 if (!FD->getAttr<FormatAttr>())
4495 FD->addAttr(::new (Context) FormatAttr("printf", 2,
4496 Name->isStr("vasprintf") ? 0 : 3));
4500 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
4501 TypeSourceInfo *TInfo) {
4502 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
4503 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
4506 assert(D.isInvalidType() && "no declarator info for valid type");
4507 TInfo = Context.getTrivialTypeSourceInfo(T);
4510 // Scope manipulation handled by caller.
4511 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
4512 D.getIdentifierLoc(),
4516 if (const TagType *TT = T->getAs<TagType>()) {
4517 TagDecl *TD = TT->getDecl();
4519 // If the TagDecl that the TypedefDecl points to is an anonymous decl
4520 // keep track of the TypedefDecl.
4521 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
4522 TD->setTypedefForAnonDecl(NewTD);
4525 if (D.isInvalidType())
4526 NewTD->setInvalidDecl();
4531 /// \brief Determine whether a tag with a given kind is acceptable
4532 /// as a redeclaration of the given tag declaration.
4534 /// \returns true if the new tag kind is acceptable, false otherwise.
4535 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
4536 TagDecl::TagKind NewTag,
4537 SourceLocation NewTagLoc,
4538 const IdentifierInfo &Name) {
4539 // C++ [dcl.type.elab]p3:
4540 // The class-key or enum keyword present in the
4541 // elaborated-type-specifier shall agree in kind with the
4542 // declaration to which the name in theelaborated-type-specifier
4543 // refers. This rule also applies to the form of
4544 // elaborated-type-specifier that declares a class-name or
4545 // friend class since it can be construed as referring to the
4546 // definition of the class. Thus, in any
4547 // elaborated-type-specifier, the enum keyword shall be used to
4548 // refer to an enumeration (7.2), the union class-keyshall be
4549 // used to refer to a union (clause 9), and either the class or
4550 // struct class-key shall be used to refer to a class (clause 9)
4551 // declared using the class or struct class-key.
4552 TagDecl::TagKind OldTag = Previous->getTagKind();
4553 if (OldTag == NewTag)
4556 if ((OldTag == TagDecl::TK_struct || OldTag == TagDecl::TK_class) &&
4557 (NewTag == TagDecl::TK_struct || NewTag == TagDecl::TK_class)) {
4558 // Warn about the struct/class tag mismatch.
4559 bool isTemplate = false;
4560 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
4561 isTemplate = Record->getDescribedClassTemplate();
4563 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
4564 << (NewTag == TagDecl::TK_class)
4565 << isTemplate << &Name
4566 << CodeModificationHint::CreateReplacement(SourceRange(NewTagLoc),
4567 OldTag == TagDecl::TK_class? "class" : "struct");
4568 Diag(Previous->getLocation(), diag::note_previous_use);
4574 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
4575 /// former case, Name will be non-null. In the later case, Name will be null.
4576 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
4577 /// reference/declaration/definition of a tag.
4578 Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4579 SourceLocation KWLoc, const CXXScopeSpec &SS,
4580 IdentifierInfo *Name, SourceLocation NameLoc,
4581 AttributeList *Attr, AccessSpecifier AS,
4582 MultiTemplateParamsArg TemplateParameterLists,
4583 bool &OwnedDecl, bool &IsDependent) {
4584 // If this is not a definition, it must have a name.
4585 assert((Name != 0 || TUK == TUK_Definition) &&
4586 "Nameless record must be a definition!");
4589 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
4591 // FIXME: Check explicit specializations more carefully.
4592 bool isExplicitSpecialization = false;
4593 if (TUK != TUK_Reference) {
4594 if (TemplateParameterList *TemplateParams
4595 = MatchTemplateParametersToScopeSpecifier(KWLoc, SS,
4596 (TemplateParameterList**)TemplateParameterLists.get(),
4597 TemplateParameterLists.size(),
4598 isExplicitSpecialization)) {
4599 if (TemplateParams->size() > 0) {
4600 // This is a declaration or definition of a class template (which may
4601 // be a member of another template).
4603 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
4604 SS, Name, NameLoc, Attr,
4607 TemplateParameterLists.release();
4608 return Result.get();
4610 // The "template<>" header is extraneous.
4611 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
4612 << ElaboratedType::getNameForTagKind(Kind) << Name;
4613 isExplicitSpecialization = true;
4617 TemplateParameterLists.release();
4620 DeclContext *SearchDC = CurContext;
4621 DeclContext *DC = CurContext;
4622 bool isStdBadAlloc = false;
4623 bool Invalid = false;
4625 RedeclarationKind Redecl = (TUK != TUK_Reference ? ForRedeclaration
4626 : NotForRedeclaration);
4628 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
4630 if (Name && SS.isNotEmpty()) {
4631 // We have a nested-name tag ('struct foo::bar').
4633 // Check for invalid 'foo::'.
4634 if (SS.isInvalid()) {
4639 // If this is a friend or a reference to a class in a dependent
4640 // context, don't try to make a decl for it.
4641 if (TUK == TUK_Friend || TUK == TUK_Reference) {
4642 DC = computeDeclContext(SS, false);
4649 if (RequireCompleteDeclContext(SS))
4650 return DeclPtrTy::make((Decl *)0);
4652 DC = computeDeclContext(SS, true);
4654 // Look-up name inside 'foo::'.
4655 LookupQualifiedName(Previous, DC);
4657 if (Previous.isAmbiguous())
4660 // A tag 'foo::bar' must already exist.
4661 if (Previous.empty()) {
4662 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
4668 // If this is a named struct, check to see if there was a previous forward
4669 // declaration or definition.
4670 // FIXME: We're looking into outer scopes here, even when we
4671 // shouldn't be. Doing so can result in ambiguities that we
4672 // shouldn't be diagnosing.
4673 LookupName(Previous, S);
4675 // Note: there used to be some attempt at recovery here.
4676 if (Previous.isAmbiguous())
4679 if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
4680 // FIXME: This makes sure that we ignore the contexts associated
4681 // with C structs, unions, and enums when looking for a matching
4682 // tag declaration or definition. See the similar lookup tweak
4683 // in Sema::LookupName; is there a better way to deal with this?
4684 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
4685 SearchDC = SearchDC->getParent();
4689 if (Previous.isSingleResult() &&
4690 Previous.getFoundDecl()->isTemplateParameter()) {
4691 // Maybe we will complain about the shadowed template parameter.
4692 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
4693 // Just pretend that we didn't see the previous declaration.
4697 if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
4698 DC->Equals(StdNamespace) && Name->isStr("bad_alloc")) {
4699 // This is a declaration of or a reference to "std::bad_alloc".
4700 isStdBadAlloc = true;
4702 if (Previous.empty() && StdBadAlloc) {
4703 // std::bad_alloc has been implicitly declared (but made invisible to
4704 // name lookup). Fill in this implicit declaration as the previous
4705 // declaration, so that the declarations get chained appropriately.
4706 Previous.addDecl(StdBadAlloc);
4710 if (!Previous.empty()) {
4711 assert(Previous.isSingleResult());
4712 NamedDecl *PrevDecl = Previous.getFoundDecl();
4713 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
4714 // If this is a use of a previous tag, or if the tag is already declared
4715 // in the same scope (so that the definition/declaration completes or
4716 // rementions the tag), reuse the decl.
4717 if (TUK == TUK_Reference || TUK == TUK_Friend ||
4718 isDeclInScope(PrevDecl, SearchDC, S)) {
4719 // Make sure that this wasn't declared as an enum and now used as a
4720 // struct or something similar.
4721 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) {
4723 = (PrevTagDecl->getTagKind() != TagDecl::TK_enum &&
4724 Kind != TagDecl::TK_enum);
4726 Diag(KWLoc, diag::err_use_with_wrong_tag)
4728 << CodeModificationHint::CreateReplacement(SourceRange(KWLoc),
4729 PrevTagDecl->getKindName());
4731 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
4732 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
4735 Kind = PrevTagDecl->getTagKind();
4737 // Recover by making this an anonymous redefinition.
4745 // If this is a use, just return the declaration we found.
4747 // FIXME: In the future, return a variant or some other clue
4748 // for the consumer of this Decl to know it doesn't own it.
4749 // For our current ASTs this shouldn't be a problem, but will
4750 // need to be changed with DeclGroups.
4751 if (TUK == TUK_Reference || TUK == TUK_Friend)
4752 return DeclPtrTy::make(PrevTagDecl);
4754 // Diagnose attempts to redefine a tag.
4755 if (TUK == TUK_Definition) {
4756 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
4757 // If we're defining a specialization and the previous definition
4758 // is from an implicit instantiation, don't emit an error
4759 // here; we'll catch this in the general case below.
4760 if (!isExplicitSpecialization ||
4761 !isa<CXXRecordDecl>(Def) ||
4762 cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
4763 == TSK_ExplicitSpecialization) {
4764 Diag(NameLoc, diag::err_redefinition) << Name;
4765 Diag(Def->getLocation(), diag::note_previous_definition);
4766 // If this is a redefinition, recover by making this
4767 // struct be anonymous, which will make any later
4768 // references get the previous definition.
4774 // If the type is currently being defined, complain
4775 // about a nested redefinition.
4776 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
4777 if (Tag->isBeingDefined()) {
4778 Diag(NameLoc, diag::err_nested_redefinition) << Name;
4779 Diag(PrevTagDecl->getLocation(),
4780 diag::note_previous_definition);
4787 // Okay, this is definition of a previously declared or referenced
4788 // tag PrevDecl. We're going to create a new Decl for it.
4791 // If we get here we have (another) forward declaration or we
4792 // have a definition. Just create a new decl.
4795 // If we get here, this is a definition of a new tag type in a nested
4796 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
4797 // new decl/type. We set PrevDecl to NULL so that the entities
4798 // have distinct types.
4801 // If we get here, we're going to create a new Decl. If PrevDecl
4802 // is non-NULL, it's a definition of the tag declared by
4803 // PrevDecl. If it's NULL, we have a new definition.
4805 // PrevDecl is a namespace, template, or anything else
4806 // that lives in the IDNS_Tag identifier namespace.
4807 if (isDeclInScope(PrevDecl, SearchDC, S)) {
4808 // The tag name clashes with a namespace name, issue an error and
4809 // recover by making this tag be anonymous.
4810 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
4811 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4816 // The existing declaration isn't relevant to us; we're in a
4817 // new scope, so clear out the previous declaration.
4821 } else if (TUK == TUK_Reference && SS.isEmpty() && Name) {
4822 // C++ [basic.scope.pdecl]p5:
4823 // -- for an elaborated-type-specifier of the form
4825 // class-key identifier
4827 // if the elaborated-type-specifier is used in the
4828 // decl-specifier-seq or parameter-declaration-clause of a
4829 // function defined in namespace scope, the identifier is
4830 // declared as a class-name in the namespace that contains
4831 // the declaration; otherwise, except as a friend
4832 // declaration, the identifier is declared in the smallest
4833 // non-class, non-function-prototype scope that contains the
4836 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
4837 // C structs and unions.
4839 // It is an error in C++ to declare (rather than define) an enum
4840 // type, including via an elaborated type specifier. We'll
4841 // diagnose that later; for now, declare the enum in the same
4842 // scope as we would have picked for any other tag type.
4844 // GNU C also supports this behavior as part of its incomplete
4845 // enum types extension, while GNU C++ does not.
4847 // Find the context where we'll be declaring the tag.
4848 // FIXME: We would like to maintain the current DeclContext as the
4850 while (SearchDC->isRecord())
4851 SearchDC = SearchDC->getParent();
4853 // Find the scope where we'll be declaring the tag.
4854 while (S->isClassScope() ||
4855 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
4856 ((S->getFlags() & Scope::DeclScope) == 0) ||
4858 ((DeclContext *)S->getEntity())->isTransparentContext()))
4861 } else if (TUK == TUK_Friend && SS.isEmpty() && Name) {
4862 // C++ [namespace.memdef]p3:
4863 // If a friend declaration in a non-local class first declares a
4864 // class or function, the friend class or function is a member of
4865 // the innermost enclosing namespace.
4866 while (!SearchDC->isFileContext())
4867 SearchDC = SearchDC->getParent();
4869 // The entity of a decl scope is a DeclContext; see PushDeclContext.
4870 while (S->getEntity() != SearchDC)
4876 TagDecl *PrevDecl = 0;
4877 if (Previous.isSingleResult())
4878 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
4880 // If there is an identifier, use the location of the identifier as the
4881 // location of the decl, otherwise use the location of the struct/union
4883 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
4885 // Otherwise, create a new declaration. If there is a previous
4886 // declaration of the same entity, the two will be linked via
4890 if (Kind == TagDecl::TK_enum) {
4891 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
4892 // enum X { A, B, C } D; D should chain to X.
4893 New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc,
4894 cast_or_null<EnumDecl>(PrevDecl));
4895 // If this is an undefined enum, warn.
4896 if (TUK != TUK_Definition && !Invalid) {
4897 unsigned DK = getLangOptions().CPlusPlus? diag::err_forward_ref_enum
4898 : diag::ext_forward_ref_enum;
4902 // struct/union/class
4904 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
4905 // struct X { int A; } D; D should chain to X.
4906 if (getLangOptions().CPlusPlus) {
4907 // FIXME: Look for a way to use RecordDecl for simple structs.
4908 New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
4909 cast_or_null<CXXRecordDecl>(PrevDecl));
4911 if (isStdBadAlloc && (!StdBadAlloc || StdBadAlloc->isImplicit()))
4912 StdBadAlloc = cast<CXXRecordDecl>(New);
4914 New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
4915 cast_or_null<RecordDecl>(PrevDecl));
4918 if (Kind != TagDecl::TK_enum) {
4919 // Handle #pragma pack: if the #pragma pack stack has non-default
4920 // alignment, make up a packed attribute for this decl. These
4921 // attributes are checked when the ASTContext lays out the
4924 // It is important for implementing the correct semantics that this
4925 // happen here (in act on tag decl). The #pragma pack stack is
4926 // maintained as a result of parser callbacks which can occur at
4927 // many points during the parsing of a struct declaration (because
4928 // the #pragma tokens are effectively skipped over during the
4929 // parsing of the struct).
4930 if (unsigned Alignment = getPragmaPackAlignment())
4931 New->addAttr(::new (Context) PragmaPackAttr(Alignment * 8));
4934 if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
4935 // C++ [dcl.typedef]p3:
4936 // [...] Similarly, in a given scope, a class or enumeration
4937 // shall not be declared with the same name as a typedef-name
4938 // that is declared in that scope and refers to a type other
4939 // than the class or enumeration itself.
4940 LookupResult Lookup(*this, Name, NameLoc, LookupOrdinaryName,
4942 LookupName(Lookup, S);
4943 TypedefDecl *PrevTypedef = Lookup.getAsSingle<TypedefDecl>();
4944 NamedDecl *PrevTypedefNamed = PrevTypedef;
4945 if (PrevTypedef && isDeclInScope(PrevTypedefNamed, SearchDC, S) &&
4946 Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
4947 Context.getCanonicalType(Context.getTypeDeclType(New))) {
4948 Diag(Loc, diag::err_tag_definition_of_typedef)
4949 << Context.getTypeDeclType(New)
4950 << PrevTypedef->getUnderlyingType();
4951 Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
4956 // If this is a specialization of a member class (of a class template),
4957 // check the specialization.
4958 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
4962 New->setInvalidDecl();
4965 ProcessDeclAttributeList(S, New, Attr);
4967 // If we're declaring or defining a tag in function prototype scope
4968 // in C, note that this type can only be used within the function.
4969 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
4970 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
4972 // Set the lexical context. If the tag has a C++ scope specifier, the
4973 // lexical context will be different from the semantic context.
4974 New->setLexicalDeclContext(CurContext);
4976 // Mark this as a friend decl if applicable.
4977 if (TUK == TUK_Friend)
4978 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty());
4980 // Set the access specifier.
4981 if (!Invalid && TUK != TUK_Friend)
4982 SetMemberAccessSpecifier(New, PrevDecl, AS);
4984 if (TUK == TUK_Definition)
4985 New->startDefinition();
4987 // If this has an identifier, add it to the scope stack.
4988 if (TUK == TUK_Friend) {
4989 // We might be replacing an existing declaration in the lookup tables;
4990 // if so, borrow its access specifier.
4992 New->setAccess(PrevDecl->getAccess());
4994 // Friend tag decls are visible in fairly strange ways.
4995 if (!CurContext->isDependentContext()) {
4996 DeclContext *DC = New->getDeclContext()->getLookupContext();
4997 DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
4998 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
4999 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
5002 S = getNonFieldDeclScope(S);
5003 PushOnScopeChains(New, S);
5005 CurContext->addDecl(New);
5008 // If this is the C FILE type, notify the AST context.
5009 if (IdentifierInfo *II = New->getIdentifier())
5010 if (!New->isInvalidDecl() &&
5011 New->getDeclContext()->getLookupContext()->isTranslationUnit() &&
5013 Context.setFILEDecl(New);
5016 return DeclPtrTy::make(New);
5019 void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) {
5020 AdjustDeclIfTemplate(TagD);
5021 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
5023 // Enter the tag context.
5024 PushDeclContext(S, Tag);
5027 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, DeclPtrTy TagD,
5028 SourceLocation LBraceLoc) {
5029 AdjustDeclIfTemplate(TagD);
5030 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD.getAs<Decl>());
5032 FieldCollector->StartClass();
5034 if (!Record->getIdentifier())
5038 // [...] The class-name is also inserted into the scope of the
5039 // class itself; this is known as the injected-class-name. For
5040 // purposes of access checking, the injected-class-name is treated
5041 // as if it were a public member name.
5042 CXXRecordDecl *InjectedClassName
5043 = CXXRecordDecl::Create(Context, Record->getTagKind(),
5044 CurContext, Record->getLocation(),
5045 Record->getIdentifier(),
5046 Record->getTagKeywordLoc(),
5048 InjectedClassName->setImplicit();
5049 InjectedClassName->setAccess(AS_public);
5050 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
5051 InjectedClassName->setDescribedClassTemplate(Template);
5052 PushOnScopeChains(InjectedClassName, S);
5053 assert(InjectedClassName->isInjectedClassName() &&
5054 "Broken injected-class-name");
5057 void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD,
5058 SourceLocation RBraceLoc) {
5059 AdjustDeclIfTemplate(TagD);
5060 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
5061 Tag->setRBraceLoc(RBraceLoc);
5063 if (isa<CXXRecordDecl>(Tag))
5064 FieldCollector->FinishClass();
5066 // Exit this scope of this tag's definition.
5069 // Notify the consumer that we've defined a tag.
5070 Consumer.HandleTagDeclDefinition(Tag);
5073 // Note that FieldName may be null for anonymous bitfields.
5074 bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
5075 QualType FieldTy, const Expr *BitWidth,
5077 // Default to true; that shouldn't confuse checks for emptiness
5081 // C99 6.7.2.1p4 - verify the field type.
5082 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
5083 if (!FieldTy->isDependentType() && !FieldTy->isIntegralType()) {
5084 // Handle incomplete types with specific error.
5085 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
5088 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
5089 << FieldName << FieldTy << BitWidth->getSourceRange();
5090 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
5091 << FieldTy << BitWidth->getSourceRange();
5094 // If the bit-width is type- or value-dependent, don't try to check
5096 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
5100 if (VerifyIntegerConstantExpression(BitWidth, &Value))
5103 if (Value != 0 && ZeroWidth)
5106 // Zero-width bitfield is ok for anonymous field.
5107 if (Value == 0 && FieldName)
5108 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
5110 if (Value.isSigned() && Value.isNegative()) {
5112 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
5113 << FieldName << Value.toString(10);
5114 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
5115 << Value.toString(10);
5118 if (!FieldTy->isDependentType()) {
5119 uint64_t TypeSize = Context.getTypeSize(FieldTy);
5120 if (Value.getZExtValue() > TypeSize) {
5122 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
5123 << FieldName << (unsigned)TypeSize;
5124 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
5125 << (unsigned)TypeSize;
5132 /// ActOnField - Each field of a struct/union/class is passed into this in order
5133 /// to create a FieldDecl object for it.
5134 Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD,
5135 SourceLocation DeclStart,
5136 Declarator &D, ExprTy *BitfieldWidth) {
5137 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()),
5138 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
5140 return DeclPtrTy::make(Res);
5143 /// HandleField - Analyze a field of a C struct or a C++ data member.
5145 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
5146 SourceLocation DeclStart,
5147 Declarator &D, Expr *BitWidth,
5148 AccessSpecifier AS) {
5149 IdentifierInfo *II = D.getIdentifier();
5150 SourceLocation Loc = DeclStart;
5151 if (II) Loc = D.getIdentifierLoc();
5153 TypeSourceInfo *TInfo = 0;
5154 QualType T = GetTypeForDeclarator(D, S, &TInfo);
5155 if (getLangOptions().CPlusPlus)
5156 CheckExtraCXXDefaultArguments(D);
5158 DiagnoseFunctionSpecifiers(D);
5160 if (D.getDeclSpec().isThreadSpecified())
5161 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
5163 NamedDecl *PrevDecl = LookupSingleName(S, II, LookupMemberName,
5166 if (PrevDecl && PrevDecl->isTemplateParameter()) {
5167 // Maybe we will complain about the shadowed template parameter.
5168 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5169 // Just pretend that we didn't see the previous declaration.
5173 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
5177 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
5178 SourceLocation TSSL = D.getSourceRange().getBegin();
5180 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, TSSL,
5182 if (NewFD->isInvalidDecl() && PrevDecl) {
5183 // Don't introduce NewFD into scope; there's already something
5184 // with the same name in the same scope.
5186 PushOnScopeChains(NewFD, S);
5188 Record->addDecl(NewFD);
5193 /// \brief Build a new FieldDecl and check its well-formedness.
5195 /// This routine builds a new FieldDecl given the fields name, type,
5196 /// record, etc. \p PrevDecl should refer to any previous declaration
5197 /// with the same name and in the same scope as the field to be
5200 /// \returns a new FieldDecl.
5202 /// \todo The Declarator argument is a hack. It will be removed once
5203 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
5204 TypeSourceInfo *TInfo,
5205 RecordDecl *Record, SourceLocation Loc,
5206 bool Mutable, Expr *BitWidth,
5207 SourceLocation TSSL,
5208 AccessSpecifier AS, NamedDecl *PrevDecl,
5210 IdentifierInfo *II = Name.getAsIdentifierInfo();
5211 bool InvalidDecl = false;
5212 if (D) InvalidDecl = D->isInvalidType();
5214 // If we receive a broken type, recover by assuming 'int' and
5215 // marking this declaration as invalid.
5221 QualType EltTy = Context.getBaseElementType(T);
5222 if (!EltTy->isDependentType() &&
5223 RequireCompleteType(Loc, EltTy, diag::err_field_incomplete))
5226 // C99 6.7.2.1p8: A member of a structure or union may have any type other
5227 // than a variably modified type.
5228 if (!InvalidDecl && T->isVariablyModifiedType()) {
5229 bool SizeIsNegative;
5230 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
5232 if (!FixedTy.isNull()) {
5233 Diag(Loc, diag::warn_illegal_constant_array_size);
5237 Diag(Loc, diag::err_typecheck_negative_array_size);
5239 Diag(Loc, diag::err_typecheck_field_variable_size);
5244 // Fields can not have abstract class types
5245 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
5246 diag::err_abstract_type_in_decl,
5250 bool ZeroWidth = false;
5251 // If this is declared as a bit-field, check the bit-field.
5252 if (!InvalidDecl && BitWidth &&
5253 VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
5255 DeleteExpr(BitWidth);
5260 FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, TInfo,
5263 NewFD->setInvalidDecl();
5265 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
5266 Diag(Loc, diag::err_duplicate_member) << II;
5267 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5268 NewFD->setInvalidDecl();
5271 if (getLangOptions().CPlusPlus) {
5272 CXXRecordDecl* CXXRecord = cast<CXXRecordDecl>(Record);
5274 if (!T->isPODType())
5275 CXXRecord->setPOD(false);
5277 CXXRecord->setEmpty(false);
5279 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
5280 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
5282 if (!RDecl->hasTrivialConstructor())
5283 CXXRecord->setHasTrivialConstructor(false);
5284 if (!RDecl->hasTrivialCopyConstructor())
5285 CXXRecord->setHasTrivialCopyConstructor(false);
5286 if (!RDecl->hasTrivialCopyAssignment())
5287 CXXRecord->setHasTrivialCopyAssignment(false);
5288 if (!RDecl->hasTrivialDestructor())
5289 CXXRecord->setHasTrivialDestructor(false);
5291 // C++ 9.5p1: An object of a class with a non-trivial
5292 // constructor, a non-trivial copy constructor, a non-trivial
5293 // destructor, or a non-trivial copy assignment operator
5294 // cannot be a member of a union, nor can an array of such
5296 // TODO: C++0x alters this restriction significantly.
5297 if (Record->isUnion()) {
5298 // We check for copy constructors before constructors
5299 // because otherwise we'll never get complaints about
5300 // copy constructors.
5302 const CXXSpecialMember invalid = (CXXSpecialMember) -1;
5304 CXXSpecialMember member;
5305 if (!RDecl->hasTrivialCopyConstructor())
5306 member = CXXCopyConstructor;
5307 else if (!RDecl->hasTrivialConstructor())
5308 member = CXXDefaultConstructor;
5309 else if (!RDecl->hasTrivialCopyAssignment())
5310 member = CXXCopyAssignment;
5311 else if (!RDecl->hasTrivialDestructor())
5312 member = CXXDestructor;
5316 if (member != invalid) {
5317 Diag(Loc, diag::err_illegal_union_member) << Name << member;
5318 DiagnoseNontrivial(RT, member);
5319 NewFD->setInvalidDecl();
5325 // FIXME: We need to pass in the attributes given an AST
5326 // representation, not a parser representation.
5328 // FIXME: What to pass instead of TUScope?
5329 ProcessDeclAttributes(TUScope, NewFD, *D);
5331 if (T.isObjCGCWeak())
5332 Diag(Loc, diag::warn_attribute_weak_on_field);
5334 NewFD->setAccess(AS);
5336 // C++ [dcl.init.aggr]p1:
5337 // An aggregate is an array or a class (clause 9) with [...] no
5338 // private or protected non-static data members (clause 11).
5339 // A POD must be an aggregate.
5340 if (getLangOptions().CPlusPlus &&
5341 (AS == AS_private || AS == AS_protected)) {
5342 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
5343 CXXRecord->setAggregate(false);
5344 CXXRecord->setPOD(false);
5350 /// DiagnoseNontrivial - Given that a class has a non-trivial
5351 /// special member, figure out why.
5352 void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
5354 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
5356 // Check whether the member was user-declared.
5358 case CXXDefaultConstructor:
5359 if (RD->hasUserDeclaredConstructor()) {
5360 typedef CXXRecordDecl::ctor_iterator ctor_iter;
5361 for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
5362 const FunctionDecl *body = 0;
5365 !cast<CXXConstructorDecl>(body)->isImplicitlyDefined(Context)) {
5366 SourceLocation CtorLoc = ci->getLocation();
5367 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5372 assert(0 && "found no user-declared constructors");
5377 case CXXCopyConstructor:
5378 if (RD->hasUserDeclaredCopyConstructor()) {
5379 SourceLocation CtorLoc =
5380 RD->getCopyConstructor(Context, 0)->getLocation();
5381 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5386 case CXXCopyAssignment:
5387 if (RD->hasUserDeclaredCopyAssignment()) {
5388 // FIXME: this should use the location of the copy
5389 // assignment, not the type.
5390 SourceLocation TyLoc = RD->getSourceRange().getBegin();
5391 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
5397 if (RD->hasUserDeclaredDestructor()) {
5398 SourceLocation DtorLoc = RD->getDestructor(Context)->getLocation();
5399 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5405 typedef CXXRecordDecl::base_class_iterator base_iter;
5407 // Virtual bases and members inhibit trivial copying/construction,
5408 // but not trivial destruction.
5409 if (member != CXXDestructor) {
5410 // Check for virtual bases. vbases includes indirect virtual bases,
5411 // so we just iterate through the direct bases.
5412 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
5413 if (bi->isVirtual()) {
5414 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5415 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
5419 // Check for virtual methods.
5420 typedef CXXRecordDecl::method_iterator meth_iter;
5421 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
5423 if (mi->isVirtual()) {
5424 SourceLocation MLoc = mi->getSourceRange().getBegin();
5425 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
5431 bool (CXXRecordDecl::*hasTrivial)() const;
5433 case CXXDefaultConstructor:
5434 hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break;
5435 case CXXCopyConstructor:
5436 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
5437 case CXXCopyAssignment:
5438 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
5440 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
5442 assert(0 && "unexpected special member"); return;
5445 // Check for nontrivial bases (and recurse).
5446 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
5447 const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
5448 assert(BaseRT && "Don't know how to handle dependent bases");
5449 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
5450 if (!(BaseRecTy->*hasTrivial)()) {
5451 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5452 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
5453 DiagnoseNontrivial(BaseRT, member);
5458 // Check for nontrivial members (and recurse).
5459 typedef RecordDecl::field_iterator field_iter;
5460 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
5462 QualType EltTy = Context.getBaseElementType((*fi)->getType());
5463 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
5464 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
5466 if (!(EltRD->*hasTrivial)()) {
5467 SourceLocation FLoc = (*fi)->getLocation();
5468 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
5469 DiagnoseNontrivial(EltRT, member);
5475 assert(0 && "found no explanation for non-trivial member");
5478 /// TranslateIvarVisibility - Translate visibility from a token ID to an
5480 static ObjCIvarDecl::AccessControl
5481 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
5482 switch (ivarVisibility) {
5483 default: assert(0 && "Unknown visitibility kind");
5484 case tok::objc_private: return ObjCIvarDecl::Private;
5485 case tok::objc_public: return ObjCIvarDecl::Public;
5486 case tok::objc_protected: return ObjCIvarDecl::Protected;
5487 case tok::objc_package: return ObjCIvarDecl::Package;
5491 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
5492 /// in order to create an IvarDecl object for it.
5493 Sema::DeclPtrTy Sema::ActOnIvar(Scope *S,
5494 SourceLocation DeclStart,
5496 Declarator &D, ExprTy *BitfieldWidth,
5497 tok::ObjCKeywordKind Visibility) {
5499 IdentifierInfo *II = D.getIdentifier();
5500 Expr *BitWidth = (Expr*)BitfieldWidth;
5501 SourceLocation Loc = DeclStart;
5502 if (II) Loc = D.getIdentifierLoc();
5504 // FIXME: Unnamed fields can be handled in various different ways, for
5505 // example, unnamed unions inject all members into the struct namespace!
5507 TypeSourceInfo *TInfo = 0;
5508 QualType T = GetTypeForDeclarator(D, S, &TInfo);
5511 // 6.7.2.1p3, 6.7.2.1p4
5512 if (VerifyBitField(Loc, II, T, BitWidth)) {
5514 DeleteExpr(BitWidth);
5524 // C99 6.7.2.1p8: A member of a structure or union may have any type other
5525 // than a variably modified type.
5526 if (T->isVariablyModifiedType()) {
5527 Diag(Loc, diag::err_typecheck_ivar_variable_size);
5531 // Get the visibility (access control) for this ivar.
5532 ObjCIvarDecl::AccessControl ac =
5533 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
5534 : ObjCIvarDecl::None;
5535 // Must set ivar's DeclContext to its enclosing interface.
5536 Decl *EnclosingDecl = IntfDecl.getAs<Decl>();
5537 DeclContext *EnclosingContext;
5538 if (ObjCImplementationDecl *IMPDecl =
5539 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
5540 // Case of ivar declared in an implementation. Context is that of its class.
5541 ObjCInterfaceDecl* IDecl = IMPDecl->getClassInterface();
5542 assert(IDecl && "No class- ActOnIvar");
5543 EnclosingContext = cast_or_null<DeclContext>(IDecl);
5545 EnclosingContext = dyn_cast<DeclContext>(EnclosingDecl);
5546 assert(EnclosingContext && "null DeclContext for ivar - ActOnIvar");
5548 // Construct the decl.
5549 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context,
5550 EnclosingContext, Loc, II, T,
5551 TInfo, ac, (Expr *)BitfieldWidth);
5554 NamedDecl *PrevDecl = LookupSingleName(S, II, LookupMemberName,
5556 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
5557 && !isa<TagDecl>(PrevDecl)) {
5558 Diag(Loc, diag::err_duplicate_member) << II;
5559 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5560 NewID->setInvalidDecl();
5564 // Process attributes attached to the ivar.
5565 ProcessDeclAttributes(S, NewID, D);
5567 if (D.isInvalidType())
5568 NewID->setInvalidDecl();
5571 // FIXME: When interfaces are DeclContexts, we'll need to add
5572 // these to the interface.
5573 S->AddDecl(DeclPtrTy::make(NewID));
5574 IdResolver.AddDecl(NewID);
5577 return DeclPtrTy::make(NewID);
5580 void Sema::ActOnFields(Scope* S,
5581 SourceLocation RecLoc, DeclPtrTy RecDecl,
5582 DeclPtrTy *Fields, unsigned NumFields,
5583 SourceLocation LBrac, SourceLocation RBrac,
5584 AttributeList *Attr) {
5585 Decl *EnclosingDecl = RecDecl.getAs<Decl>();
5586 assert(EnclosingDecl && "missing record or interface decl");
5588 // If the decl this is being inserted into is invalid, then it may be a
5589 // redeclaration or some other bogus case. Don't try to add fields to it.
5590 if (EnclosingDecl->isInvalidDecl()) {
5591 // FIXME: Deallocate fields?
5596 // Verify that all the fields are okay.
5597 unsigned NumNamedMembers = 0;
5598 llvm::SmallVector<FieldDecl*, 32> RecFields;
5600 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
5601 for (unsigned i = 0; i != NumFields; ++i) {
5602 FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>());
5604 // Get the type for the field.
5605 Type *FDTy = FD->getType().getTypePtr();
5607 if (!FD->isAnonymousStructOrUnion()) {
5608 // Remember all fields written by the user.
5609 RecFields.push_back(FD);
5612 // If the field is already invalid for some reason, don't emit more
5613 // diagnostics about it.
5614 if (FD->isInvalidDecl()) {
5615 EnclosingDecl->setInvalidDecl();
5620 // A structure or union shall not contain a member with
5621 // incomplete or function type (hence, a structure shall not
5622 // contain an instance of itself, but may contain a pointer to
5623 // an instance of itself), except that the last member of a
5624 // structure with more than one named member may have incomplete
5625 // array type; such a structure (and any union containing,
5626 // possibly recursively, a member that is such a structure)
5627 // shall not be a member of a structure or an element of an
5629 if (FDTy->isFunctionType()) {
5630 // Field declared as a function.
5631 Diag(FD->getLocation(), diag::err_field_declared_as_function)
5632 << FD->getDeclName();
5633 FD->setInvalidDecl();
5634 EnclosingDecl->setInvalidDecl();
5636 } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 &&
5637 Record && Record->isStruct()) {
5638 // Flexible array member.
5639 if (NumNamedMembers < 1) {
5640 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
5641 << FD->getDeclName();
5642 FD->setInvalidDecl();
5643 EnclosingDecl->setInvalidDecl();
5646 // Okay, we have a legal flexible array member at the end of the struct.
5648 Record->setHasFlexibleArrayMember(true);
5649 } else if (!FDTy->isDependentType() &&
5650 RequireCompleteType(FD->getLocation(), FD->getType(),
5651 diag::err_field_incomplete)) {
5653 FD->setInvalidDecl();
5654 EnclosingDecl->setInvalidDecl();
5656 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
5657 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
5658 // If this is a member of a union, then entire union becomes "flexible".
5659 if (Record && Record->isUnion()) {
5660 Record->setHasFlexibleArrayMember(true);
5662 // If this is a struct/class and this is not the last element, reject
5663 // it. Note that GCC supports variable sized arrays in the middle of
5665 if (i != NumFields-1)
5666 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
5667 << FD->getDeclName() << FD->getType();
5669 // We support flexible arrays at the end of structs in
5670 // other structs as an extension.
5671 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
5672 << FD->getDeclName();
5674 Record->setHasFlexibleArrayMember(true);
5678 if (Record && FDTTy->getDecl()->hasObjectMember())
5679 Record->setHasObjectMember(true);
5680 } else if (FDTy->isObjCInterfaceType()) {
5681 /// A field cannot be an Objective-c object
5682 Diag(FD->getLocation(), diag::err_statically_allocated_object);
5683 FD->setInvalidDecl();
5684 EnclosingDecl->setInvalidDecl();
5686 } else if (getLangOptions().ObjC1 &&
5687 getLangOptions().getGCMode() != LangOptions::NonGC &&
5689 (FD->getType()->isObjCObjectPointerType() ||
5690 FD->getType().isObjCGCStrong()))
5691 Record->setHasObjectMember(true);
5692 // Keep track of the number of named members.
5693 if (FD->getIdentifier())
5697 // Okay, we successfully defined 'Record'.
5699 Record->completeDefinition(Context);
5701 ObjCIvarDecl **ClsFields =
5702 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
5703 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
5704 ID->setIVarList(ClsFields, RecFields.size(), Context);
5705 ID->setLocEnd(RBrac);
5706 // Add ivar's to class's DeclContext.
5707 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
5708 ClsFields[i]->setLexicalDeclContext(ID);
5709 ID->addDecl(ClsFields[i]);
5711 // Must enforce the rule that ivars in the base classes may not be
5713 if (ID->getSuperClass()) {
5714 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
5715 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
5716 ObjCIvarDecl* Ivar = (*IVI);
5718 if (IdentifierInfo *II = Ivar->getIdentifier()) {
5719 ObjCIvarDecl* prevIvar =
5720 ID->getSuperClass()->lookupInstanceVariable(II);
5722 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
5723 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
5728 } else if (ObjCImplementationDecl *IMPDecl =
5729 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
5730 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
5731 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
5732 // Ivar declared in @implementation never belongs to the implementation.
5733 // Only it is in implementation's lexical context.
5734 ClsFields[I]->setLexicalDeclContext(IMPDecl);
5735 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
5740 ProcessDeclAttributeList(S, Record, Attr);
5743 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
5744 EnumConstantDecl *LastEnumConst,
5745 SourceLocation IdLoc,
5748 Expr *Val = (Expr *)val.get();
5750 llvm::APSInt EnumVal(32);
5753 if (Enum->isDependentType())
5754 EltTy = Context.DependentTy;
5756 // Make sure to promote the operand type to int.
5757 UsualUnaryConversions(Val);
5758 if (Val != val.get()) {
5763 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
5764 SourceLocation ExpLoc;
5765 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
5768 EltTy = Val->getType();
5774 if (Enum->isDependentType())
5775 EltTy = Context.DependentTy;
5776 else if (LastEnumConst) {
5777 // Assign the last value + 1.
5778 EnumVal = LastEnumConst->getInitVal();
5781 // Check for overflow on increment.
5782 if (EnumVal < LastEnumConst->getInitVal())
5783 Diag(IdLoc, diag::warn_enum_value_overflow);
5785 EltTy = LastEnumConst->getType();
5787 // First value, set to zero.
5788 EltTy = Context.IntTy;
5789 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
5790 EnumVal.setIsSigned(true);
5794 assert(!EltTy.isNull() && "Enum constant with NULL type");
5797 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
5802 Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl,
5803 DeclPtrTy lastEnumConst,
5804 SourceLocation IdLoc,
5806 SourceLocation EqualLoc, ExprTy *val) {
5807 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>());
5808 EnumConstantDecl *LastEnumConst =
5809 cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>());
5810 Expr *Val = static_cast<Expr*>(val);
5812 // The scope passed in may not be a decl scope. Zip up the scope tree until
5813 // we find one that is.
5814 S = getNonFieldDeclScope(S);
5816 // Verify that there isn't already something declared with this name in this
5818 NamedDecl *PrevDecl = LookupSingleName(S, Id, LookupOrdinaryName);
5819 if (PrevDecl && PrevDecl->isTemplateParameter()) {
5820 // Maybe we will complain about the shadowed template parameter.
5821 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
5822 // Just pretend that we didn't see the previous declaration.
5827 // When in C++, we may get a TagDecl with the same name; in this case the
5828 // enum constant will 'hide' the tag.
5829 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
5830 "Received TagDecl when not in C++!");
5831 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
5832 if (isa<EnumConstantDecl>(PrevDecl))
5833 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
5835 Diag(IdLoc, diag::err_redefinition) << Id;
5836 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5837 if (Val) Val->Destroy(Context);
5842 EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst,
5843 IdLoc, Id, Owned(Val));
5845 // Register this decl in the current scope stack.
5847 PushOnScopeChains(New, S);
5849 return DeclPtrTy::make(New);
5852 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
5853 SourceLocation RBraceLoc, DeclPtrTy EnumDeclX,
5854 DeclPtrTy *Elements, unsigned NumElements,
5855 Scope *S, AttributeList *Attr) {
5856 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>());
5857 QualType EnumType = Context.getTypeDeclType(Enum);
5860 ProcessDeclAttributeList(S, Enum, Attr);
5862 if (Enum->isDependentType()) {
5863 for (unsigned i = 0; i != NumElements; ++i) {
5864 EnumConstantDecl *ECD =
5865 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
5868 ECD->setType(EnumType);
5871 Enum->completeDefinition(Context, Context.DependentTy, Context.DependentTy);
5875 // TODO: If the result value doesn't fit in an int, it must be a long or long
5876 // long value. ISO C does not support this, but GCC does as an extension,
5878 unsigned IntWidth = Context.Target.getIntWidth();
5879 unsigned CharWidth = Context.Target.getCharWidth();
5880 unsigned ShortWidth = Context.Target.getShortWidth();
5882 // Verify that all the values are okay, compute the size of the values, and
5883 // reverse the list.
5884 unsigned NumNegativeBits = 0;
5885 unsigned NumPositiveBits = 0;
5887 // Keep track of whether all elements have type int.
5888 bool AllElementsInt = true;
5890 for (unsigned i = 0; i != NumElements; ++i) {
5891 EnumConstantDecl *ECD =
5892 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
5893 if (!ECD) continue; // Already issued a diagnostic.
5895 // If the enum value doesn't fit in an int, emit an extension warning.
5896 const llvm::APSInt &InitVal = ECD->getInitVal();
5897 assert(InitVal.getBitWidth() >= IntWidth &&
5898 "Should have promoted value to int");
5899 if (!getLangOptions().CPlusPlus && InitVal.getBitWidth() > IntWidth) {
5900 llvm::APSInt V(InitVal);
5902 V.extend(InitVal.getBitWidth());
5904 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
5905 << InitVal.toString(10);
5908 // Keep track of the size of positive and negative values.
5909 if (InitVal.isUnsigned() || InitVal.isNonNegative())
5910 NumPositiveBits = std::max(NumPositiveBits,
5911 (unsigned)InitVal.getActiveBits());
5913 NumNegativeBits = std::max(NumNegativeBits,
5914 (unsigned)InitVal.getMinSignedBits());
5916 // Keep track of whether every enum element has type int (very commmon).
5918 AllElementsInt = ECD->getType() == Context.IntTy;
5921 // Figure out the type that should be used for this enum.
5922 // FIXME: Support -fshort-enums.
5926 // C++0x N3000 [conv.prom]p3:
5927 // An rvalue of an unscoped enumeration type whose underlying
5928 // type is not fixed can be converted to an rvalue of the first
5929 // of the following types that can represent all the values of
5930 // the enumeration: int, unsigned int, long int, unsigned long
5931 // int, long long int, or unsigned long long int.
5933 // An identifier declared as an enumeration constant has type int.
5934 // The C99 rule is modified by a gcc extension
5935 QualType BestPromotionType;
5937 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
5939 if (NumNegativeBits) {
5940 // If there is a negative value, figure out the smallest integer type (of
5941 // int/long/longlong) that fits.
5942 // If it's packed, check also if it fits a char or a short.
5943 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
5944 BestType = Context.SignedCharTy;
5945 BestWidth = CharWidth;
5946 } else if (Packed && NumNegativeBits <= ShortWidth &&
5947 NumPositiveBits < ShortWidth) {
5948 BestType = Context.ShortTy;
5949 BestWidth = ShortWidth;
5950 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5951 BestType = Context.IntTy;
5952 BestWidth = IntWidth;
5954 BestWidth = Context.Target.getLongWidth();
5956 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5957 BestType = Context.LongTy;
5959 BestWidth = Context.Target.getLongLongWidth();
5961 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5962 Diag(Enum->getLocation(), diag::warn_enum_too_large);
5963 BestType = Context.LongLongTy;
5966 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
5968 // If there is no negative value, figure out which of uint, ulong, ulonglong
5970 // If it's packed, check also if it fits a char or a short.
5971 if (Packed && NumPositiveBits <= CharWidth) {
5972 BestType = Context.UnsignedCharTy;
5973 BestPromotionType = Context.IntTy;
5974 BestWidth = CharWidth;
5975 } else if (Packed && NumPositiveBits <= ShortWidth) {
5976 BestType = Context.UnsignedShortTy;
5977 BestPromotionType = Context.IntTy;
5978 BestWidth = ShortWidth;
5979 } else if (NumPositiveBits <= IntWidth) {
5980 BestType = Context.UnsignedIntTy;
5981 BestWidth = IntWidth;
5982 BestPromotionType = (NumPositiveBits == BestWidth
5983 ? Context.UnsignedIntTy : Context.IntTy);
5984 } else if (NumPositiveBits <=
5985 (BestWidth = Context.Target.getLongWidth())) {
5986 BestType = Context.UnsignedLongTy;
5987 BestPromotionType = (NumPositiveBits == BestWidth
5988 ? Context.UnsignedLongTy : Context.LongTy);
5990 BestWidth = Context.Target.getLongLongWidth();
5991 assert(NumPositiveBits <= BestWidth &&
5992 "How could an initializer get larger than ULL?");
5993 BestType = Context.UnsignedLongLongTy;
5994 BestPromotionType = (NumPositiveBits == BestWidth
5995 ? Context.UnsignedLongLongTy : Context.LongLongTy);
5999 // If we're in C and the promotion type is larger than an int, just
6000 // use the underlying type, which is generally the unsigned integer
6001 // type of the same rank as the promotion type. This is how the gcc
6003 if (!getLangOptions().CPlusPlus && BestPromotionType != Context.IntTy)
6004 BestPromotionType = BestType;
6006 // Loop over all of the enumerator constants, changing their types to match
6007 // the type of the enum if needed.
6008 for (unsigned i = 0; i != NumElements; ++i) {
6009 EnumConstantDecl *ECD =
6010 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
6011 if (!ECD) continue; // Already issued a diagnostic.
6013 // Standard C says the enumerators have int type, but we allow, as an
6014 // extension, the enumerators to be larger than int size. If each
6015 // enumerator value fits in an int, type it as an int, otherwise type it the
6016 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
6017 // that X has type 'int', not 'unsigned'.
6018 if (!getLangOptions().CPlusPlus && ECD->getType() == Context.IntTy)
6021 // Determine whether the value fits into an int.
6022 llvm::APSInt InitVal = ECD->getInitVal();
6024 if (InitVal.isUnsigned() || !InitVal.isNegative())
6025 FitsInInt = InitVal.getActiveBits() < IntWidth;
6027 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
6029 // If it fits into an integer type, force it. Otherwise force it to match
6030 // the enum decl type.
6034 if (FitsInInt && !getLangOptions().CPlusPlus) {
6035 NewTy = Context.IntTy;
6036 NewWidth = IntWidth;
6038 } else if (ECD->getType() == BestType) {
6039 // Already the right type!
6040 if (getLangOptions().CPlusPlus)
6041 // C++ [dcl.enum]p4: Following the closing brace of an
6042 // enum-specifier, each enumerator has the type of its
6044 ECD->setType(EnumType);
6048 NewWidth = BestWidth;
6049 NewSign = BestType->isSignedIntegerType();
6052 // Adjust the APSInt value.
6053 InitVal.extOrTrunc(NewWidth);
6054 InitVal.setIsSigned(NewSign);
6055 ECD->setInitVal(InitVal);
6057 // Adjust the Expr initializer and type.
6058 if (ECD->getInitExpr())
6059 ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy,
6060 CastExpr::CK_IntegralCast,
6062 /*isLvalue=*/false));
6063 if (getLangOptions().CPlusPlus)
6064 // C++ [dcl.enum]p4: Following the closing brace of an
6065 // enum-specifier, each enumerator has the type of its
6067 ECD->setType(EnumType);
6069 ECD->setType(NewTy);
6072 Enum->completeDefinition(Context, BestType, BestPromotionType);
6075 Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
6077 StringLiteral *AsmString = cast<StringLiteral>(expr.takeAs<Expr>());
6079 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
6081 CurContext->addDecl(New);
6082 return DeclPtrTy::make(New);
6085 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
6086 SourceLocation PragmaLoc,
6087 SourceLocation NameLoc) {
6088 Decl *PrevDecl = LookupSingleName(TUScope, Name, LookupOrdinaryName);
6091 PrevDecl->addAttr(::new (Context) WeakAttr());
6093 (void)WeakUndeclaredIdentifiers.insert(
6094 std::pair<IdentifierInfo*,WeakInfo>
6095 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
6099 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
6100 IdentifierInfo* AliasName,
6101 SourceLocation PragmaLoc,
6102 SourceLocation NameLoc,
6103 SourceLocation AliasNameLoc) {
6104 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, LookupOrdinaryName);
6105 WeakInfo W = WeakInfo(Name, NameLoc);
6108 if (!PrevDecl->hasAttr<AliasAttr>())
6109 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
6110 DeclApplyPragmaWeak(TUScope, ND, W);
6112 (void)WeakUndeclaredIdentifiers.insert(
6113 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));