Don't warn that variables in C++ static member functions shadow fields. Fixes rdar...
[clang.git] / lib / Sema / SemaDecl.cpp
blobb2cb96134c0f0057decdca825d89d0ca3cdd34ee
1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements semantic analysis for declarations.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/Initialization.h"
16 #include "clang/Sema/Lookup.h"
17 #include "clang/Sema/CXXFieldCollector.h"
18 #include "clang/Sema/Scope.h"
19 #include "clang/Sema/ScopeInfo.h"
20 #include "clang/AST/APValue.h"
21 #include "clang/AST/ASTConsumer.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/CXXInheritance.h"
24 #include "clang/AST/DeclCXX.h"
25 #include "clang/AST/DeclObjC.h"
26 #include "clang/AST/DeclTemplate.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/AST/CharUnits.h"
30 #include "clang/Sema/DeclSpec.h"
31 #include "clang/Sema/ParsedTemplate.h"
32 #include "clang/Parse/ParseDiagnostic.h"
33 #include "clang/Basic/PartialDiagnostic.h"
34 #include "clang/Basic/SourceManager.h"
35 #include "clang/Basic/TargetInfo.h"
36 // FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
37 #include "clang/Lex/Preprocessor.h"
38 #include "clang/Lex/HeaderSearch.h"
39 #include "llvm/ADT/Triple.h"
40 #include <algorithm>
41 #include <cstring>
42 #include <functional>
43 using namespace clang;
44 using namespace sema;
46 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr) {
47 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
50 /// \brief If the identifier refers to a type name within this scope,
51 /// return the declaration of that type.
52 ///
53 /// This routine performs ordinary name lookup of the identifier II
54 /// within the given scope, with optional C++ scope specifier SS, to
55 /// determine whether the name refers to a type. If so, returns an
56 /// opaque pointer (actually a QualType) corresponding to that
57 /// type. Otherwise, returns NULL.
58 ///
59 /// If name lookup results in an ambiguity, this routine will complain
60 /// and then return NULL.
61 ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
62 Scope *S, CXXScopeSpec *SS,
63 bool isClassName,
64 ParsedType ObjectTypePtr) {
65 // Determine where we will perform name lookup.
66 DeclContext *LookupCtx = 0;
67 if (ObjectTypePtr) {
68 QualType ObjectType = ObjectTypePtr.get();
69 if (ObjectType->isRecordType())
70 LookupCtx = computeDeclContext(ObjectType);
71 } else if (SS && SS->isNotEmpty()) {
72 LookupCtx = computeDeclContext(*SS, false);
74 if (!LookupCtx) {
75 if (isDependentScopeSpecifier(*SS)) {
76 // C++ [temp.res]p3:
77 // A qualified-id that refers to a type and in which the
78 // nested-name-specifier depends on a template-parameter (14.6.2)
79 // shall be prefixed by the keyword typename to indicate that the
80 // qualified-id denotes a type, forming an
81 // elaborated-type-specifier (7.1.5.3).
83 // We therefore do not perform any name lookup if the result would
84 // refer to a member of an unknown specialization.
85 if (!isClassName)
86 return ParsedType();
88 // We know from the grammar that this name refers to a type,
89 // so build a dependent node to describe the type.
90 QualType T =
91 CheckTypenameType(ETK_None, SS->getScopeRep(), II,
92 SourceLocation(), SS->getRange(), NameLoc);
93 return ParsedType::make(T);
96 return ParsedType();
99 if (!LookupCtx->isDependentContext() &&
100 RequireCompleteDeclContext(*SS, LookupCtx))
101 return ParsedType();
104 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
105 // lookup for class-names.
106 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
107 LookupOrdinaryName;
108 LookupResult Result(*this, &II, NameLoc, Kind);
109 if (LookupCtx) {
110 // Perform "qualified" name lookup into the declaration context we
111 // computed, which is either the type of the base of a member access
112 // expression or the declaration context associated with a prior
113 // nested-name-specifier.
114 LookupQualifiedName(Result, LookupCtx);
116 if (ObjectTypePtr && Result.empty()) {
117 // C++ [basic.lookup.classref]p3:
118 // If the unqualified-id is ~type-name, the type-name is looked up
119 // in the context of the entire postfix-expression. If the type T of
120 // the object expression is of a class type C, the type-name is also
121 // looked up in the scope of class C. At least one of the lookups shall
122 // find a name that refers to (possibly cv-qualified) T.
123 LookupName(Result, S);
125 } else {
126 // Perform unqualified name lookup.
127 LookupName(Result, S);
130 NamedDecl *IIDecl = 0;
131 switch (Result.getResultKind()) {
132 case LookupResult::NotFound:
133 case LookupResult::NotFoundInCurrentInstantiation:
134 case LookupResult::FoundOverloaded:
135 case LookupResult::FoundUnresolvedValue:
136 Result.suppressDiagnostics();
137 return ParsedType();
139 case LookupResult::Ambiguous:
140 // Recover from type-hiding ambiguities by hiding the type. We'll
141 // do the lookup again when looking for an object, and we can
142 // diagnose the error then. If we don't do this, then the error
143 // about hiding the type will be immediately followed by an error
144 // that only makes sense if the identifier was treated like a type.
145 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
146 Result.suppressDiagnostics();
147 return ParsedType();
150 // Look to see if we have a type anywhere in the list of results.
151 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
152 Res != ResEnd; ++Res) {
153 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
154 if (!IIDecl ||
155 (*Res)->getLocation().getRawEncoding() <
156 IIDecl->getLocation().getRawEncoding())
157 IIDecl = *Res;
161 if (!IIDecl) {
162 // None of the entities we found is a type, so there is no way
163 // to even assume that the result is a type. In this case, don't
164 // complain about the ambiguity. The parser will either try to
165 // perform this lookup again (e.g., as an object name), which
166 // will produce the ambiguity, or will complain that it expected
167 // a type name.
168 Result.suppressDiagnostics();
169 return ParsedType();
172 // We found a type within the ambiguous lookup; diagnose the
173 // ambiguity and then return that type. This might be the right
174 // answer, or it might not be, but it suppresses any attempt to
175 // perform the name lookup again.
176 break;
178 case LookupResult::Found:
179 IIDecl = Result.getFoundDecl();
180 break;
183 assert(IIDecl && "Didn't find decl");
185 QualType T;
186 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
187 DiagnoseUseOfDecl(IIDecl, NameLoc);
189 if (T.isNull())
190 T = Context.getTypeDeclType(TD);
192 if (SS)
193 T = getElaboratedType(ETK_None, *SS, T);
195 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
196 T = Context.getObjCInterfaceType(IDecl);
197 } else {
198 // If it's not plausibly a type, suppress diagnostics.
199 Result.suppressDiagnostics();
200 return ParsedType();
203 return ParsedType::make(T);
206 /// isTagName() - This method is called *for error recovery purposes only*
207 /// to determine if the specified name is a valid tag name ("struct foo"). If
208 /// so, this returns the TST for the tag corresponding to it (TST_enum,
209 /// TST_union, TST_struct, TST_class). This is used to diagnose cases in C
210 /// where the user forgot to specify the tag.
211 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
212 // Do a tag name lookup in this scope.
213 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
214 LookupName(R, S, false);
215 R.suppressDiagnostics();
216 if (R.getResultKind() == LookupResult::Found)
217 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
218 switch (TD->getTagKind()) {
219 default: return DeclSpec::TST_unspecified;
220 case TTK_Struct: return DeclSpec::TST_struct;
221 case TTK_Union: return DeclSpec::TST_union;
222 case TTK_Class: return DeclSpec::TST_class;
223 case TTK_Enum: return DeclSpec::TST_enum;
227 return DeclSpec::TST_unspecified;
230 bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
231 SourceLocation IILoc,
232 Scope *S,
233 CXXScopeSpec *SS,
234 ParsedType &SuggestedType) {
235 // We don't have anything to suggest (yet).
236 SuggestedType = ParsedType();
238 // There may have been a typo in the name of the type. Look up typo
239 // results, in case we have something that we can suggest.
240 LookupResult Lookup(*this, &II, IILoc, LookupOrdinaryName,
241 NotForRedeclaration);
243 if (DeclarationName Corrected = CorrectTypo(Lookup, S, SS, 0, 0, CTC_Type)) {
244 if (NamedDecl *Result = Lookup.getAsSingle<NamedDecl>()) {
245 if ((isa<TypeDecl>(Result) || isa<ObjCInterfaceDecl>(Result)) &&
246 !Result->isInvalidDecl()) {
247 // We found a similarly-named type or interface; suggest that.
248 if (!SS || !SS->isSet())
249 Diag(IILoc, diag::err_unknown_typename_suggest)
250 << &II << Lookup.getLookupName()
251 << FixItHint::CreateReplacement(SourceRange(IILoc),
252 Result->getNameAsString());
253 else if (DeclContext *DC = computeDeclContext(*SS, false))
254 Diag(IILoc, diag::err_unknown_nested_typename_suggest)
255 << &II << DC << Lookup.getLookupName() << SS->getRange()
256 << FixItHint::CreateReplacement(SourceRange(IILoc),
257 Result->getNameAsString());
258 else
259 llvm_unreachable("could not have corrected a typo here");
261 Diag(Result->getLocation(), diag::note_previous_decl)
262 << Result->getDeclName();
264 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS);
265 return true;
267 } else if (Lookup.empty()) {
268 // We corrected to a keyword.
269 // FIXME: Actually recover with the keyword we suggest, and emit a fix-it.
270 Diag(IILoc, diag::err_unknown_typename_suggest)
271 << &II << Corrected;
272 return true;
276 if (getLangOptions().CPlusPlus) {
277 // See if II is a class template that the user forgot to pass arguments to.
278 UnqualifiedId Name;
279 Name.setIdentifier(&II, IILoc);
280 CXXScopeSpec EmptySS;
281 TemplateTy TemplateResult;
282 bool MemberOfUnknownSpecialization;
283 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
284 Name, ParsedType(), true, TemplateResult,
285 MemberOfUnknownSpecialization) == TNK_Type_template) {
286 TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
287 Diag(IILoc, diag::err_template_missing_args) << TplName;
288 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
289 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
290 << TplDecl->getTemplateParameters()->getSourceRange();
292 return true;
296 // FIXME: Should we move the logic that tries to recover from a missing tag
297 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
299 if (!SS || (!SS->isSet() && !SS->isInvalid()))
300 Diag(IILoc, diag::err_unknown_typename) << &II;
301 else if (DeclContext *DC = computeDeclContext(*SS, false))
302 Diag(IILoc, diag::err_typename_nested_not_found)
303 << &II << DC << SS->getRange();
304 else if (isDependentScopeSpecifier(*SS)) {
305 Diag(SS->getRange().getBegin(), diag::err_typename_missing)
306 << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
307 << SourceRange(SS->getRange().getBegin(), IILoc)
308 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
309 SuggestedType = ActOnTypenameType(S, SourceLocation(), *SS, II, IILoc).get();
310 } else {
311 assert(SS && SS->isInvalid() &&
312 "Invalid scope specifier has already been diagnosed");
315 return true;
318 // Determines the context to return to after temporarily entering a
319 // context. This depends in an unnecessarily complicated way on the
320 // exact ordering of callbacks from the parser.
321 DeclContext *Sema::getContainingDC(DeclContext *DC) {
323 // Functions defined inline within classes aren't parsed until we've
324 // finished parsing the top-level class, so the top-level class is
325 // the context we'll need to return to.
326 if (isa<FunctionDecl>(DC)) {
327 DC = DC->getLexicalParent();
329 // A function not defined within a class will always return to its
330 // lexical context.
331 if (!isa<CXXRecordDecl>(DC))
332 return DC;
334 // A C++ inline method/friend is parsed *after* the topmost class
335 // it was declared in is fully parsed ("complete"); the topmost
336 // class is the context we need to return to.
337 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
338 DC = RD;
340 // Return the declaration context of the topmost class the inline method is
341 // declared in.
342 return DC;
345 // ObjCMethodDecls are parsed (for some reason) outside the context
346 // of the class.
347 if (isa<ObjCMethodDecl>(DC))
348 return DC->getLexicalParent()->getLexicalParent();
350 return DC->getLexicalParent();
353 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
354 assert(getContainingDC(DC) == CurContext &&
355 "The next DeclContext should be lexically contained in the current one.");
356 CurContext = DC;
357 S->setEntity(DC);
360 void Sema::PopDeclContext() {
361 assert(CurContext && "DeclContext imbalance!");
363 CurContext = getContainingDC(CurContext);
364 assert(CurContext && "Popped translation unit!");
367 /// EnterDeclaratorContext - Used when we must lookup names in the context
368 /// of a declarator's nested name specifier.
370 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
371 // C++0x [basic.lookup.unqual]p13:
372 // A name used in the definition of a static data member of class
373 // X (after the qualified-id of the static member) is looked up as
374 // if the name was used in a member function of X.
375 // C++0x [basic.lookup.unqual]p14:
376 // If a variable member of a namespace is defined outside of the
377 // scope of its namespace then any name used in the definition of
378 // the variable member (after the declarator-id) is looked up as
379 // if the definition of the variable member occurred in its
380 // namespace.
381 // Both of these imply that we should push a scope whose context
382 // is the semantic context of the declaration. We can't use
383 // PushDeclContext here because that context is not necessarily
384 // lexically contained in the current context. Fortunately,
385 // the containing scope should have the appropriate information.
387 assert(!S->getEntity() && "scope already has entity");
389 #ifndef NDEBUG
390 Scope *Ancestor = S->getParent();
391 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
392 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
393 #endif
395 CurContext = DC;
396 S->setEntity(DC);
399 void Sema::ExitDeclaratorContext(Scope *S) {
400 assert(S->getEntity() == CurContext && "Context imbalance!");
402 // Switch back to the lexical context. The safety of this is
403 // enforced by an assert in EnterDeclaratorContext.
404 Scope *Ancestor = S->getParent();
405 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
406 CurContext = (DeclContext*) Ancestor->getEntity();
408 // We don't need to do anything with the scope, which is going to
409 // disappear.
412 /// \brief Determine whether we allow overloading of the function
413 /// PrevDecl with another declaration.
415 /// This routine determines whether overloading is possible, not
416 /// whether some new function is actually an overload. It will return
417 /// true in C++ (where we can always provide overloads) or, as an
418 /// extension, in C when the previous function is already an
419 /// overloaded function declaration or has the "overloadable"
420 /// attribute.
421 static bool AllowOverloadingOfFunction(LookupResult &Previous,
422 ASTContext &Context) {
423 if (Context.getLangOptions().CPlusPlus)
424 return true;
426 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
427 return true;
429 return (Previous.getResultKind() == LookupResult::Found
430 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
433 /// Add this decl to the scope shadowed decl chains.
434 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
435 // Move up the scope chain until we find the nearest enclosing
436 // non-transparent context. The declaration will be introduced into this
437 // scope.
438 while (S->getEntity() &&
439 ((DeclContext *)S->getEntity())->isTransparentContext())
440 S = S->getParent();
442 // Add scoped declarations into their context, so that they can be
443 // found later. Declarations without a context won't be inserted
444 // into any context.
445 if (AddToContext)
446 CurContext->addDecl(D);
448 // Out-of-line definitions shouldn't be pushed into scope in C++.
449 // Out-of-line variable and function definitions shouldn't even in C.
450 if ((getLangOptions().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
451 D->isOutOfLine())
452 return;
454 // Template instantiations should also not be pushed into scope.
455 if (isa<FunctionDecl>(D) &&
456 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
457 return;
459 // If this replaces anything in the current scope,
460 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
461 IEnd = IdResolver.end();
462 for (; I != IEnd; ++I) {
463 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
464 S->RemoveDecl(*I);
465 IdResolver.RemoveDecl(*I);
467 // Should only need to replace one decl.
468 break;
472 S->AddDecl(D);
473 IdResolver.AddDecl(D);
476 bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S) {
477 return IdResolver.isDeclInScope(D, Ctx, Context, S);
480 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
481 DeclContext *TargetDC = DC->getPrimaryContext();
482 do {
483 if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
484 if (ScopeDC->getPrimaryContext() == TargetDC)
485 return S;
486 } while ((S = S->getParent()));
488 return 0;
491 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
492 DeclContext*,
493 ASTContext&);
495 /// Filters out lookup results that don't fall within the given scope
496 /// as determined by isDeclInScope.
497 static void FilterLookupForScope(Sema &SemaRef, LookupResult &R,
498 DeclContext *Ctx, Scope *S,
499 bool ConsiderLinkage) {
500 LookupResult::Filter F = R.makeFilter();
501 while (F.hasNext()) {
502 NamedDecl *D = F.next();
504 if (SemaRef.isDeclInScope(D, Ctx, S))
505 continue;
507 if (ConsiderLinkage &&
508 isOutOfScopePreviousDeclaration(D, Ctx, SemaRef.Context))
509 continue;
511 F.erase();
514 F.done();
517 static bool isUsingDecl(NamedDecl *D) {
518 return isa<UsingShadowDecl>(D) ||
519 isa<UnresolvedUsingTypenameDecl>(D) ||
520 isa<UnresolvedUsingValueDecl>(D);
523 /// Removes using shadow declarations from the lookup results.
524 static void RemoveUsingDecls(LookupResult &R) {
525 LookupResult::Filter F = R.makeFilter();
526 while (F.hasNext())
527 if (isUsingDecl(F.next()))
528 F.erase();
530 F.done();
533 /// \brief Check for this common pattern:
534 /// @code
535 /// class S {
536 /// S(const S&); // DO NOT IMPLEMENT
537 /// void operator=(const S&); // DO NOT IMPLEMENT
538 /// };
539 /// @endcode
540 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
541 // FIXME: Should check for private access too but access is set after we get
542 // the decl here.
543 if (D->isThisDeclarationADefinition())
544 return false;
546 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
547 return CD->isCopyConstructor();
548 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
549 return Method->isCopyAssignmentOperator();
550 return false;
553 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
554 assert(D);
556 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
557 return false;
559 // Ignore class templates.
560 if (D->getDeclContext()->isDependentContext() ||
561 D->getLexicalDeclContext()->isDependentContext())
562 return false;
564 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
565 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
566 return false;
568 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
569 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
570 return false;
571 } else {
572 // 'static inline' functions are used in headers; don't warn.
573 if (FD->getStorageClass() == SC_Static &&
574 FD->isInlineSpecified())
575 return false;
578 if (FD->isThisDeclarationADefinition() &&
579 Context.DeclMustBeEmitted(FD))
580 return false;
582 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
583 if (!VD->isFileVarDecl() ||
584 VD->getType().isConstant(Context) ||
585 Context.DeclMustBeEmitted(VD))
586 return false;
588 if (VD->isStaticDataMember() &&
589 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
590 return false;
592 } else {
593 return false;
596 // Only warn for unused decls internal to the translation unit.
597 if (D->getLinkage() == ExternalLinkage)
598 return false;
600 return true;
603 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
604 if (!D)
605 return;
607 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
608 const FunctionDecl *First = FD->getFirstDeclaration();
609 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
610 return; // First should already be in the vector.
613 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
614 const VarDecl *First = VD->getFirstDeclaration();
615 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
616 return; // First should already be in the vector.
619 if (ShouldWarnIfUnusedFileScopedDecl(D))
620 UnusedFileScopedDecls.push_back(D);
623 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
624 if (D->isInvalidDecl())
625 return false;
627 if (D->isUsed() || D->hasAttr<UnusedAttr>())
628 return false;
630 // White-list anything that isn't a local variable.
631 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
632 !D->getDeclContext()->isFunctionOrMethod())
633 return false;
635 // Types of valid local variables should be complete, so this should succeed.
636 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
638 // White-list anything with an __attribute__((unused)) type.
639 QualType Ty = VD->getType();
641 // Only look at the outermost level of typedef.
642 if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) {
643 if (TT->getDecl()->hasAttr<UnusedAttr>())
644 return false;
647 // If we failed to complete the type for some reason, or if the type is
648 // dependent, don't diagnose the variable.
649 if (Ty->isIncompleteType() || Ty->isDependentType())
650 return false;
652 if (const TagType *TT = Ty->getAs<TagType>()) {
653 const TagDecl *Tag = TT->getDecl();
654 if (Tag->hasAttr<UnusedAttr>())
655 return false;
657 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
658 // FIXME: Checking for the presence of a user-declared constructor
659 // isn't completely accurate; we'd prefer to check that the initializer
660 // has no side effects.
661 if (RD->hasUserDeclaredConstructor() || !RD->hasTrivialDestructor())
662 return false;
666 // TODO: __attribute__((unused)) templates?
669 return true;
672 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
673 if (!ShouldDiagnoseUnusedDecl(D))
674 return;
676 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
677 Diag(D->getLocation(), diag::warn_unused_exception_param)
678 << D->getDeclName();
679 else
680 Diag(D->getLocation(), diag::warn_unused_variable)
681 << D->getDeclName();
684 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
685 if (S->decl_empty()) return;
686 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
687 "Scope shouldn't contain decls!");
689 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
690 I != E; ++I) {
691 Decl *TmpD = (*I);
692 assert(TmpD && "This decl didn't get pushed??");
694 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
695 NamedDecl *D = cast<NamedDecl>(TmpD);
697 if (!D->getDeclName()) continue;
699 // Diagnose unused variables in this scope.
700 if (!S->hasErrorOccurred())
701 DiagnoseUnusedDecl(D);
703 // Remove this name from our lexical scope.
704 IdResolver.RemoveDecl(D);
708 /// \brief Look for an Objective-C class in the translation unit.
710 /// \param Id The name of the Objective-C class we're looking for. If
711 /// typo-correction fixes this name, the Id will be updated
712 /// to the fixed name.
714 /// \param IdLoc The location of the name in the translation unit.
716 /// \param TypoCorrection If true, this routine will attempt typo correction
717 /// if there is no class with the given name.
719 /// \returns The declaration of the named Objective-C class, or NULL if the
720 /// class could not be found.
721 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
722 SourceLocation IdLoc,
723 bool TypoCorrection) {
724 // The third "scope" argument is 0 since we aren't enabling lazy built-in
725 // creation from this context.
726 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
728 if (!IDecl && TypoCorrection) {
729 // Perform typo correction at the given location, but only if we
730 // find an Objective-C class name.
731 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName);
732 if (CorrectTypo(R, TUScope, 0, 0, false, CTC_NoKeywords) &&
733 (IDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
734 Diag(IdLoc, diag::err_undef_interface_suggest)
735 << Id << IDecl->getDeclName()
736 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
737 Diag(IDecl->getLocation(), diag::note_previous_decl)
738 << IDecl->getDeclName();
740 Id = IDecl->getIdentifier();
744 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
747 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
748 /// from S, where a non-field would be declared. This routine copes
749 /// with the difference between C and C++ scoping rules in structs and
750 /// unions. For example, the following code is well-formed in C but
751 /// ill-formed in C++:
752 /// @code
753 /// struct S6 {
754 /// enum { BAR } e;
755 /// };
757 /// void test_S6() {
758 /// struct S6 a;
759 /// a.e = BAR;
760 /// }
761 /// @endcode
762 /// For the declaration of BAR, this routine will return a different
763 /// scope. The scope S will be the scope of the unnamed enumeration
764 /// within S6. In C++, this routine will return the scope associated
765 /// with S6, because the enumeration's scope is a transparent
766 /// context but structures can contain non-field names. In C, this
767 /// routine will return the translation unit scope, since the
768 /// enumeration's scope is a transparent context and structures cannot
769 /// contain non-field names.
770 Scope *Sema::getNonFieldDeclScope(Scope *S) {
771 while (((S->getFlags() & Scope::DeclScope) == 0) ||
772 (S->getEntity() &&
773 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
774 (S->isClassScope() && !getLangOptions().CPlusPlus))
775 S = S->getParent();
776 return S;
779 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
780 /// file scope. lazily create a decl for it. ForRedeclaration is true
781 /// if we're creating this built-in in anticipation of redeclaring the
782 /// built-in.
783 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
784 Scope *S, bool ForRedeclaration,
785 SourceLocation Loc) {
786 Builtin::ID BID = (Builtin::ID)bid;
788 ASTContext::GetBuiltinTypeError Error;
789 QualType R = Context.GetBuiltinType(BID, Error);
790 switch (Error) {
791 case ASTContext::GE_None:
792 // Okay
793 break;
795 case ASTContext::GE_Missing_stdio:
796 if (ForRedeclaration)
797 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
798 << Context.BuiltinInfo.GetName(BID);
799 return 0;
801 case ASTContext::GE_Missing_setjmp:
802 if (ForRedeclaration)
803 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
804 << Context.BuiltinInfo.GetName(BID);
805 return 0;
808 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
809 Diag(Loc, diag::ext_implicit_lib_function_decl)
810 << Context.BuiltinInfo.GetName(BID)
811 << R;
812 if (Context.BuiltinInfo.getHeaderName(BID) &&
813 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
814 != Diagnostic::Ignored)
815 Diag(Loc, diag::note_please_include_header)
816 << Context.BuiltinInfo.getHeaderName(BID)
817 << Context.BuiltinInfo.GetName(BID);
820 FunctionDecl *New = FunctionDecl::Create(Context,
821 Context.getTranslationUnitDecl(),
822 Loc, II, R, /*TInfo=*/0,
823 SC_Extern,
824 SC_None, false,
825 /*hasPrototype=*/true);
826 New->setImplicit();
828 // Create Decl objects for each parameter, adding them to the
829 // FunctionDecl.
830 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
831 llvm::SmallVector<ParmVarDecl*, 16> Params;
832 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
833 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
834 FT->getArgType(i), /*TInfo=*/0,
835 SC_None, SC_None, 0));
836 New->setParams(Params.data(), Params.size());
839 AddKnownFunctionAttributes(New);
841 // TUScope is the translation-unit scope to insert this function into.
842 // FIXME: This is hideous. We need to teach PushOnScopeChains to
843 // relate Scopes to DeclContexts, and probably eliminate CurContext
844 // entirely, but we're not there yet.
845 DeclContext *SavedContext = CurContext;
846 CurContext = Context.getTranslationUnitDecl();
847 PushOnScopeChains(New, TUScope);
848 CurContext = SavedContext;
849 return New;
852 /// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
853 /// same name and scope as a previous declaration 'Old'. Figure out
854 /// how to resolve this situation, merging decls or emitting
855 /// diagnostics as appropriate. If there was an error, set New to be invalid.
857 void Sema::MergeTypeDefDecl(TypedefDecl *New, LookupResult &OldDecls) {
858 // If the new decl is known invalid already, don't bother doing any
859 // merging checks.
860 if (New->isInvalidDecl()) return;
862 // Allow multiple definitions for ObjC built-in typedefs.
863 // FIXME: Verify the underlying types are equivalent!
864 if (getLangOptions().ObjC1) {
865 const IdentifierInfo *TypeID = New->getIdentifier();
866 switch (TypeID->getLength()) {
867 default: break;
868 case 2:
869 if (!TypeID->isStr("id"))
870 break;
871 Context.ObjCIdRedefinitionType = New->getUnderlyingType();
872 // Install the built-in type for 'id', ignoring the current definition.
873 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
874 return;
875 case 5:
876 if (!TypeID->isStr("Class"))
877 break;
878 Context.ObjCClassRedefinitionType = New->getUnderlyingType();
879 // Install the built-in type for 'Class', ignoring the current definition.
880 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
881 return;
882 case 3:
883 if (!TypeID->isStr("SEL"))
884 break;
885 Context.ObjCSelRedefinitionType = New->getUnderlyingType();
886 // Install the built-in type for 'SEL', ignoring the current definition.
887 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
888 return;
889 case 8:
890 if (!TypeID->isStr("Protocol"))
891 break;
892 Context.setObjCProtoType(New->getUnderlyingType());
893 return;
895 // Fall through - the typedef name was not a builtin type.
898 // Verify the old decl was also a type.
899 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
900 if (!Old) {
901 Diag(New->getLocation(), diag::err_redefinition_different_kind)
902 << New->getDeclName();
904 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
905 if (OldD->getLocation().isValid())
906 Diag(OldD->getLocation(), diag::note_previous_definition);
908 return New->setInvalidDecl();
911 // If the old declaration is invalid, just give up here.
912 if (Old->isInvalidDecl())
913 return New->setInvalidDecl();
915 // Determine the "old" type we'll use for checking and diagnostics.
916 QualType OldType;
917 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
918 OldType = OldTypedef->getUnderlyingType();
919 else
920 OldType = Context.getTypeDeclType(Old);
922 // If the typedef types are not identical, reject them in all languages and
923 // with any extensions enabled.
925 if (OldType != New->getUnderlyingType() &&
926 Context.getCanonicalType(OldType) !=
927 Context.getCanonicalType(New->getUnderlyingType())) {
928 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
929 << New->getUnderlyingType() << OldType;
930 if (Old->getLocation().isValid())
931 Diag(Old->getLocation(), diag::note_previous_definition);
932 return New->setInvalidDecl();
935 // The types match. Link up the redeclaration chain if the old
936 // declaration was a typedef.
937 // FIXME: this is a potential source of wierdness if the type
938 // spellings don't match exactly.
939 if (isa<TypedefDecl>(Old))
940 New->setPreviousDeclaration(cast<TypedefDecl>(Old));
942 if (getLangOptions().Microsoft)
943 return;
945 if (getLangOptions().CPlusPlus) {
946 // C++ [dcl.typedef]p2:
947 // In a given non-class scope, a typedef specifier can be used to
948 // redefine the name of any type declared in that scope to refer
949 // to the type to which it already refers.
950 if (!isa<CXXRecordDecl>(CurContext))
951 return;
953 // C++0x [dcl.typedef]p4:
954 // In a given class scope, a typedef specifier can be used to redefine
955 // any class-name declared in that scope that is not also a typedef-name
956 // to refer to the type to which it already refers.
958 // This wording came in via DR424, which was a correction to the
959 // wording in DR56, which accidentally banned code like:
961 // struct S {
962 // typedef struct A { } A;
963 // };
965 // in the C++03 standard. We implement the C++0x semantics, which
966 // allow the above but disallow
968 // struct S {
969 // typedef int I;
970 // typedef int I;
971 // };
973 // since that was the intent of DR56.
974 if (!isa<TypedefDecl >(Old))
975 return;
977 Diag(New->getLocation(), diag::err_redefinition)
978 << New->getDeclName();
979 Diag(Old->getLocation(), diag::note_previous_definition);
980 return New->setInvalidDecl();
983 // If we have a redefinition of a typedef in C, emit a warning. This warning
984 // is normally mapped to an error, but can be controlled with
985 // -Wtypedef-redefinition. If either the original or the redefinition is
986 // in a system header, don't emit this for compatibility with GCC.
987 if (getDiagnostics().getSuppressSystemWarnings() &&
988 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
989 Context.getSourceManager().isInSystemHeader(New->getLocation())))
990 return;
992 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
993 << New->getDeclName();
994 Diag(Old->getLocation(), diag::note_previous_definition);
995 return;
998 /// DeclhasAttr - returns true if decl Declaration already has the target
999 /// attribute.
1000 static bool
1001 DeclHasAttr(const Decl *D, const Attr *A) {
1002 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1003 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1004 if ((*i)->getKind() == A->getKind()) {
1005 // FIXME: Don't hardcode this check
1006 if (OA && isa<OwnershipAttr>(*i))
1007 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
1008 return true;
1011 return false;
1014 /// MergeDeclAttributes - append attributes from the Old decl to the New one.
1015 static void MergeDeclAttributes(Decl *New, Decl *Old, ASTContext &C) {
1016 if (!Old->hasAttrs())
1017 return;
1018 // Ensure that any moving of objects within the allocated map is done before
1019 // we process them.
1020 if (!New->hasAttrs())
1021 New->setAttrs(AttrVec());
1022 for (specific_attr_iterator<InheritableAttr>
1023 i = Old->specific_attr_begin<InheritableAttr>(),
1024 e = Old->specific_attr_end<InheritableAttr>(); i != e; ++i) {
1025 if (!DeclHasAttr(New, *i)) {
1026 InheritableAttr *NewAttr = cast<InheritableAttr>((*i)->clone(C));
1027 NewAttr->setInherited(true);
1028 New->addAttr(NewAttr);
1033 namespace {
1035 /// Used in MergeFunctionDecl to keep track of function parameters in
1036 /// C.
1037 struct GNUCompatibleParamWarning {
1038 ParmVarDecl *OldParm;
1039 ParmVarDecl *NewParm;
1040 QualType PromotedType;
1045 /// getSpecialMember - get the special member enum for a method.
1046 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
1047 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
1048 if (Ctor->isCopyConstructor())
1049 return Sema::CXXCopyConstructor;
1051 return Sema::CXXConstructor;
1054 if (isa<CXXDestructorDecl>(MD))
1055 return Sema::CXXDestructor;
1057 assert(MD->isCopyAssignmentOperator() &&
1058 "Must have copy assignment operator");
1059 return Sema::CXXCopyAssignment;
1062 /// canRedefineFunction - checks if a function can be redefined. Currently,
1063 /// only extern inline functions can be redefined, and even then only in
1064 /// GNU89 mode.
1065 static bool canRedefineFunction(const FunctionDecl *FD,
1066 const LangOptions& LangOpts) {
1067 return (LangOpts.GNUMode && !LangOpts.C99 && !LangOpts.CPlusPlus &&
1068 FD->isInlineSpecified() &&
1069 FD->getStorageClass() == SC_Extern);
1072 /// MergeFunctionDecl - We just parsed a function 'New' from
1073 /// declarator D which has the same name and scope as a previous
1074 /// declaration 'Old'. Figure out how to resolve this situation,
1075 /// merging decls or emitting diagnostics as appropriate.
1077 /// In C++, New and Old must be declarations that are not
1078 /// overloaded. Use IsOverload to determine whether New and Old are
1079 /// overloaded, and to select the Old declaration that New should be
1080 /// merged with.
1082 /// Returns true if there was an error, false otherwise.
1083 bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
1084 // Verify the old decl was also a function.
1085 FunctionDecl *Old = 0;
1086 if (FunctionTemplateDecl *OldFunctionTemplate
1087 = dyn_cast<FunctionTemplateDecl>(OldD))
1088 Old = OldFunctionTemplate->getTemplatedDecl();
1089 else
1090 Old = dyn_cast<FunctionDecl>(OldD);
1091 if (!Old) {
1092 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
1093 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
1094 Diag(Shadow->getTargetDecl()->getLocation(),
1095 diag::note_using_decl_target);
1096 Diag(Shadow->getUsingDecl()->getLocation(),
1097 diag::note_using_decl) << 0;
1098 return true;
1101 Diag(New->getLocation(), diag::err_redefinition_different_kind)
1102 << New->getDeclName();
1103 Diag(OldD->getLocation(), diag::note_previous_definition);
1104 return true;
1107 // Determine whether the previous declaration was a definition,
1108 // implicit declaration, or a declaration.
1109 diag::kind PrevDiag;
1110 if (Old->isThisDeclarationADefinition())
1111 PrevDiag = diag::note_previous_definition;
1112 else if (Old->isImplicit())
1113 PrevDiag = diag::note_previous_implicit_declaration;
1114 else
1115 PrevDiag = diag::note_previous_declaration;
1117 QualType OldQType = Context.getCanonicalType(Old->getType());
1118 QualType NewQType = Context.getCanonicalType(New->getType());
1120 // Don't complain about this if we're in GNU89 mode and the old function
1121 // is an extern inline function.
1122 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
1123 New->getStorageClass() == SC_Static &&
1124 Old->getStorageClass() != SC_Static &&
1125 !canRedefineFunction(Old, getLangOptions())) {
1126 Diag(New->getLocation(), diag::err_static_non_static)
1127 << New;
1128 Diag(Old->getLocation(), PrevDiag);
1129 return true;
1132 // If a function is first declared with a calling convention, but is
1133 // later declared or defined without one, the second decl assumes the
1134 // calling convention of the first.
1136 // For the new decl, we have to look at the NON-canonical type to tell the
1137 // difference between a function that really doesn't have a calling
1138 // convention and one that is declared cdecl. That's because in
1139 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
1140 // because it is the default calling convention.
1142 // Note also that we DO NOT return at this point, because we still have
1143 // other tests to run.
1144 const FunctionType *OldType = cast<FunctionType>(OldQType);
1145 const FunctionType *NewType = New->getType()->getAs<FunctionType>();
1146 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
1147 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
1148 bool RequiresAdjustment = false;
1149 if (OldTypeInfo.getCC() != CC_Default &&
1150 NewTypeInfo.getCC() == CC_Default) {
1151 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
1152 RequiresAdjustment = true;
1153 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
1154 NewTypeInfo.getCC())) {
1155 // Calling conventions really aren't compatible, so complain.
1156 Diag(New->getLocation(), diag::err_cconv_change)
1157 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
1158 << (OldTypeInfo.getCC() == CC_Default)
1159 << (OldTypeInfo.getCC() == CC_Default ? "" :
1160 FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
1161 Diag(Old->getLocation(), diag::note_previous_declaration);
1162 return true;
1165 // FIXME: diagnose the other way around?
1166 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
1167 NewTypeInfo = NewTypeInfo.withNoReturn(true);
1168 RequiresAdjustment = true;
1171 // Merge regparm attribute.
1172 if (OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
1173 if (NewTypeInfo.getRegParm()) {
1174 Diag(New->getLocation(), diag::err_regparm_mismatch)
1175 << NewType->getRegParmType()
1176 << OldType->getRegParmType();
1177 Diag(Old->getLocation(), diag::note_previous_declaration);
1178 return true;
1181 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
1182 RequiresAdjustment = true;
1185 if (RequiresAdjustment) {
1186 NewType = Context.adjustFunctionType(NewType, NewTypeInfo);
1187 New->setType(QualType(NewType, 0));
1188 NewQType = Context.getCanonicalType(New->getType());
1191 if (getLangOptions().CPlusPlus) {
1192 // (C++98 13.1p2):
1193 // Certain function declarations cannot be overloaded:
1194 // -- Function declarations that differ only in the return type
1195 // cannot be overloaded.
1196 QualType OldReturnType = OldType->getResultType();
1197 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
1198 QualType ResQT;
1199 if (OldReturnType != NewReturnType) {
1200 if (NewReturnType->isObjCObjectPointerType()
1201 && OldReturnType->isObjCObjectPointerType())
1202 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
1203 if (ResQT.isNull()) {
1204 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
1205 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1206 return true;
1208 else
1209 NewQType = ResQT;
1212 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
1213 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
1214 if (OldMethod && NewMethod) {
1215 // Preserve triviality.
1216 NewMethod->setTrivial(OldMethod->isTrivial());
1218 bool isFriend = NewMethod->getFriendObjectKind();
1220 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord()) {
1221 // -- Member function declarations with the same name and the
1222 // same parameter types cannot be overloaded if any of them
1223 // is a static member function declaration.
1224 if (OldMethod->isStatic() || NewMethod->isStatic()) {
1225 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
1226 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1227 return true;
1230 // C++ [class.mem]p1:
1231 // [...] A member shall not be declared twice in the
1232 // member-specification, except that a nested class or member
1233 // class template can be declared and then later defined.
1234 unsigned NewDiag;
1235 if (isa<CXXConstructorDecl>(OldMethod))
1236 NewDiag = diag::err_constructor_redeclared;
1237 else if (isa<CXXDestructorDecl>(NewMethod))
1238 NewDiag = diag::err_destructor_redeclared;
1239 else if (isa<CXXConversionDecl>(NewMethod))
1240 NewDiag = diag::err_conv_function_redeclared;
1241 else
1242 NewDiag = diag::err_member_redeclared;
1244 Diag(New->getLocation(), NewDiag);
1245 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1247 // Complain if this is an explicit declaration of a special
1248 // member that was initially declared implicitly.
1250 // As an exception, it's okay to befriend such methods in order
1251 // to permit the implicit constructor/destructor/operator calls.
1252 } else if (OldMethod->isImplicit()) {
1253 if (isFriend) {
1254 NewMethod->setImplicit();
1255 } else {
1256 Diag(NewMethod->getLocation(),
1257 diag::err_definition_of_implicitly_declared_member)
1258 << New << getSpecialMember(OldMethod);
1259 return true;
1264 // (C++98 8.3.5p3):
1265 // All declarations for a function shall agree exactly in both the
1266 // return type and the parameter-type-list.
1267 // We also want to respect all the extended bits except noreturn.
1269 // noreturn should now match unless the old type info didn't have it.
1270 QualType OldQTypeForComparison = OldQType;
1271 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
1272 assert(OldQType == QualType(OldType, 0));
1273 const FunctionType *OldTypeForComparison
1274 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
1275 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
1276 assert(OldQTypeForComparison.isCanonical());
1279 if (OldQTypeForComparison == NewQType)
1280 return MergeCompatibleFunctionDecls(New, Old);
1282 // Fall through for conflicting redeclarations and redefinitions.
1285 // C: Function types need to be compatible, not identical. This handles
1286 // duplicate function decls like "void f(int); void f(enum X);" properly.
1287 if (!getLangOptions().CPlusPlus &&
1288 Context.typesAreCompatible(OldQType, NewQType)) {
1289 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
1290 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
1291 const FunctionProtoType *OldProto = 0;
1292 if (isa<FunctionNoProtoType>(NewFuncType) &&
1293 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
1294 // The old declaration provided a function prototype, but the
1295 // new declaration does not. Merge in the prototype.
1296 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
1297 llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
1298 OldProto->arg_type_end());
1299 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
1300 ParamTypes.data(), ParamTypes.size(),
1301 OldProto->getExtProtoInfo());
1302 New->setType(NewQType);
1303 New->setHasInheritedPrototype();
1305 // Synthesize a parameter for each argument type.
1306 llvm::SmallVector<ParmVarDecl*, 16> Params;
1307 for (FunctionProtoType::arg_type_iterator
1308 ParamType = OldProto->arg_type_begin(),
1309 ParamEnd = OldProto->arg_type_end();
1310 ParamType != ParamEnd; ++ParamType) {
1311 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
1312 SourceLocation(), 0,
1313 *ParamType, /*TInfo=*/0,
1314 SC_None, SC_None,
1316 Param->setImplicit();
1317 Params.push_back(Param);
1320 New->setParams(Params.data(), Params.size());
1323 return MergeCompatibleFunctionDecls(New, Old);
1326 // GNU C permits a K&R definition to follow a prototype declaration
1327 // if the declared types of the parameters in the K&R definition
1328 // match the types in the prototype declaration, even when the
1329 // promoted types of the parameters from the K&R definition differ
1330 // from the types in the prototype. GCC then keeps the types from
1331 // the prototype.
1333 // If a variadic prototype is followed by a non-variadic K&R definition,
1334 // the K&R definition becomes variadic. This is sort of an edge case, but
1335 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
1336 // C99 6.9.1p8.
1337 if (!getLangOptions().CPlusPlus &&
1338 Old->hasPrototype() && !New->hasPrototype() &&
1339 New->getType()->getAs<FunctionProtoType>() &&
1340 Old->getNumParams() == New->getNumParams()) {
1341 llvm::SmallVector<QualType, 16> ArgTypes;
1342 llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
1343 const FunctionProtoType *OldProto
1344 = Old->getType()->getAs<FunctionProtoType>();
1345 const FunctionProtoType *NewProto
1346 = New->getType()->getAs<FunctionProtoType>();
1348 // Determine whether this is the GNU C extension.
1349 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
1350 NewProto->getResultType());
1351 bool LooseCompatible = !MergedReturn.isNull();
1352 for (unsigned Idx = 0, End = Old->getNumParams();
1353 LooseCompatible && Idx != End; ++Idx) {
1354 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
1355 ParmVarDecl *NewParm = New->getParamDecl(Idx);
1356 if (Context.typesAreCompatible(OldParm->getType(),
1357 NewProto->getArgType(Idx))) {
1358 ArgTypes.push_back(NewParm->getType());
1359 } else if (Context.typesAreCompatible(OldParm->getType(),
1360 NewParm->getType(),
1361 /*CompareUnqualified=*/true)) {
1362 GNUCompatibleParamWarning Warn
1363 = { OldParm, NewParm, NewProto->getArgType(Idx) };
1364 Warnings.push_back(Warn);
1365 ArgTypes.push_back(NewParm->getType());
1366 } else
1367 LooseCompatible = false;
1370 if (LooseCompatible) {
1371 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
1372 Diag(Warnings[Warn].NewParm->getLocation(),
1373 diag::ext_param_promoted_not_compatible_with_prototype)
1374 << Warnings[Warn].PromotedType
1375 << Warnings[Warn].OldParm->getType();
1376 if (Warnings[Warn].OldParm->getLocation().isValid())
1377 Diag(Warnings[Warn].OldParm->getLocation(),
1378 diag::note_previous_declaration);
1381 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
1382 ArgTypes.size(),
1383 OldProto->getExtProtoInfo()));
1384 return MergeCompatibleFunctionDecls(New, Old);
1387 // Fall through to diagnose conflicting types.
1390 // A function that has already been declared has been redeclared or defined
1391 // with a different type- show appropriate diagnostic
1392 if (unsigned BuiltinID = Old->getBuiltinID()) {
1393 // The user has declared a builtin function with an incompatible
1394 // signature.
1395 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
1396 // The function the user is redeclaring is a library-defined
1397 // function like 'malloc' or 'printf'. Warn about the
1398 // redeclaration, then pretend that we don't know about this
1399 // library built-in.
1400 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
1401 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
1402 << Old << Old->getType();
1403 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
1404 Old->setInvalidDecl();
1405 return false;
1408 PrevDiag = diag::note_previous_builtin_declaration;
1411 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
1412 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1413 return true;
1416 /// \brief Completes the merge of two function declarations that are
1417 /// known to be compatible.
1419 /// This routine handles the merging of attributes and other
1420 /// properties of function declarations form the old declaration to
1421 /// the new declaration, once we know that New is in fact a
1422 /// redeclaration of Old.
1424 /// \returns false
1425 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
1426 // Merge the attributes
1427 MergeDeclAttributes(New, Old, Context);
1429 // Merge the storage class.
1430 if (Old->getStorageClass() != SC_Extern &&
1431 Old->getStorageClass() != SC_None)
1432 New->setStorageClass(Old->getStorageClass());
1434 // Merge "pure" flag.
1435 if (Old->isPure())
1436 New->setPure();
1438 // Merge the "deleted" flag.
1439 if (Old->isDeleted())
1440 New->setDeleted();
1442 if (getLangOptions().CPlusPlus)
1443 return MergeCXXFunctionDecl(New, Old);
1445 return false;
1448 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
1449 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
1450 /// situation, merging decls or emitting diagnostics as appropriate.
1452 /// Tentative definition rules (C99 6.9.2p2) are checked by
1453 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
1454 /// definitions here, since the initializer hasn't been attached.
1456 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
1457 // If the new decl is already invalid, don't do any other checking.
1458 if (New->isInvalidDecl())
1459 return;
1461 // Verify the old decl was also a variable.
1462 VarDecl *Old = 0;
1463 if (!Previous.isSingleResult() ||
1464 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
1465 Diag(New->getLocation(), diag::err_redefinition_different_kind)
1466 << New->getDeclName();
1467 Diag(Previous.getRepresentativeDecl()->getLocation(),
1468 diag::note_previous_definition);
1469 return New->setInvalidDecl();
1472 // C++ [class.mem]p1:
1473 // A member shall not be declared twice in the member-specification [...]
1475 // Here, we need only consider static data members.
1476 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
1477 Diag(New->getLocation(), diag::err_duplicate_member)
1478 << New->getIdentifier();
1479 Diag(Old->getLocation(), diag::note_previous_declaration);
1480 New->setInvalidDecl();
1483 MergeDeclAttributes(New, Old, Context);
1485 // Merge the types
1486 QualType MergedT;
1487 if (getLangOptions().CPlusPlus) {
1488 if (Context.hasSameType(New->getType(), Old->getType()))
1489 MergedT = New->getType();
1490 // C++ [basic.link]p10:
1491 // [...] the types specified by all declarations referring to a given
1492 // object or function shall be identical, except that declarations for an
1493 // array object can specify array types that differ by the presence or
1494 // absence of a major array bound (8.3.4).
1495 else if (Old->getType()->isIncompleteArrayType() &&
1496 New->getType()->isArrayType()) {
1497 CanQual<ArrayType> OldArray
1498 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1499 CanQual<ArrayType> NewArray
1500 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1501 if (OldArray->getElementType() == NewArray->getElementType())
1502 MergedT = New->getType();
1503 } else if (Old->getType()->isArrayType() &&
1504 New->getType()->isIncompleteArrayType()) {
1505 CanQual<ArrayType> OldArray
1506 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1507 CanQual<ArrayType> NewArray
1508 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1509 if (OldArray->getElementType() == NewArray->getElementType())
1510 MergedT = Old->getType();
1511 } else if (New->getType()->isObjCObjectPointerType()
1512 && Old->getType()->isObjCObjectPointerType()) {
1513 MergedT = Context.mergeObjCGCQualifiers(New->getType(), Old->getType());
1515 } else {
1516 MergedT = Context.mergeTypes(New->getType(), Old->getType());
1518 if (MergedT.isNull()) {
1519 Diag(New->getLocation(), diag::err_redefinition_different_type)
1520 << New->getDeclName();
1521 Diag(Old->getLocation(), diag::note_previous_definition);
1522 return New->setInvalidDecl();
1524 New->setType(MergedT);
1526 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
1527 if (New->getStorageClass() == SC_Static &&
1528 (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) {
1529 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
1530 Diag(Old->getLocation(), diag::note_previous_definition);
1531 return New->setInvalidDecl();
1533 // C99 6.2.2p4:
1534 // For an identifier declared with the storage-class specifier
1535 // extern in a scope in which a prior declaration of that
1536 // identifier is visible,23) if the prior declaration specifies
1537 // internal or external linkage, the linkage of the identifier at
1538 // the later declaration is the same as the linkage specified at
1539 // the prior declaration. If no prior declaration is visible, or
1540 // if the prior declaration specifies no linkage, then the
1541 // identifier has external linkage.
1542 if (New->hasExternalStorage() && Old->hasLinkage())
1543 /* Okay */;
1544 else if (New->getStorageClass() != SC_Static &&
1545 Old->getStorageClass() == SC_Static) {
1546 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
1547 Diag(Old->getLocation(), diag::note_previous_definition);
1548 return New->setInvalidDecl();
1551 // Check if extern is followed by non-extern and vice-versa.
1552 if (New->hasExternalStorage() &&
1553 !Old->hasLinkage() && Old->isLocalVarDecl()) {
1554 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
1555 Diag(Old->getLocation(), diag::note_previous_definition);
1556 return New->setInvalidDecl();
1558 if (Old->hasExternalStorage() &&
1559 !New->hasLinkage() && New->isLocalVarDecl()) {
1560 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
1561 Diag(Old->getLocation(), diag::note_previous_definition);
1562 return New->setInvalidDecl();
1565 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
1567 // FIXME: The test for external storage here seems wrong? We still
1568 // need to check for mismatches.
1569 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
1570 // Don't complain about out-of-line definitions of static members.
1571 !(Old->getLexicalDeclContext()->isRecord() &&
1572 !New->getLexicalDeclContext()->isRecord())) {
1573 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
1574 Diag(Old->getLocation(), diag::note_previous_definition);
1575 return New->setInvalidDecl();
1578 if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
1579 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
1580 Diag(Old->getLocation(), diag::note_previous_definition);
1581 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
1582 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
1583 Diag(Old->getLocation(), diag::note_previous_definition);
1586 // C++ doesn't have tentative definitions, so go right ahead and check here.
1587 const VarDecl *Def;
1588 if (getLangOptions().CPlusPlus &&
1589 New->isThisDeclarationADefinition() == VarDecl::Definition &&
1590 (Def = Old->getDefinition())) {
1591 Diag(New->getLocation(), diag::err_redefinition)
1592 << New->getDeclName();
1593 Diag(Def->getLocation(), diag::note_previous_definition);
1594 New->setInvalidDecl();
1595 return;
1597 // c99 6.2.2 P4.
1598 // For an identifier declared with the storage-class specifier extern in a
1599 // scope in which a prior declaration of that identifier is visible, if
1600 // the prior declaration specifies internal or external linkage, the linkage
1601 // of the identifier at the later declaration is the same as the linkage
1602 // specified at the prior declaration.
1603 // FIXME. revisit this code.
1604 if (New->hasExternalStorage() &&
1605 Old->getLinkage() == InternalLinkage &&
1606 New->getDeclContext() == Old->getDeclContext())
1607 New->setStorageClass(Old->getStorageClass());
1609 // Keep a chain of previous declarations.
1610 New->setPreviousDeclaration(Old);
1612 // Inherit access appropriately.
1613 New->setAccess(Old->getAccess());
1616 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
1617 /// no declarator (e.g. "struct foo;") is parsed.
1618 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1619 DeclSpec &DS) {
1620 // FIXME: Error on inline/virtual/explicit
1621 // FIXME: Warn on useless __thread
1622 // FIXME: Warn on useless const/volatile
1623 // FIXME: Warn on useless static/extern/typedef/private_extern/mutable
1624 // FIXME: Warn on useless attributes
1625 Decl *TagD = 0;
1626 TagDecl *Tag = 0;
1627 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
1628 DS.getTypeSpecType() == DeclSpec::TST_struct ||
1629 DS.getTypeSpecType() == DeclSpec::TST_union ||
1630 DS.getTypeSpecType() == DeclSpec::TST_enum) {
1631 TagD = DS.getRepAsDecl();
1633 if (!TagD) // We probably had an error
1634 return 0;
1636 // Note that the above type specs guarantee that the
1637 // type rep is a Decl, whereas in many of the others
1638 // it's a Type.
1639 Tag = dyn_cast<TagDecl>(TagD);
1642 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1643 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
1644 // or incomplete types shall not be restrict-qualified."
1645 if (TypeQuals & DeclSpec::TQ_restrict)
1646 Diag(DS.getRestrictSpecLoc(),
1647 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
1648 << DS.getSourceRange();
1651 if (DS.isFriendSpecified()) {
1652 // If we're dealing with a decl but not a TagDecl, assume that
1653 // whatever routines created it handled the friendship aspect.
1654 if (TagD && !Tag)
1655 return 0;
1656 return ActOnFriendTypeDecl(S, DS, MultiTemplateParamsArg(*this, 0, 0));
1659 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
1660 ProcessDeclAttributeList(S, Record, DS.getAttributes().getList());
1662 if (!Record->getDeclName() && Record->isDefinition() &&
1663 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
1664 if (getLangOptions().CPlusPlus ||
1665 Record->getDeclContext()->isRecord())
1666 return BuildAnonymousStructOrUnion(S, DS, AS, Record);
1668 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
1669 << DS.getSourceRange();
1673 // Check for Microsoft C extension: anonymous struct.
1674 if (getLangOptions().Microsoft && !getLangOptions().CPlusPlus &&
1675 CurContext->isRecord() &&
1676 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
1677 // Handle 2 kinds of anonymous struct:
1678 // struct STRUCT;
1679 // and
1680 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
1681 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
1682 if ((Record && Record->getDeclName() && !Record->isDefinition()) ||
1683 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
1684 DS.getRepAsType().get()->isStructureType())) {
1685 Diag(DS.getSourceRange().getBegin(), diag::ext_ms_anonymous_struct)
1686 << DS.getSourceRange();
1687 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
1691 if (getLangOptions().CPlusPlus &&
1692 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
1693 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
1694 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
1695 !Enum->getIdentifier() && !Enum->isInvalidDecl())
1696 Diag(Enum->getLocation(), diag::ext_no_declarators)
1697 << DS.getSourceRange();
1699 if (!DS.isMissingDeclaratorOk() &&
1700 DS.getTypeSpecType() != DeclSpec::TST_error) {
1701 // Warn about typedefs of enums without names, since this is an
1702 // extension in both Microsoft and GNU.
1703 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
1704 Tag && isa<EnumDecl>(Tag)) {
1705 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
1706 << DS.getSourceRange();
1707 return Tag;
1710 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
1711 << DS.getSourceRange();
1714 return TagD;
1717 /// ActOnVlaStmt - This rouine if finds a vla expression in a decl spec.
1718 /// builds a statement for it and returns it so it is evaluated.
1719 StmtResult Sema::ActOnVlaStmt(const DeclSpec &DS) {
1720 StmtResult R;
1721 if (DS.getTypeSpecType() == DeclSpec::TST_typeofExpr) {
1722 Expr *Exp = DS.getRepAsExpr();
1723 QualType Ty = Exp->getType();
1724 if (Ty->isPointerType()) {
1726 Ty = Ty->getAs<PointerType>()->getPointeeType();
1727 while (Ty->isPointerType());
1729 if (Ty->isVariableArrayType()) {
1730 R = ActOnExprStmt(MakeFullExpr(Exp));
1733 return R;
1736 /// We are trying to inject an anonymous member into the given scope;
1737 /// check if there's an existing declaration that can't be overloaded.
1739 /// \return true if this is a forbidden redeclaration
1740 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
1741 Scope *S,
1742 DeclContext *Owner,
1743 DeclarationName Name,
1744 SourceLocation NameLoc,
1745 unsigned diagnostic) {
1746 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
1747 Sema::ForRedeclaration);
1748 if (!SemaRef.LookupName(R, S)) return false;
1750 if (R.getAsSingle<TagDecl>())
1751 return false;
1753 // Pick a representative declaration.
1754 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
1755 assert(PrevDecl && "Expected a non-null Decl");
1757 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
1758 return false;
1760 SemaRef.Diag(NameLoc, diagnostic) << Name;
1761 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
1763 return true;
1766 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
1767 /// anonymous struct or union AnonRecord into the owning context Owner
1768 /// and scope S. This routine will be invoked just after we realize
1769 /// that an unnamed union or struct is actually an anonymous union or
1770 /// struct, e.g.,
1772 /// @code
1773 /// union {
1774 /// int i;
1775 /// float f;
1776 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
1777 /// // f into the surrounding scope.x
1778 /// @endcode
1780 /// This routine is recursive, injecting the names of nested anonymous
1781 /// structs/unions into the owning context and scope as well.
1782 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
1783 DeclContext *Owner,
1784 RecordDecl *AnonRecord,
1785 AccessSpecifier AS,
1786 llvm::SmallVector<NamedDecl*, 2> &Chaining,
1787 bool MSAnonStruct) {
1788 unsigned diagKind
1789 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
1790 : diag::err_anonymous_struct_member_redecl;
1792 bool Invalid = false;
1794 // Look every FieldDecl and IndirectFieldDecl with a name.
1795 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
1796 DEnd = AnonRecord->decls_end();
1797 D != DEnd; ++D) {
1798 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
1799 cast<NamedDecl>(*D)->getDeclName()) {
1800 ValueDecl *VD = cast<ValueDecl>(*D);
1801 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
1802 VD->getLocation(), diagKind)) {
1803 // C++ [class.union]p2:
1804 // The names of the members of an anonymous union shall be
1805 // distinct from the names of any other entity in the
1806 // scope in which the anonymous union is declared.
1807 Invalid = true;
1808 } else {
1809 // C++ [class.union]p2:
1810 // For the purpose of name lookup, after the anonymous union
1811 // definition, the members of the anonymous union are
1812 // considered to have been defined in the scope in which the
1813 // anonymous union is declared.
1814 unsigned OldChainingSize = Chaining.size();
1815 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
1816 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
1817 PE = IF->chain_end(); PI != PE; ++PI)
1818 Chaining.push_back(*PI);
1819 else
1820 Chaining.push_back(VD);
1822 assert(Chaining.size() >= 2);
1823 NamedDecl **NamedChain =
1824 new (SemaRef.Context)NamedDecl*[Chaining.size()];
1825 for (unsigned i = 0; i < Chaining.size(); i++)
1826 NamedChain[i] = Chaining[i];
1828 IndirectFieldDecl* IndirectField =
1829 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
1830 VD->getIdentifier(), VD->getType(),
1831 NamedChain, Chaining.size());
1833 IndirectField->setAccess(AS);
1834 IndirectField->setImplicit();
1835 SemaRef.PushOnScopeChains(IndirectField, S);
1837 // That includes picking up the appropriate access specifier.
1838 if (AS != AS_none) IndirectField->setAccess(AS);
1840 Chaining.resize(OldChainingSize);
1845 return Invalid;
1848 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
1849 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
1850 /// illegal input values are mapped to SC_None.
1851 static StorageClass
1852 StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
1853 switch (StorageClassSpec) {
1854 case DeclSpec::SCS_unspecified: return SC_None;
1855 case DeclSpec::SCS_extern: return SC_Extern;
1856 case DeclSpec::SCS_static: return SC_Static;
1857 case DeclSpec::SCS_auto: return SC_Auto;
1858 case DeclSpec::SCS_register: return SC_Register;
1859 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
1860 // Illegal SCSs map to None: error reporting is up to the caller.
1861 case DeclSpec::SCS_mutable: // Fall through.
1862 case DeclSpec::SCS_typedef: return SC_None;
1864 llvm_unreachable("unknown storage class specifier");
1867 /// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
1868 /// a StorageClass. Any error reporting is up to the caller:
1869 /// illegal input values are mapped to SC_None.
1870 static StorageClass
1871 StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
1872 switch (StorageClassSpec) {
1873 case DeclSpec::SCS_unspecified: return SC_None;
1874 case DeclSpec::SCS_extern: return SC_Extern;
1875 case DeclSpec::SCS_static: return SC_Static;
1876 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
1877 // Illegal SCSs map to None: error reporting is up to the caller.
1878 case DeclSpec::SCS_auto: // Fall through.
1879 case DeclSpec::SCS_mutable: // Fall through.
1880 case DeclSpec::SCS_register: // Fall through.
1881 case DeclSpec::SCS_typedef: return SC_None;
1883 llvm_unreachable("unknown storage class specifier");
1886 /// BuildAnonymousStructOrUnion - Handle the declaration of an
1887 /// anonymous structure or union. Anonymous unions are a C++ feature
1888 /// (C++ [class.union]) and a GNU C extension; anonymous structures
1889 /// are a GNU C and GNU C++ extension.
1890 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1891 AccessSpecifier AS,
1892 RecordDecl *Record) {
1893 DeclContext *Owner = Record->getDeclContext();
1895 // Diagnose whether this anonymous struct/union is an extension.
1896 if (Record->isUnion() && !getLangOptions().CPlusPlus)
1897 Diag(Record->getLocation(), diag::ext_anonymous_union);
1898 else if (!Record->isUnion())
1899 Diag(Record->getLocation(), diag::ext_anonymous_struct);
1901 // C and C++ require different kinds of checks for anonymous
1902 // structs/unions.
1903 bool Invalid = false;
1904 if (getLangOptions().CPlusPlus) {
1905 const char* PrevSpec = 0;
1906 unsigned DiagID;
1907 // C++ [class.union]p3:
1908 // Anonymous unions declared in a named namespace or in the
1909 // global namespace shall be declared static.
1910 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
1911 (isa<TranslationUnitDecl>(Owner) ||
1912 (isa<NamespaceDecl>(Owner) &&
1913 cast<NamespaceDecl>(Owner)->getDeclName()))) {
1914 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
1915 Invalid = true;
1917 // Recover by adding 'static'.
1918 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(),
1919 PrevSpec, DiagID);
1921 // C++ [class.union]p3:
1922 // A storage class is not allowed in a declaration of an
1923 // anonymous union in a class scope.
1924 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1925 isa<RecordDecl>(Owner)) {
1926 Diag(DS.getStorageClassSpecLoc(),
1927 diag::err_anonymous_union_with_storage_spec);
1928 Invalid = true;
1930 // Recover by removing the storage specifier.
1931 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
1932 PrevSpec, DiagID);
1935 // C++ [class.union]p2:
1936 // The member-specification of an anonymous union shall only
1937 // define non-static data members. [Note: nested types and
1938 // functions cannot be declared within an anonymous union. ]
1939 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
1940 MemEnd = Record->decls_end();
1941 Mem != MemEnd; ++Mem) {
1942 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
1943 // C++ [class.union]p3:
1944 // An anonymous union shall not have private or protected
1945 // members (clause 11).
1946 assert(FD->getAccess() != AS_none);
1947 if (FD->getAccess() != AS_public) {
1948 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
1949 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
1950 Invalid = true;
1953 if (CheckNontrivialField(FD))
1954 Invalid = true;
1955 } else if ((*Mem)->isImplicit()) {
1956 // Any implicit members are fine.
1957 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
1958 // This is a type that showed up in an
1959 // elaborated-type-specifier inside the anonymous struct or
1960 // union, but which actually declares a type outside of the
1961 // anonymous struct or union. It's okay.
1962 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
1963 if (!MemRecord->isAnonymousStructOrUnion() &&
1964 MemRecord->getDeclName()) {
1965 // Visual C++ allows type definition in anonymous struct or union.
1966 if (getLangOptions().Microsoft)
1967 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
1968 << (int)Record->isUnion();
1969 else {
1970 // This is a nested type declaration.
1971 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
1972 << (int)Record->isUnion();
1973 Invalid = true;
1976 } else if (isa<AccessSpecDecl>(*Mem)) {
1977 // Any access specifier is fine.
1978 } else {
1979 // We have something that isn't a non-static data
1980 // member. Complain about it.
1981 unsigned DK = diag::err_anonymous_record_bad_member;
1982 if (isa<TypeDecl>(*Mem))
1983 DK = diag::err_anonymous_record_with_type;
1984 else if (isa<FunctionDecl>(*Mem))
1985 DK = diag::err_anonymous_record_with_function;
1986 else if (isa<VarDecl>(*Mem))
1987 DK = diag::err_anonymous_record_with_static;
1989 // Visual C++ allows type definition in anonymous struct or union.
1990 if (getLangOptions().Microsoft &&
1991 DK == diag::err_anonymous_record_with_type)
1992 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
1993 << (int)Record->isUnion();
1994 else {
1995 Diag((*Mem)->getLocation(), DK)
1996 << (int)Record->isUnion();
1997 Invalid = true;
2003 if (!Record->isUnion() && !Owner->isRecord()) {
2004 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
2005 << (int)getLangOptions().CPlusPlus;
2006 Invalid = true;
2009 // Mock up a declarator.
2010 Declarator Dc(DS, Declarator::TypeNameContext);
2011 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
2012 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
2014 // Create a declaration for this anonymous struct/union.
2015 NamedDecl *Anon = 0;
2016 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
2017 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
2018 /*IdentifierInfo=*/0,
2019 Context.getTypeDeclType(Record),
2020 TInfo,
2021 /*BitWidth=*/0, /*Mutable=*/false);
2022 Anon->setAccess(AS);
2023 if (getLangOptions().CPlusPlus)
2024 FieldCollector->Add(cast<FieldDecl>(Anon));
2025 } else {
2026 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
2027 assert(SCSpec != DeclSpec::SCS_typedef &&
2028 "Parser allowed 'typedef' as storage class VarDecl.");
2029 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
2030 if (SCSpec == DeclSpec::SCS_mutable) {
2031 // mutable can only appear on non-static class members, so it's always
2032 // an error here
2033 Diag(Record->getLocation(), diag::err_mutable_nonmember);
2034 Invalid = true;
2035 SC = SC_None;
2037 SCSpec = DS.getStorageClassSpecAsWritten();
2038 VarDecl::StorageClass SCAsWritten
2039 = StorageClassSpecToVarDeclStorageClass(SCSpec);
2041 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
2042 /*IdentifierInfo=*/0,
2043 Context.getTypeDeclType(Record),
2044 TInfo, SC, SCAsWritten);
2046 Anon->setImplicit();
2048 // Add the anonymous struct/union object to the current
2049 // context. We'll be referencing this object when we refer to one of
2050 // its members.
2051 Owner->addDecl(Anon);
2053 // Inject the members of the anonymous struct/union into the owning
2054 // context and into the identifier resolver chain for name lookup
2055 // purposes.
2056 llvm::SmallVector<NamedDecl*, 2> Chain;
2057 Chain.push_back(Anon);
2059 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
2060 Chain, false))
2061 Invalid = true;
2063 // Mark this as an anonymous struct/union type. Note that we do not
2064 // do this until after we have already checked and injected the
2065 // members of this anonymous struct/union type, because otherwise
2066 // the members could be injected twice: once by DeclContext when it
2067 // builds its lookup table, and once by
2068 // InjectAnonymousStructOrUnionMembers.
2069 Record->setAnonymousStructOrUnion(true);
2071 if (Invalid)
2072 Anon->setInvalidDecl();
2074 return Anon;
2077 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
2078 /// Microsoft C anonymous structure.
2079 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
2080 /// Example:
2082 /// struct A { int a; };
2083 /// struct B { struct A; int b; };
2085 /// void foo() {
2086 /// B var;
2087 /// var.a = 3;
2088 /// }
2090 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2091 RecordDecl *Record) {
2093 // If there is no Record, get the record via the typedef.
2094 if (!Record)
2095 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
2097 // Mock up a declarator.
2098 Declarator Dc(DS, Declarator::TypeNameContext);
2099 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
2100 assert(TInfo && "couldn't build declarator info for anonymous struct");
2102 // Create a declaration for this anonymous struct.
2103 NamedDecl* Anon = FieldDecl::Create(Context,
2104 cast<RecordDecl>(CurContext),
2105 DS.getSourceRange().getBegin(),
2106 /*IdentifierInfo=*/0,
2107 Context.getTypeDeclType(Record),
2108 TInfo,
2109 /*BitWidth=*/0, /*Mutable=*/false);
2110 Anon->setImplicit();
2112 // Add the anonymous struct object to the current context.
2113 CurContext->addDecl(Anon);
2115 // Inject the members of the anonymous struct into the current
2116 // context and into the identifier resolver chain for name lookup
2117 // purposes.
2118 llvm::SmallVector<NamedDecl*, 2> Chain;
2119 Chain.push_back(Anon);
2121 if (InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
2122 Record->getDefinition(),
2123 AS_none, Chain, true))
2124 Anon->setInvalidDecl();
2126 return Anon;
2129 /// GetNameForDeclarator - Determine the full declaration name for the
2130 /// given Declarator.
2131 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
2132 return GetNameFromUnqualifiedId(D.getName());
2135 /// \brief Retrieves the declaration name from a parsed unqualified-id.
2136 DeclarationNameInfo
2137 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
2138 DeclarationNameInfo NameInfo;
2139 NameInfo.setLoc(Name.StartLocation);
2141 switch (Name.getKind()) {
2143 case UnqualifiedId::IK_Identifier:
2144 NameInfo.setName(Name.Identifier);
2145 NameInfo.setLoc(Name.StartLocation);
2146 return NameInfo;
2148 case UnqualifiedId::IK_OperatorFunctionId:
2149 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
2150 Name.OperatorFunctionId.Operator));
2151 NameInfo.setLoc(Name.StartLocation);
2152 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
2153 = Name.OperatorFunctionId.SymbolLocations[0];
2154 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
2155 = Name.EndLocation.getRawEncoding();
2156 return NameInfo;
2158 case UnqualifiedId::IK_LiteralOperatorId:
2159 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
2160 Name.Identifier));
2161 NameInfo.setLoc(Name.StartLocation);
2162 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
2163 return NameInfo;
2165 case UnqualifiedId::IK_ConversionFunctionId: {
2166 TypeSourceInfo *TInfo;
2167 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
2168 if (Ty.isNull())
2169 return DeclarationNameInfo();
2170 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
2171 Context.getCanonicalType(Ty)));
2172 NameInfo.setLoc(Name.StartLocation);
2173 NameInfo.setNamedTypeInfo(TInfo);
2174 return NameInfo;
2177 case UnqualifiedId::IK_ConstructorName: {
2178 TypeSourceInfo *TInfo;
2179 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
2180 if (Ty.isNull())
2181 return DeclarationNameInfo();
2182 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
2183 Context.getCanonicalType(Ty)));
2184 NameInfo.setLoc(Name.StartLocation);
2185 NameInfo.setNamedTypeInfo(TInfo);
2186 return NameInfo;
2189 case UnqualifiedId::IK_ConstructorTemplateId: {
2190 // In well-formed code, we can only have a constructor
2191 // template-id that refers to the current context, so go there
2192 // to find the actual type being constructed.
2193 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
2194 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
2195 return DeclarationNameInfo();
2197 // Determine the type of the class being constructed.
2198 QualType CurClassType = Context.getTypeDeclType(CurClass);
2200 // FIXME: Check two things: that the template-id names the same type as
2201 // CurClassType, and that the template-id does not occur when the name
2202 // was qualified.
2204 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
2205 Context.getCanonicalType(CurClassType)));
2206 NameInfo.setLoc(Name.StartLocation);
2207 // FIXME: should we retrieve TypeSourceInfo?
2208 NameInfo.setNamedTypeInfo(0);
2209 return NameInfo;
2212 case UnqualifiedId::IK_DestructorName: {
2213 TypeSourceInfo *TInfo;
2214 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
2215 if (Ty.isNull())
2216 return DeclarationNameInfo();
2217 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
2218 Context.getCanonicalType(Ty)));
2219 NameInfo.setLoc(Name.StartLocation);
2220 NameInfo.setNamedTypeInfo(TInfo);
2221 return NameInfo;
2224 case UnqualifiedId::IK_TemplateId: {
2225 TemplateName TName = Name.TemplateId->Template.get();
2226 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
2227 return Context.getNameForTemplate(TName, TNameLoc);
2230 } // switch (Name.getKind())
2232 assert(false && "Unknown name kind");
2233 return DeclarationNameInfo();
2236 /// isNearlyMatchingFunction - Determine whether the C++ functions
2237 /// Declaration and Definition are "nearly" matching. This heuristic
2238 /// is used to improve diagnostics in the case where an out-of-line
2239 /// function definition doesn't match any declaration within
2240 /// the class or namespace.
2241 static bool isNearlyMatchingFunction(ASTContext &Context,
2242 FunctionDecl *Declaration,
2243 FunctionDecl *Definition) {
2244 if (Declaration->param_size() != Definition->param_size())
2245 return false;
2246 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
2247 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
2248 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
2250 if (!Context.hasSameUnqualifiedType(DeclParamTy.getNonReferenceType(),
2251 DefParamTy.getNonReferenceType()))
2252 return false;
2255 return true;
2258 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
2259 /// declarator needs to be rebuilt in the current instantiation.
2260 /// Any bits of declarator which appear before the name are valid for
2261 /// consideration here. That's specifically the type in the decl spec
2262 /// and the base type in any member-pointer chunks.
2263 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
2264 DeclarationName Name) {
2265 // The types we specifically need to rebuild are:
2266 // - typenames, typeofs, and decltypes
2267 // - types which will become injected class names
2268 // Of course, we also need to rebuild any type referencing such a
2269 // type. It's safest to just say "dependent", but we call out a
2270 // few cases here.
2272 DeclSpec &DS = D.getMutableDeclSpec();
2273 switch (DS.getTypeSpecType()) {
2274 case DeclSpec::TST_typename:
2275 case DeclSpec::TST_typeofType:
2276 case DeclSpec::TST_decltype: {
2277 // Grab the type from the parser.
2278 TypeSourceInfo *TSI = 0;
2279 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
2280 if (T.isNull() || !T->isDependentType()) break;
2282 // Make sure there's a type source info. This isn't really much
2283 // of a waste; most dependent types should have type source info
2284 // attached already.
2285 if (!TSI)
2286 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
2288 // Rebuild the type in the current instantiation.
2289 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
2290 if (!TSI) return true;
2292 // Store the new type back in the decl spec.
2293 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
2294 DS.UpdateTypeRep(LocType);
2295 break;
2298 case DeclSpec::TST_typeofExpr: {
2299 Expr *E = DS.getRepAsExpr();
2300 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
2301 if (Result.isInvalid()) return true;
2302 DS.UpdateExprRep(Result.get());
2303 break;
2306 default:
2307 // Nothing to do for these decl specs.
2308 break;
2311 // It doesn't matter what order we do this in.
2312 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
2313 DeclaratorChunk &Chunk = D.getTypeObject(I);
2315 // The only type information in the declarator which can come
2316 // before the declaration name is the base type of a member
2317 // pointer.
2318 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
2319 continue;
2321 // Rebuild the scope specifier in-place.
2322 CXXScopeSpec &SS = Chunk.Mem.Scope();
2323 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
2324 return true;
2327 return false;
2330 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
2331 return HandleDeclarator(S, D, MultiTemplateParamsArg(*this), false);
2334 Decl *Sema::HandleDeclarator(Scope *S, Declarator &D,
2335 MultiTemplateParamsArg TemplateParamLists,
2336 bool IsFunctionDefinition) {
2337 // TODO: consider using NameInfo for diagnostic.
2338 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2339 DeclarationName Name = NameInfo.getName();
2341 // All of these full declarators require an identifier. If it doesn't have
2342 // one, the ParsedFreeStandingDeclSpec action should be used.
2343 if (!Name) {
2344 if (!D.isInvalidType()) // Reject this if we think it is valid.
2345 Diag(D.getDeclSpec().getSourceRange().getBegin(),
2346 diag::err_declarator_need_ident)
2347 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
2348 return 0;
2349 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
2350 return 0;
2352 // The scope passed in may not be a decl scope. Zip up the scope tree until
2353 // we find one that is.
2354 while ((S->getFlags() & Scope::DeclScope) == 0 ||
2355 (S->getFlags() & Scope::TemplateParamScope) != 0)
2356 S = S->getParent();
2358 DeclContext *DC = CurContext;
2359 if (D.getCXXScopeSpec().isInvalid())
2360 D.setInvalidType();
2361 else if (D.getCXXScopeSpec().isSet()) {
2362 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
2363 UPPC_DeclarationQualifier))
2364 return 0;
2366 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
2367 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
2368 if (!DC) {
2369 // If we could not compute the declaration context, it's because the
2370 // declaration context is dependent but does not refer to a class,
2371 // class template, or class template partial specialization. Complain
2372 // and return early, to avoid the coming semantic disaster.
2373 Diag(D.getIdentifierLoc(),
2374 diag::err_template_qualified_declarator_no_match)
2375 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
2376 << D.getCXXScopeSpec().getRange();
2377 return 0;
2380 bool IsDependentContext = DC->isDependentContext();
2382 if (!IsDependentContext &&
2383 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
2384 return 0;
2386 if (isa<CXXRecordDecl>(DC)) {
2387 if (!cast<CXXRecordDecl>(DC)->hasDefinition()) {
2388 Diag(D.getIdentifierLoc(),
2389 diag::err_member_def_undefined_record)
2390 << Name << DC << D.getCXXScopeSpec().getRange();
2391 D.setInvalidType();
2392 } else if (isa<CXXRecordDecl>(CurContext) &&
2393 !D.getDeclSpec().isFriendSpecified()) {
2394 // The user provided a superfluous scope specifier inside a class
2395 // definition:
2397 // class X {
2398 // void X::f();
2399 // };
2400 if (CurContext->Equals(DC))
2401 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
2402 << Name << FixItHint::CreateRemoval(D.getCXXScopeSpec().getRange());
2403 else
2404 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2405 << Name << D.getCXXScopeSpec().getRange();
2407 // Pretend that this qualifier was not here.
2408 D.getCXXScopeSpec().clear();
2412 // Check whether we need to rebuild the type of the given
2413 // declaration in the current instantiation.
2414 if (EnteringContext && IsDependentContext &&
2415 TemplateParamLists.size() != 0) {
2416 ContextRAII SavedContext(*this, DC);
2417 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
2418 D.setInvalidType();
2422 // C++ [class.mem]p13:
2423 // If T is the name of a class, then each of the following shall have a
2424 // name different from T:
2425 // - every static data member of class T;
2426 // - every member function of class T
2427 // - every member of class T that is itself a type;
2428 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
2429 if (Record->getIdentifier() && Record->getDeclName() == Name) {
2430 Diag(D.getIdentifierLoc(), diag::err_member_name_of_class)
2431 << Name;
2433 // If this is a typedef, we'll end up spewing multiple diagnostics.
2434 // Just return early; it's safer.
2435 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2436 return 0;
2439 NamedDecl *New;
2441 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
2442 QualType R = TInfo->getType();
2444 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
2445 UPPC_DeclarationType))
2446 D.setInvalidType();
2448 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
2449 ForRedeclaration);
2451 // See if this is a redefinition of a variable in the same scope.
2452 if (!D.getCXXScopeSpec().isSet()) {
2453 bool IsLinkageLookup = false;
2455 // If the declaration we're planning to build will be a function
2456 // or object with linkage, then look for another declaration with
2457 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
2458 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2459 /* Do nothing*/;
2460 else if (R->isFunctionType()) {
2461 if (CurContext->isFunctionOrMethod() ||
2462 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
2463 IsLinkageLookup = true;
2464 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
2465 IsLinkageLookup = true;
2466 else if (CurContext->getRedeclContext()->isTranslationUnit() &&
2467 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
2468 IsLinkageLookup = true;
2470 if (IsLinkageLookup)
2471 Previous.clear(LookupRedeclarationWithLinkage);
2473 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
2474 } else { // Something like "int foo::x;"
2475 LookupQualifiedName(Previous, DC);
2477 // Don't consider using declarations as previous declarations for
2478 // out-of-line members.
2479 RemoveUsingDecls(Previous);
2481 // C++ 7.3.1.2p2:
2482 // Members (including explicit specializations of templates) of a named
2483 // namespace can also be defined outside that namespace by explicit
2484 // qualification of the name being defined, provided that the entity being
2485 // defined was already declared in the namespace and the definition appears
2486 // after the point of declaration in a namespace that encloses the
2487 // declarations namespace.
2489 // Note that we only check the context at this point. We don't yet
2490 // have enough information to make sure that PrevDecl is actually
2491 // the declaration we want to match. For example, given:
2493 // class X {
2494 // void f();
2495 // void f(float);
2496 // };
2498 // void X::f(int) { } // ill-formed
2500 // In this case, PrevDecl will point to the overload set
2501 // containing the two f's declared in X, but neither of them
2502 // matches.
2504 // First check whether we named the global scope.
2505 if (isa<TranslationUnitDecl>(DC)) {
2506 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
2507 << Name << D.getCXXScopeSpec().getRange();
2508 } else {
2509 DeclContext *Cur = CurContext;
2510 while (isa<LinkageSpecDecl>(Cur))
2511 Cur = Cur->getParent();
2512 if (!Cur->Encloses(DC)) {
2513 // The qualifying scope doesn't enclose the original declaration.
2514 // Emit diagnostic based on current scope.
2515 SourceLocation L = D.getIdentifierLoc();
2516 SourceRange R = D.getCXXScopeSpec().getRange();
2517 if (isa<FunctionDecl>(Cur))
2518 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
2519 else
2520 Diag(L, diag::err_invalid_declarator_scope)
2521 << Name << cast<NamedDecl>(DC) << R;
2522 D.setInvalidType();
2527 if (Previous.isSingleResult() &&
2528 Previous.getFoundDecl()->isTemplateParameter()) {
2529 // Maybe we will complain about the shadowed template parameter.
2530 if (!D.isInvalidType())
2531 if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
2532 Previous.getFoundDecl()))
2533 D.setInvalidType();
2535 // Just pretend that we didn't see the previous declaration.
2536 Previous.clear();
2539 // In C++, the previous declaration we find might be a tag type
2540 // (class or enum). In this case, the new declaration will hide the
2541 // tag type. Note that this does does not apply if we're declaring a
2542 // typedef (C++ [dcl.typedef]p4).
2543 if (Previous.isSingleTagDecl() &&
2544 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
2545 Previous.clear();
2547 bool Redeclaration = false;
2548 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
2549 if (TemplateParamLists.size()) {
2550 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
2551 return 0;
2554 New = ActOnTypedefDeclarator(S, D, DC, R, TInfo, Previous, Redeclaration);
2555 } else if (R->isFunctionType()) {
2556 New = ActOnFunctionDeclarator(S, D, DC, R, TInfo, Previous,
2557 move(TemplateParamLists),
2558 IsFunctionDefinition, Redeclaration);
2559 } else {
2560 New = ActOnVariableDeclarator(S, D, DC, R, TInfo, Previous,
2561 move(TemplateParamLists),
2562 Redeclaration);
2565 if (New == 0)
2566 return 0;
2568 // If this has an identifier and is not an invalid redeclaration or
2569 // function template specialization, add it to the scope stack.
2570 if (New->getDeclName() && !(Redeclaration && New->isInvalidDecl()))
2571 PushOnScopeChains(New, S);
2573 return New;
2576 /// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2577 /// types into constant array types in certain situations which would otherwise
2578 /// be errors (for GCC compatibility).
2579 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2580 ASTContext &Context,
2581 bool &SizeIsNegative,
2582 llvm::APSInt &Oversized) {
2583 // This method tries to turn a variable array into a constant
2584 // array even when the size isn't an ICE. This is necessary
2585 // for compatibility with code that depends on gcc's buggy
2586 // constant expression folding, like struct {char x[(int)(char*)2];}
2587 SizeIsNegative = false;
2588 Oversized = 0;
2590 if (T->isDependentType())
2591 return QualType();
2593 QualifierCollector Qs;
2594 const Type *Ty = Qs.strip(T);
2596 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
2597 QualType Pointee = PTy->getPointeeType();
2598 QualType FixedType =
2599 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
2600 Oversized);
2601 if (FixedType.isNull()) return FixedType;
2602 FixedType = Context.getPointerType(FixedType);
2603 return Qs.apply(Context, FixedType);
2605 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
2606 QualType Inner = PTy->getInnerType();
2607 QualType FixedType =
2608 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
2609 Oversized);
2610 if (FixedType.isNull()) return FixedType;
2611 FixedType = Context.getParenType(FixedType);
2612 return Qs.apply(Context, FixedType);
2615 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2616 if (!VLATy)
2617 return QualType();
2618 // FIXME: We should probably handle this case
2619 if (VLATy->getElementType()->isVariablyModifiedType())
2620 return QualType();
2622 Expr::EvalResult EvalResult;
2623 if (!VLATy->getSizeExpr() ||
2624 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
2625 !EvalResult.Val.isInt())
2626 return QualType();
2628 // Check whether the array size is negative.
2629 llvm::APSInt &Res = EvalResult.Val.getInt();
2630 if (Res.isSigned() && Res.isNegative()) {
2631 SizeIsNegative = true;
2632 return QualType();
2635 // Check whether the array is too large to be addressed.
2636 unsigned ActiveSizeBits
2637 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
2638 Res);
2639 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2640 Oversized = Res;
2641 return QualType();
2644 return Context.getConstantArrayType(VLATy->getElementType(),
2645 Res, ArrayType::Normal, 0);
2648 /// \brief Register the given locally-scoped external C declaration so
2649 /// that it can be found later for redeclarations
2650 void
2651 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
2652 const LookupResult &Previous,
2653 Scope *S) {
2654 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
2655 "Decl is not a locally-scoped decl!");
2656 // Note that we have a locally-scoped external with this name.
2657 LocallyScopedExternalDecls[ND->getDeclName()] = ND;
2659 if (!Previous.isSingleResult())
2660 return;
2662 NamedDecl *PrevDecl = Previous.getFoundDecl();
2664 // If there was a previous declaration of this variable, it may be
2665 // in our identifier chain. Update the identifier chain with the new
2666 // declaration.
2667 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
2668 // The previous declaration was found on the identifer resolver
2669 // chain, so remove it from its scope.
2670 while (S && !S->isDeclScope(PrevDecl))
2671 S = S->getParent();
2673 if (S)
2674 S->RemoveDecl(PrevDecl);
2678 /// \brief Diagnose function specifiers on a declaration of an identifier that
2679 /// does not identify a function.
2680 void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
2681 // FIXME: We should probably indicate the identifier in question to avoid
2682 // confusion for constructs like "inline int a(), b;"
2683 if (D.getDeclSpec().isInlineSpecified())
2684 Diag(D.getDeclSpec().getInlineSpecLoc(),
2685 diag::err_inline_non_function);
2687 if (D.getDeclSpec().isVirtualSpecified())
2688 Diag(D.getDeclSpec().getVirtualSpecLoc(),
2689 diag::err_virtual_non_function);
2691 if (D.getDeclSpec().isExplicitSpecified())
2692 Diag(D.getDeclSpec().getExplicitSpecLoc(),
2693 diag::err_explicit_non_function);
2696 NamedDecl*
2697 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2698 QualType R, TypeSourceInfo *TInfo,
2699 LookupResult &Previous, bool &Redeclaration) {
2700 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
2701 if (D.getCXXScopeSpec().isSet()) {
2702 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
2703 << D.getCXXScopeSpec().getRange();
2704 D.setInvalidType();
2705 // Pretend we didn't see the scope specifier.
2706 DC = CurContext;
2707 Previous.clear();
2710 if (getLangOptions().CPlusPlus) {
2711 // Check that there are no default arguments (C++ only).
2712 CheckExtraCXXDefaultArguments(D);
2715 DiagnoseFunctionSpecifiers(D);
2717 if (D.getDeclSpec().isThreadSpecified())
2718 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2720 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
2721 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
2722 << D.getName().getSourceRange();
2723 return 0;
2726 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, TInfo);
2727 if (!NewTD) return 0;
2729 // Handle attributes prior to checking for duplicates in MergeVarDecl
2730 ProcessDeclAttributes(S, NewTD, D);
2732 // C99 6.7.7p2: If a typedef name specifies a variably modified type
2733 // then it shall have block scope.
2734 // Note that variably modified types must be fixed before merging the decl so
2735 // that redeclarations will match.
2736 QualType T = NewTD->getUnderlyingType();
2737 if (T->isVariablyModifiedType()) {
2738 getCurFunction()->setHasBranchProtectedScope();
2740 if (S->getFnParent() == 0) {
2741 bool SizeIsNegative;
2742 llvm::APSInt Oversized;
2743 QualType FixedTy =
2744 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
2745 Oversized);
2746 if (!FixedTy.isNull()) {
2747 Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size);
2748 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
2749 } else {
2750 if (SizeIsNegative)
2751 Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size);
2752 else if (T->isVariableArrayType())
2753 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
2754 else if (Oversized.getBoolValue())
2755 Diag(D.getIdentifierLoc(), diag::err_array_too_large)
2756 << Oversized.toString(10);
2757 else
2758 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
2759 NewTD->setInvalidDecl();
2764 // Merge the decl with the existing one if appropriate. If the decl is
2765 // in an outer scope, it isn't the same thing.
2766 FilterLookupForScope(*this, Previous, DC, S, /*ConsiderLinkage*/ false);
2767 if (!Previous.empty()) {
2768 Redeclaration = true;
2769 MergeTypeDefDecl(NewTD, Previous);
2772 // If this is the C FILE type, notify the AST context.
2773 if (IdentifierInfo *II = NewTD->getIdentifier())
2774 if (!NewTD->isInvalidDecl() &&
2775 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
2776 if (II->isStr("FILE"))
2777 Context.setFILEDecl(NewTD);
2778 else if (II->isStr("jmp_buf"))
2779 Context.setjmp_bufDecl(NewTD);
2780 else if (II->isStr("sigjmp_buf"))
2781 Context.setsigjmp_bufDecl(NewTD);
2782 else if (II->isStr("__builtin_va_list"))
2783 Context.setBuiltinVaListType(Context.getTypedefType(NewTD));
2786 return NewTD;
2789 /// \brief Determines whether the given declaration is an out-of-scope
2790 /// previous declaration.
2792 /// This routine should be invoked when name lookup has found a
2793 /// previous declaration (PrevDecl) that is not in the scope where a
2794 /// new declaration by the same name is being introduced. If the new
2795 /// declaration occurs in a local scope, previous declarations with
2796 /// linkage may still be considered previous declarations (C99
2797 /// 6.2.2p4-5, C++ [basic.link]p6).
2799 /// \param PrevDecl the previous declaration found by name
2800 /// lookup
2802 /// \param DC the context in which the new declaration is being
2803 /// declared.
2805 /// \returns true if PrevDecl is an out-of-scope previous declaration
2806 /// for a new delcaration with the same name.
2807 static bool
2808 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
2809 ASTContext &Context) {
2810 if (!PrevDecl)
2811 return false;
2813 if (!PrevDecl->hasLinkage())
2814 return false;
2816 if (Context.getLangOptions().CPlusPlus) {
2817 // C++ [basic.link]p6:
2818 // If there is a visible declaration of an entity with linkage
2819 // having the same name and type, ignoring entities declared
2820 // outside the innermost enclosing namespace scope, the block
2821 // scope declaration declares that same entity and receives the
2822 // linkage of the previous declaration.
2823 DeclContext *OuterContext = DC->getRedeclContext();
2824 if (!OuterContext->isFunctionOrMethod())
2825 // This rule only applies to block-scope declarations.
2826 return false;
2828 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
2829 if (PrevOuterContext->isRecord())
2830 // We found a member function: ignore it.
2831 return false;
2833 // Find the innermost enclosing namespace for the new and
2834 // previous declarations.
2835 OuterContext = OuterContext->getEnclosingNamespaceContext();
2836 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
2838 // The previous declaration is in a different namespace, so it
2839 // isn't the same function.
2840 if (!OuterContext->Equals(PrevOuterContext))
2841 return false;
2844 return true;
2847 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
2848 CXXScopeSpec &SS = D.getCXXScopeSpec();
2849 if (!SS.isSet()) return;
2850 DD->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2851 SS.getRange());
2854 NamedDecl*
2855 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
2856 QualType R, TypeSourceInfo *TInfo,
2857 LookupResult &Previous,
2858 MultiTemplateParamsArg TemplateParamLists,
2859 bool &Redeclaration) {
2860 DeclarationName Name = GetNameForDeclarator(D).getName();
2862 // Check that there are no default arguments (C++ only).
2863 if (getLangOptions().CPlusPlus)
2864 CheckExtraCXXDefaultArguments(D);
2866 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
2867 assert(SCSpec != DeclSpec::SCS_typedef &&
2868 "Parser allowed 'typedef' as storage class VarDecl.");
2869 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
2870 if (SCSpec == DeclSpec::SCS_mutable) {
2871 // mutable can only appear on non-static class members, so it's always
2872 // an error here
2873 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
2874 D.setInvalidType();
2875 SC = SC_None;
2877 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
2878 VarDecl::StorageClass SCAsWritten
2879 = StorageClassSpecToVarDeclStorageClass(SCSpec);
2881 IdentifierInfo *II = Name.getAsIdentifierInfo();
2882 if (!II) {
2883 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
2884 << Name.getAsString();
2885 return 0;
2888 DiagnoseFunctionSpecifiers(D);
2890 if (!DC->isRecord() && S->getFnParent() == 0) {
2891 // C99 6.9p2: The storage-class specifiers auto and register shall not
2892 // appear in the declaration specifiers in an external declaration.
2893 if (SC == SC_Auto || SC == SC_Register) {
2895 // If this is a register variable with an asm label specified, then this
2896 // is a GNU extension.
2897 if (SC == SC_Register && D.getAsmLabel())
2898 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
2899 else
2900 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
2901 D.setInvalidType();
2905 bool isExplicitSpecialization = false;
2906 VarDecl *NewVD;
2907 if (!getLangOptions().CPlusPlus) {
2908 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
2909 II, R, TInfo, SC, SCAsWritten);
2911 if (D.isInvalidType())
2912 NewVD->setInvalidDecl();
2913 } else {
2914 if (DC->isRecord() && !CurContext->isRecord()) {
2915 // This is an out-of-line definition of a static data member.
2916 if (SC == SC_Static) {
2917 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2918 diag::err_static_out_of_line)
2919 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
2920 } else if (SC == SC_None)
2921 SC = SC_Static;
2923 if (SC == SC_Static) {
2924 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
2925 if (RD->isLocalClass())
2926 Diag(D.getIdentifierLoc(),
2927 diag::err_static_data_member_not_allowed_in_local_class)
2928 << Name << RD->getDeclName();
2930 // C++ [class.union]p1: If a union contains a static data member,
2931 // the program is ill-formed.
2933 // We also disallow static data members in anonymous structs.
2934 if (CurContext->isRecord() && (RD->isUnion() || !RD->getDeclName()))
2935 Diag(D.getIdentifierLoc(),
2936 diag::err_static_data_member_not_allowed_in_union_or_anon_struct)
2937 << Name << RD->isUnion();
2941 // Match up the template parameter lists with the scope specifier, then
2942 // determine whether we have a template or a template specialization.
2943 isExplicitSpecialization = false;
2944 unsigned NumMatchedTemplateParamLists = TemplateParamLists.size();
2945 bool Invalid = false;
2946 if (TemplateParameterList *TemplateParams
2947 = MatchTemplateParametersToScopeSpecifier(
2948 D.getDeclSpec().getSourceRange().getBegin(),
2949 D.getCXXScopeSpec(),
2950 TemplateParamLists.get(),
2951 TemplateParamLists.size(),
2952 /*never a friend*/ false,
2953 isExplicitSpecialization,
2954 Invalid)) {
2955 // All but one template parameter lists have been matching.
2956 --NumMatchedTemplateParamLists;
2958 if (TemplateParams->size() > 0) {
2959 // There is no such thing as a variable template.
2960 Diag(D.getIdentifierLoc(), diag::err_template_variable)
2961 << II
2962 << SourceRange(TemplateParams->getTemplateLoc(),
2963 TemplateParams->getRAngleLoc());
2964 return 0;
2965 } else {
2966 // There is an extraneous 'template<>' for this variable. Complain
2967 // about it, but allow the declaration of the variable.
2968 Diag(TemplateParams->getTemplateLoc(),
2969 diag::err_template_variable_noparams)
2970 << II
2971 << SourceRange(TemplateParams->getTemplateLoc(),
2972 TemplateParams->getRAngleLoc());
2974 isExplicitSpecialization = true;
2978 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
2979 II, R, TInfo, SC, SCAsWritten);
2981 if (D.isInvalidType() || Invalid)
2982 NewVD->setInvalidDecl();
2984 SetNestedNameSpecifier(NewVD, D);
2986 if (NumMatchedTemplateParamLists > 0 && D.getCXXScopeSpec().isSet()) {
2987 NewVD->setTemplateParameterListsInfo(Context,
2988 NumMatchedTemplateParamLists,
2989 TemplateParamLists.release());
2993 if (D.getDeclSpec().isThreadSpecified()) {
2994 if (NewVD->hasLocalStorage())
2995 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
2996 else if (!Context.Target.isTLSSupported())
2997 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
2998 else
2999 NewVD->setThreadSpecified(true);
3002 // Set the lexical context. If the declarator has a C++ scope specifier, the
3003 // lexical context will be different from the semantic context.
3004 NewVD->setLexicalDeclContext(CurContext);
3006 // Handle attributes prior to checking for duplicates in MergeVarDecl
3007 ProcessDeclAttributes(S, NewVD, D);
3009 // Handle GNU asm-label extension (encoded as an attribute).
3010 if (Expr *E = (Expr*)D.getAsmLabel()) {
3011 // The parser guarantees this is a string.
3012 StringLiteral *SE = cast<StringLiteral>(E);
3013 llvm::StringRef Label = SE->getString();
3014 if (S->getFnParent() != 0) {
3015 switch (SC) {
3016 case SC_None:
3017 case SC_Auto:
3018 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
3019 break;
3020 case SC_Register:
3021 if (!Context.Target.isValidGCCRegisterName(Label))
3022 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
3023 break;
3024 case SC_Static:
3025 case SC_Extern:
3026 case SC_PrivateExtern:
3027 break;
3031 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
3032 Context, Label));
3035 // Diagnose shadowed variables before filtering for scope.
3036 if (!D.getCXXScopeSpec().isSet())
3037 CheckShadow(S, NewVD, Previous);
3039 // Don't consider existing declarations that are in a different
3040 // scope and are out-of-semantic-context declarations (if the new
3041 // declaration has linkage).
3042 FilterLookupForScope(*this, Previous, DC, S, NewVD->hasLinkage());
3044 if (!getLangOptions().CPlusPlus)
3045 CheckVariableDeclaration(NewVD, Previous, Redeclaration);
3046 else {
3047 // Merge the decl with the existing one if appropriate.
3048 if (!Previous.empty()) {
3049 if (Previous.isSingleResult() &&
3050 isa<FieldDecl>(Previous.getFoundDecl()) &&
3051 D.getCXXScopeSpec().isSet()) {
3052 // The user tried to define a non-static data member
3053 // out-of-line (C++ [dcl.meaning]p1).
3054 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
3055 << D.getCXXScopeSpec().getRange();
3056 Previous.clear();
3057 NewVD->setInvalidDecl();
3059 } else if (D.getCXXScopeSpec().isSet()) {
3060 // No previous declaration in the qualifying scope.
3061 Diag(D.getIdentifierLoc(), diag::err_no_member)
3062 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
3063 << D.getCXXScopeSpec().getRange();
3064 NewVD->setInvalidDecl();
3067 CheckVariableDeclaration(NewVD, Previous, Redeclaration);
3069 // This is an explicit specialization of a static data member. Check it.
3070 if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
3071 CheckMemberSpecialization(NewVD, Previous))
3072 NewVD->setInvalidDecl();
3075 // attributes declared post-definition are currently ignored
3076 // FIXME: This should be handled in attribute merging, not
3077 // here.
3078 if (Previous.isSingleResult()) {
3079 VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl());
3080 if (Def && (Def = Def->getDefinition()) &&
3081 Def != NewVD && D.hasAttributes()) {
3082 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
3083 Diag(Def->getLocation(), diag::note_previous_definition);
3087 // If this is a locally-scoped extern C variable, update the map of
3088 // such variables.
3089 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
3090 !NewVD->isInvalidDecl())
3091 RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
3093 // If there's a #pragma GCC visibility in scope, and this isn't a class
3094 // member, set the visibility of this variable.
3095 if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord())
3096 AddPushedVisibilityAttribute(NewVD);
3098 MarkUnusedFileScopedDecl(NewVD);
3100 return NewVD;
3103 /// \brief Diagnose variable or built-in function shadowing. Implements
3104 /// -Wshadow.
3106 /// This method is called whenever a VarDecl is added to a "useful"
3107 /// scope.
3109 /// \param S the scope in which the shadowing name is being declared
3110 /// \param R the lookup of the name
3112 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
3113 // Return if warning is ignored.
3114 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
3115 Diagnostic::Ignored)
3116 return;
3118 // Don't diagnose declarations at file scope. The scope might not
3119 // have a DeclContext if (e.g.) we're parsing a function prototype.
3120 DeclContext *NewDC = static_cast<DeclContext*>(S->getEntity());
3121 if (NewDC && NewDC->isFileContext())
3122 return;
3124 // Only diagnose if we're shadowing an unambiguous field or variable.
3125 if (R.getResultKind() != LookupResult::Found)
3126 return;
3128 NamedDecl* ShadowedDecl = R.getFoundDecl();
3129 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
3130 return;
3132 // Fields are not shadowed by variables in C++ static methods.
3133 if (isa<FieldDecl>(ShadowedDecl))
3134 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
3135 if (MD->isStatic())
3136 return;
3138 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
3139 if (shadowedVar->isExternC()) {
3140 // Don't warn for this case:
3142 // @code
3143 // extern int bob;
3144 // void f() {
3145 // extern int bob;
3146 // }
3147 // @endcode
3148 if (D->isExternC())
3149 return;
3151 // For shadowing external vars, make sure that we point to the global
3152 // declaration, not a locally scoped extern declaration.
3153 for (VarDecl::redecl_iterator
3154 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
3155 I != E; ++I)
3156 if (I->isFileVarDecl()) {
3157 ShadowedDecl = *I;
3158 break;
3162 DeclContext *OldDC = ShadowedDecl->getDeclContext();
3164 // Only warn about certain kinds of shadowing for class members.
3165 if (NewDC && NewDC->isRecord()) {
3166 // In particular, don't warn about shadowing non-class members.
3167 if (!OldDC->isRecord())
3168 return;
3170 // TODO: should we warn about static data members shadowing
3171 // static data members from base classes?
3173 // TODO: don't diagnose for inaccessible shadowed members.
3174 // This is hard to do perfectly because we might friend the
3175 // shadowing context, but that's just a false negative.
3178 // Determine what kind of declaration we're shadowing.
3179 unsigned Kind;
3180 if (isa<RecordDecl>(OldDC)) {
3181 if (isa<FieldDecl>(ShadowedDecl))
3182 Kind = 3; // field
3183 else
3184 Kind = 2; // static data member
3185 } else if (OldDC->isFileContext())
3186 Kind = 1; // global
3187 else
3188 Kind = 0; // local
3190 DeclarationName Name = R.getLookupName();
3192 // Emit warning and note.
3193 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
3194 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
3197 /// \brief Check -Wshadow without the advantage of a previous lookup.
3198 void Sema::CheckShadow(Scope *S, VarDecl *D) {
3199 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
3200 Diagnostic::Ignored)
3201 return;
3203 LookupResult R(*this, D->getDeclName(), D->getLocation(),
3204 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
3205 LookupName(R, S);
3206 CheckShadow(S, D, R);
3209 /// \brief Perform semantic checking on a newly-created variable
3210 /// declaration.
3212 /// This routine performs all of the type-checking required for a
3213 /// variable declaration once it has been built. It is used both to
3214 /// check variables after they have been parsed and their declarators
3215 /// have been translated into a declaration, and to check variables
3216 /// that have been instantiated from a template.
3218 /// Sets NewVD->isInvalidDecl() if an error was encountered.
3219 void Sema::CheckVariableDeclaration(VarDecl *NewVD,
3220 LookupResult &Previous,
3221 bool &Redeclaration) {
3222 // If the decl is already known invalid, don't check it.
3223 if (NewVD->isInvalidDecl())
3224 return;
3226 QualType T = NewVD->getType();
3228 if (T->isObjCObjectType()) {
3229 Diag(NewVD->getLocation(), diag::err_statically_allocated_object);
3230 return NewVD->setInvalidDecl();
3233 // Emit an error if an address space was applied to decl with local storage.
3234 // This includes arrays of objects with address space qualifiers, but not
3235 // automatic variables that point to other address spaces.
3236 // ISO/IEC TR 18037 S5.1.2
3237 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
3238 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
3239 return NewVD->setInvalidDecl();
3242 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
3243 && !NewVD->hasAttr<BlocksAttr>())
3244 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
3246 bool isVM = T->isVariablyModifiedType();
3247 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
3248 NewVD->hasAttr<BlocksAttr>())
3249 getCurFunction()->setHasBranchProtectedScope();
3251 if ((isVM && NewVD->hasLinkage()) ||
3252 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
3253 bool SizeIsNegative;
3254 llvm::APSInt Oversized;
3255 QualType FixedTy =
3256 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
3257 Oversized);
3259 if (FixedTy.isNull() && T->isVariableArrayType()) {
3260 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
3261 // FIXME: This won't give the correct result for
3262 // int a[10][n];
3263 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
3265 if (NewVD->isFileVarDecl())
3266 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
3267 << SizeRange;
3268 else if (NewVD->getStorageClass() == SC_Static)
3269 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
3270 << SizeRange;
3271 else
3272 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
3273 << SizeRange;
3274 return NewVD->setInvalidDecl();
3277 if (FixedTy.isNull()) {
3278 if (NewVD->isFileVarDecl())
3279 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
3280 else
3281 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
3282 return NewVD->setInvalidDecl();
3285 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
3286 NewVD->setType(FixedTy);
3289 if (Previous.empty() && NewVD->isExternC()) {
3290 // Since we did not find anything by this name and we're declaring
3291 // an extern "C" variable, look for a non-visible extern "C"
3292 // declaration with the same name.
3293 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3294 = LocallyScopedExternalDecls.find(NewVD->getDeclName());
3295 if (Pos != LocallyScopedExternalDecls.end())
3296 Previous.addDecl(Pos->second);
3299 if (T->isVoidType() && !NewVD->hasExternalStorage()) {
3300 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
3301 << T;
3302 return NewVD->setInvalidDecl();
3305 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
3306 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
3307 return NewVD->setInvalidDecl();
3310 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
3311 Diag(NewVD->getLocation(), diag::err_block_on_vm);
3312 return NewVD->setInvalidDecl();
3315 // Function pointers and references cannot have qualified function type, only
3316 // function pointer-to-members can do that.
3317 QualType Pointee;
3318 unsigned PtrOrRef = 0;
3319 if (const PointerType *Ptr = T->getAs<PointerType>())
3320 Pointee = Ptr->getPointeeType();
3321 else if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
3322 Pointee = Ref->getPointeeType();
3323 PtrOrRef = 1;
3325 if (!Pointee.isNull() && Pointee->isFunctionProtoType() &&
3326 Pointee->getAs<FunctionProtoType>()->getTypeQuals() != 0) {
3327 Diag(NewVD->getLocation(), diag::err_invalid_qualified_function_pointer)
3328 << PtrOrRef;
3329 return NewVD->setInvalidDecl();
3332 if (!Previous.empty()) {
3333 Redeclaration = true;
3334 MergeVarDecl(NewVD, Previous);
3338 /// \brief Data used with FindOverriddenMethod
3339 struct FindOverriddenMethodData {
3340 Sema *S;
3341 CXXMethodDecl *Method;
3344 /// \brief Member lookup function that determines whether a given C++
3345 /// method overrides a method in a base class, to be used with
3346 /// CXXRecordDecl::lookupInBases().
3347 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
3348 CXXBasePath &Path,
3349 void *UserData) {
3350 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
3352 FindOverriddenMethodData *Data
3353 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
3355 DeclarationName Name = Data->Method->getDeclName();
3357 // FIXME: Do we care about other names here too?
3358 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
3359 // We really want to find the base class destructor here.
3360 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
3361 CanQualType CT = Data->S->Context.getCanonicalType(T);
3363 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
3366 for (Path.Decls = BaseRecord->lookup(Name);
3367 Path.Decls.first != Path.Decls.second;
3368 ++Path.Decls.first) {
3369 NamedDecl *D = *Path.Decls.first;
3370 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
3371 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
3372 return true;
3376 return false;
3379 /// AddOverriddenMethods - See if a method overrides any in the base classes,
3380 /// and if so, check that it's a valid override and remember it.
3381 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
3382 // Look for virtual methods in base classes that this method might override.
3383 CXXBasePaths Paths;
3384 FindOverriddenMethodData Data;
3385 Data.Method = MD;
3386 Data.S = this;
3387 bool AddedAny = false;
3388 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
3389 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
3390 E = Paths.found_decls_end(); I != E; ++I) {
3391 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
3392 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
3393 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
3394 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
3395 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
3396 AddedAny = true;
3402 return AddedAny;
3405 static void DiagnoseInvalidRedeclaration(Sema &S, FunctionDecl *NewFD) {
3406 LookupResult Prev(S, NewFD->getDeclName(), NewFD->getLocation(),
3407 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
3408 S.LookupQualifiedName(Prev, NewFD->getDeclContext());
3409 assert(!Prev.isAmbiguous() &&
3410 "Cannot have an ambiguity in previous-declaration lookup");
3411 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
3412 Func != FuncEnd; ++Func) {
3413 if (isa<FunctionDecl>(*Func) &&
3414 isNearlyMatchingFunction(S.Context, cast<FunctionDecl>(*Func), NewFD))
3415 S.Diag((*Func)->getLocation(), diag::note_member_def_close_match);
3419 NamedDecl*
3420 Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
3421 QualType R, TypeSourceInfo *TInfo,
3422 LookupResult &Previous,
3423 MultiTemplateParamsArg TemplateParamLists,
3424 bool IsFunctionDefinition, bool &Redeclaration) {
3425 assert(R.getTypePtr()->isFunctionType());
3427 // TODO: consider using NameInfo for diagnostic.
3428 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3429 DeclarationName Name = NameInfo.getName();
3430 FunctionDecl::StorageClass SC = SC_None;
3431 switch (D.getDeclSpec().getStorageClassSpec()) {
3432 default: assert(0 && "Unknown storage class!");
3433 case DeclSpec::SCS_auto:
3434 case DeclSpec::SCS_register:
3435 case DeclSpec::SCS_mutable:
3436 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
3437 diag::err_typecheck_sclass_func);
3438 D.setInvalidType();
3439 break;
3440 case DeclSpec::SCS_unspecified: SC = SC_None; break;
3441 case DeclSpec::SCS_extern: SC = SC_Extern; break;
3442 case DeclSpec::SCS_static: {
3443 if (CurContext->getRedeclContext()->isFunctionOrMethod()) {
3444 // C99 6.7.1p5:
3445 // The declaration of an identifier for a function that has
3446 // block scope shall have no explicit storage-class specifier
3447 // other than extern
3448 // See also (C++ [dcl.stc]p4).
3449 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
3450 diag::err_static_block_func);
3451 SC = SC_None;
3452 } else
3453 SC = SC_Static;
3454 break;
3456 case DeclSpec::SCS_private_extern: SC = SC_PrivateExtern; break;
3459 if (D.getDeclSpec().isThreadSpecified())
3460 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
3462 // Do not allow returning a objc interface by-value.
3463 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
3464 Diag(D.getIdentifierLoc(),
3465 diag::err_object_cannot_be_passed_returned_by_value) << 0
3466 << R->getAs<FunctionType>()->getResultType();
3467 D.setInvalidType();
3470 FunctionDecl *NewFD;
3471 bool isInline = D.getDeclSpec().isInlineSpecified();
3472 bool isFriend = false;
3473 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
3474 FunctionDecl::StorageClass SCAsWritten
3475 = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
3476 FunctionTemplateDecl *FunctionTemplate = 0;
3477 bool isExplicitSpecialization = false;
3478 bool isFunctionTemplateSpecialization = false;
3479 unsigned NumMatchedTemplateParamLists = 0;
3481 if (!getLangOptions().CPlusPlus) {
3482 // Determine whether the function was written with a
3483 // prototype. This true when:
3484 // - there is a prototype in the declarator, or
3485 // - the type R of the function is some kind of typedef or other reference
3486 // to a type name (which eventually refers to a function type).
3487 bool HasPrototype =
3488 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
3489 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
3491 NewFD = FunctionDecl::Create(Context, DC,
3492 NameInfo, R, TInfo, SC, SCAsWritten, isInline,
3493 HasPrototype);
3494 if (D.isInvalidType())
3495 NewFD->setInvalidDecl();
3497 // Set the lexical context.
3498 NewFD->setLexicalDeclContext(CurContext);
3499 // Filter out previous declarations that don't match the scope.
3500 FilterLookupForScope(*this, Previous, DC, S, NewFD->hasLinkage());
3501 } else {
3502 isFriend = D.getDeclSpec().isFriendSpecified();
3503 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
3504 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
3505 bool isVirtualOkay = false;
3507 // Check that the return type is not an abstract class type.
3508 // For record types, this is done by the AbstractClassUsageDiagnoser once
3509 // the class has been completely parsed.
3510 if (!DC->isRecord() &&
3511 RequireNonAbstractType(D.getIdentifierLoc(),
3512 R->getAs<FunctionType>()->getResultType(),
3513 diag::err_abstract_type_in_decl,
3514 AbstractReturnType))
3515 D.setInvalidType();
3518 if (isFriend) {
3519 // C++ [class.friend]p5
3520 // A function can be defined in a friend declaration of a
3521 // class . . . . Such a function is implicitly inline.
3522 isInline |= IsFunctionDefinition;
3525 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
3526 // This is a C++ constructor declaration.
3527 assert(DC->isRecord() &&
3528 "Constructors can only be declared in a member context");
3530 R = CheckConstructorDeclarator(D, R, SC);
3532 // Create the new declaration
3533 NewFD = CXXConstructorDecl::Create(Context,
3534 cast<CXXRecordDecl>(DC),
3535 NameInfo, R, TInfo,
3536 isExplicit, isInline,
3537 /*isImplicitlyDeclared=*/false);
3538 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
3539 // This is a C++ destructor declaration.
3540 if (DC->isRecord()) {
3541 R = CheckDestructorDeclarator(D, R, SC);
3543 NewFD = CXXDestructorDecl::Create(Context,
3544 cast<CXXRecordDecl>(DC),
3545 NameInfo, R, TInfo,
3546 isInline,
3547 /*isImplicitlyDeclared=*/false);
3548 isVirtualOkay = true;
3549 } else {
3550 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
3552 // Create a FunctionDecl to satisfy the function definition parsing
3553 // code path.
3554 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
3555 Name, R, TInfo, SC, SCAsWritten, isInline,
3556 /*hasPrototype=*/true);
3557 D.setInvalidType();
3559 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
3560 if (!DC->isRecord()) {
3561 Diag(D.getIdentifierLoc(),
3562 diag::err_conv_function_not_member);
3563 return 0;
3566 CheckConversionDeclarator(D, R, SC);
3567 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
3568 NameInfo, R, TInfo,
3569 isInline, isExplicit);
3571 isVirtualOkay = true;
3572 } else if (DC->isRecord()) {
3573 // If the of the function is the same as the name of the record, then this
3574 // must be an invalid constructor that has a return type.
3575 // (The parser checks for a return type and makes the declarator a
3576 // constructor if it has no return type).
3577 // must have an invalid constructor that has a return type
3578 if (Name.getAsIdentifierInfo() &&
3579 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
3580 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
3581 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3582 << SourceRange(D.getIdentifierLoc());
3583 return 0;
3586 bool isStatic = SC == SC_Static;
3588 // [class.free]p1:
3589 // Any allocation function for a class T is a static member
3590 // (even if not explicitly declared static).
3591 if (Name.getCXXOverloadedOperator() == OO_New ||
3592 Name.getCXXOverloadedOperator() == OO_Array_New)
3593 isStatic = true;
3595 // [class.free]p6 Any deallocation function for a class X is a static member
3596 // (even if not explicitly declared static).
3597 if (Name.getCXXOverloadedOperator() == OO_Delete ||
3598 Name.getCXXOverloadedOperator() == OO_Array_Delete)
3599 isStatic = true;
3601 // This is a C++ method declaration.
3602 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
3603 NameInfo, R, TInfo,
3604 isStatic, SCAsWritten, isInline);
3606 isVirtualOkay = !isStatic;
3607 } else {
3608 // Determine whether the function was written with a
3609 // prototype. This true when:
3610 // - we're in C++ (where every function has a prototype),
3611 NewFD = FunctionDecl::Create(Context, DC,
3612 NameInfo, R, TInfo, SC, SCAsWritten, isInline,
3613 true/*HasPrototype*/);
3615 SetNestedNameSpecifier(NewFD, D);
3616 isExplicitSpecialization = false;
3617 isFunctionTemplateSpecialization = false;
3618 NumMatchedTemplateParamLists = TemplateParamLists.size();
3619 if (D.isInvalidType())
3620 NewFD->setInvalidDecl();
3622 // Set the lexical context. If the declarator has a C++
3623 // scope specifier, or is the object of a friend declaration, the
3624 // lexical context will be different from the semantic context.
3625 NewFD->setLexicalDeclContext(CurContext);
3627 // Match up the template parameter lists with the scope specifier, then
3628 // determine whether we have a template or a template specialization.
3629 bool Invalid = false;
3630 if (TemplateParameterList *TemplateParams
3631 = MatchTemplateParametersToScopeSpecifier(
3632 D.getDeclSpec().getSourceRange().getBegin(),
3633 D.getCXXScopeSpec(),
3634 TemplateParamLists.get(),
3635 TemplateParamLists.size(),
3636 isFriend,
3637 isExplicitSpecialization,
3638 Invalid)) {
3639 // All but one template parameter lists have been matching.
3640 --NumMatchedTemplateParamLists;
3642 if (TemplateParams->size() > 0) {
3643 // This is a function template
3645 // Check that we can declare a template here.
3646 if (CheckTemplateDeclScope(S, TemplateParams))
3647 return 0;
3649 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
3650 NewFD->getLocation(),
3651 Name, TemplateParams,
3652 NewFD);
3653 FunctionTemplate->setLexicalDeclContext(CurContext);
3654 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
3655 } else {
3656 // This is a function template specialization.
3657 isFunctionTemplateSpecialization = true;
3659 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
3660 if (isFriend && isFunctionTemplateSpecialization) {
3661 // We want to remove the "template<>", found here.
3662 SourceRange RemoveRange = TemplateParams->getSourceRange();
3664 // If we remove the template<> and the name is not a
3665 // template-id, we're actually silently creating a problem:
3666 // the friend declaration will refer to an untemplated decl,
3667 // and clearly the user wants a template specialization. So
3668 // we need to insert '<>' after the name.
3669 SourceLocation InsertLoc;
3670 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
3671 InsertLoc = D.getName().getSourceRange().getEnd();
3672 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
3675 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
3676 << Name << RemoveRange
3677 << FixItHint::CreateRemoval(RemoveRange)
3678 << FixItHint::CreateInsertion(InsertLoc, "<>");
3683 if (NumMatchedTemplateParamLists > 0 && D.getCXXScopeSpec().isSet()) {
3684 NewFD->setTemplateParameterListsInfo(Context,
3685 NumMatchedTemplateParamLists,
3686 TemplateParamLists.release());
3689 if (Invalid) {
3690 NewFD->setInvalidDecl();
3691 if (FunctionTemplate)
3692 FunctionTemplate->setInvalidDecl();
3695 // C++ [dcl.fct.spec]p5:
3696 // The virtual specifier shall only be used in declarations of
3697 // nonstatic class member functions that appear within a
3698 // member-specification of a class declaration; see 10.3.
3700 if (isVirtual && !NewFD->isInvalidDecl()) {
3701 if (!isVirtualOkay) {
3702 Diag(D.getDeclSpec().getVirtualSpecLoc(),
3703 diag::err_virtual_non_function);
3704 } else if (!CurContext->isRecord()) {
3705 // 'virtual' was specified outside of the class.
3706 Diag(D.getDeclSpec().getVirtualSpecLoc(),
3707 diag::err_virtual_out_of_class)
3708 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
3709 } else if (NewFD->getDescribedFunctionTemplate()) {
3710 // C++ [temp.mem]p3:
3711 // A member function template shall not be virtual.
3712 Diag(D.getDeclSpec().getVirtualSpecLoc(),
3713 diag::err_virtual_member_function_template)
3714 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
3715 } else {
3716 // Okay: Add virtual to the method.
3717 NewFD->setVirtualAsWritten(true);
3721 // C++ [dcl.fct.spec]p3:
3722 // The inline specifier shall not appear on a block scope function declaration.
3723 if (isInline && !NewFD->isInvalidDecl()) {
3724 if (CurContext->isFunctionOrMethod()) {
3725 // 'inline' is not allowed on block scope function declaration.
3726 Diag(D.getDeclSpec().getInlineSpecLoc(),
3727 diag::err_inline_declaration_block_scope) << Name
3728 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
3732 // C++ [dcl.fct.spec]p6:
3733 // The explicit specifier shall be used only in the declaration of a
3734 // constructor or conversion function within its class definition; see 12.3.1
3735 // and 12.3.2.
3736 if (isExplicit && !NewFD->isInvalidDecl()) {
3737 if (!CurContext->isRecord()) {
3738 // 'explicit' was specified outside of the class.
3739 Diag(D.getDeclSpec().getExplicitSpecLoc(),
3740 diag::err_explicit_out_of_class)
3741 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
3742 } else if (!isa<CXXConstructorDecl>(NewFD) &&
3743 !isa<CXXConversionDecl>(NewFD)) {
3744 // 'explicit' was specified on a function that wasn't a constructor
3745 // or conversion function.
3746 Diag(D.getDeclSpec().getExplicitSpecLoc(),
3747 diag::err_explicit_non_ctor_or_conv_function)
3748 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
3752 // Filter out previous declarations that don't match the scope.
3753 FilterLookupForScope(*this, Previous, DC, S, NewFD->hasLinkage());
3755 if (isFriend) {
3756 // For now, claim that the objects have no previous declaration.
3757 if (FunctionTemplate) {
3758 FunctionTemplate->setObjectOfFriendDecl(false);
3759 FunctionTemplate->setAccess(AS_public);
3761 NewFD->setObjectOfFriendDecl(false);
3762 NewFD->setAccess(AS_public);
3765 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && IsFunctionDefinition) {
3766 // A method is implicitly inline if it's defined in its class
3767 // definition.
3768 NewFD->setImplicitlyInline();
3771 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
3772 !CurContext->isRecord()) {
3773 // C++ [class.static]p1:
3774 // A data or function member of a class may be declared static
3775 // in a class definition, in which case it is a static member of
3776 // the class.
3778 // Complain about the 'static' specifier if it's on an out-of-line
3779 // member function definition.
3780 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
3781 diag::err_static_out_of_line)
3782 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3786 // Handle GNU asm-label extension (encoded as an attribute).
3787 if (Expr *E = (Expr*) D.getAsmLabel()) {
3788 // The parser guarantees this is a string.
3789 StringLiteral *SE = cast<StringLiteral>(E);
3790 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
3791 SE->getString()));
3794 // Copy the parameter declarations from the declarator D to the function
3795 // declaration NewFD, if they are available. First scavenge them into Params.
3796 llvm::SmallVector<ParmVarDecl*, 16> Params;
3797 if (D.isFunctionDeclarator()) {
3798 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
3800 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
3801 // function that takes no arguments, not a function that takes a
3802 // single void argument.
3803 // We let through "const void" here because Sema::GetTypeForDeclarator
3804 // already checks for that case.
3805 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3806 FTI.ArgInfo[0].Param &&
3807 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
3808 // Empty arg list, don't push any params.
3809 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[0].Param);
3811 // In C++, the empty parameter-type-list must be spelled "void"; a
3812 // typedef of void is not permitted.
3813 if (getLangOptions().CPlusPlus &&
3814 Param->getType().getUnqualifiedType() != Context.VoidTy)
3815 Diag(Param->getLocation(), diag::err_param_typedef_of_void);
3816 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
3817 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
3818 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
3819 assert(Param->getDeclContext() != NewFD && "Was set before ?");
3820 Param->setDeclContext(NewFD);
3821 Params.push_back(Param);
3823 if (Param->isInvalidDecl())
3824 NewFD->setInvalidDecl();
3828 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
3829 // When we're declaring a function with a typedef, typeof, etc as in the
3830 // following example, we'll need to synthesize (unnamed)
3831 // parameters for use in the declaration.
3833 // @code
3834 // typedef void fn(int);
3835 // fn f;
3836 // @endcode
3838 // Synthesize a parameter for each argument type.
3839 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
3840 AE = FT->arg_type_end(); AI != AE; ++AI) {
3841 ParmVarDecl *Param =
3842 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
3843 Params.push_back(Param);
3845 } else {
3846 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
3847 "Should not need args for typedef of non-prototype fn");
3849 // Finally, we know we have the right number of parameters, install them.
3850 NewFD->setParams(Params.data(), Params.size());
3852 // Process the non-inheritable attributes on this declaration.
3853 ProcessDeclAttributes(S, NewFD, D,
3854 /*NonInheritable=*/true, /*Inheritable=*/false);
3856 if (!getLangOptions().CPlusPlus) {
3857 // Perform semantic checking on the function declaration.
3858 bool isExplctSpecialization=false;
3859 CheckFunctionDeclaration(S, NewFD, Previous, isExplctSpecialization,
3860 Redeclaration);
3861 assert((NewFD->isInvalidDecl() || !Redeclaration ||
3862 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
3863 "previous declaration set still overloaded");
3864 } else {
3865 // If the declarator is a template-id, translate the parser's template
3866 // argument list into our AST format.
3867 bool HasExplicitTemplateArgs = false;
3868 TemplateArgumentListInfo TemplateArgs;
3869 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
3870 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3871 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
3872 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
3873 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3874 TemplateId->getTemplateArgs(),
3875 TemplateId->NumArgs);
3876 translateTemplateArguments(TemplateArgsPtr,
3877 TemplateArgs);
3878 TemplateArgsPtr.release();
3880 HasExplicitTemplateArgs = true;
3882 if (FunctionTemplate) {
3883 // Function template with explicit template arguments.
3884 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
3885 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
3887 HasExplicitTemplateArgs = false;
3888 } else if (!isFunctionTemplateSpecialization &&
3889 !D.getDeclSpec().isFriendSpecified()) {
3890 // We have encountered something that the user meant to be a
3891 // specialization (because it has explicitly-specified template
3892 // arguments) but that was not introduced with a "template<>" (or had
3893 // too few of them).
3894 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
3895 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
3896 << FixItHint::CreateInsertion(
3897 D.getDeclSpec().getSourceRange().getBegin(),
3898 "template<> ");
3899 isFunctionTemplateSpecialization = true;
3900 } else {
3901 // "friend void foo<>(int);" is an implicit specialization decl.
3902 isFunctionTemplateSpecialization = true;
3904 } else if (isFriend && isFunctionTemplateSpecialization) {
3905 // This combination is only possible in a recovery case; the user
3906 // wrote something like:
3907 // template <> friend void foo(int);
3908 // which we're recovering from as if the user had written:
3909 // friend void foo<>(int);
3910 // Go ahead and fake up a template id.
3911 HasExplicitTemplateArgs = true;
3912 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
3913 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
3916 // If it's a friend (and only if it's a friend), it's possible
3917 // that either the specialized function type or the specialized
3918 // template is dependent, and therefore matching will fail. In
3919 // this case, don't check the specialization yet.
3920 if (isFunctionTemplateSpecialization && isFriend &&
3921 (NewFD->getType()->isDependentType() || DC->isDependentContext())) {
3922 assert(HasExplicitTemplateArgs &&
3923 "friend function specialization without template args");
3924 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
3925 Previous))
3926 NewFD->setInvalidDecl();
3927 } else if (isFunctionTemplateSpecialization) {
3928 if (CheckFunctionTemplateSpecialization(NewFD,
3929 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
3930 Previous))
3931 NewFD->setInvalidDecl();
3932 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
3933 if (CheckMemberSpecialization(NewFD, Previous))
3934 NewFD->setInvalidDecl();
3937 // Perform semantic checking on the function declaration.
3938 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization,
3939 Redeclaration);
3941 assert((NewFD->isInvalidDecl() || !Redeclaration ||
3942 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
3943 "previous declaration set still overloaded");
3945 NamedDecl *PrincipalDecl = (FunctionTemplate
3946 ? cast<NamedDecl>(FunctionTemplate)
3947 : NewFD);
3949 if (isFriend && Redeclaration) {
3950 AccessSpecifier Access = AS_public;
3951 if (!NewFD->isInvalidDecl())
3952 Access = NewFD->getPreviousDeclaration()->getAccess();
3954 NewFD->setAccess(Access);
3955 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
3957 PrincipalDecl->setObjectOfFriendDecl(true);
3960 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
3961 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
3962 PrincipalDecl->setNonMemberOperator();
3964 // If we have a function template, check the template parameter
3965 // list. This will check and merge default template arguments.
3966 if (FunctionTemplate) {
3967 FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration();
3968 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
3969 PrevTemplate? PrevTemplate->getTemplateParameters() : 0,
3970 D.getDeclSpec().isFriendSpecified()? TPC_FriendFunctionTemplate
3971 : TPC_FunctionTemplate);
3974 if (NewFD->isInvalidDecl()) {
3975 // Ignore all the rest of this.
3976 } else if (!Redeclaration) {
3977 // Fake up an access specifier if it's supposed to be a class member.
3978 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
3979 NewFD->setAccess(AS_public);
3981 // Qualified decls generally require a previous declaration.
3982 if (D.getCXXScopeSpec().isSet()) {
3983 // ...with the major exception of templated-scope or
3984 // dependent-scope friend declarations.
3986 // TODO: we currently also suppress this check in dependent
3987 // contexts because (1) the parameter depth will be off when
3988 // matching friend templates and (2) we might actually be
3989 // selecting a friend based on a dependent factor. But there
3990 // are situations where these conditions don't apply and we
3991 // can actually do this check immediately.
3992 if (isFriend &&
3993 (NumMatchedTemplateParamLists ||
3994 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
3995 CurContext->isDependentContext())) {
3996 // ignore these
3997 } else {
3998 // The user tried to provide an out-of-line definition for a
3999 // function that is a member of a class or namespace, but there
4000 // was no such member function declared (C++ [class.mfct]p2,
4001 // C++ [namespace.memdef]p2). For example:
4003 // class X {
4004 // void f() const;
4005 // };
4007 // void X::f() { } // ill-formed
4009 // Complain about this problem, and attempt to suggest close
4010 // matches (e.g., those that differ only in cv-qualifiers and
4011 // whether the parameter types are references).
4012 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
4013 << Name << DC << D.getCXXScopeSpec().getRange();
4014 NewFD->setInvalidDecl();
4016 DiagnoseInvalidRedeclaration(*this, NewFD);
4019 // Unqualified local friend declarations are required to resolve
4020 // to something.
4021 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
4022 Diag(D.getIdentifierLoc(), diag::err_no_matching_local_friend);
4023 NewFD->setInvalidDecl();
4024 DiagnoseInvalidRedeclaration(*this, NewFD);
4027 } else if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
4028 !isFriend && !isFunctionTemplateSpecialization &&
4029 !isExplicitSpecialization) {
4030 // An out-of-line member function declaration must also be a
4031 // definition (C++ [dcl.meaning]p1).
4032 // Note that this is not the case for explicit specializations of
4033 // function templates or member functions of class templates, per
4034 // C++ [temp.expl.spec]p2. We also allow these declarations as an extension
4035 // for compatibility with old SWIG code which likes to generate them.
4036 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
4037 << D.getCXXScopeSpec().getRange();
4042 // Handle attributes. We need to have merged decls when handling attributes
4043 // (for example to check for conflicts, etc).
4044 // FIXME: This needs to happen before we merge declarations. Then,
4045 // let attribute merging cope with attribute conflicts.
4046 ProcessDeclAttributes(S, NewFD, D,
4047 /*NonInheritable=*/false, /*Inheritable=*/true);
4049 // attributes declared post-definition are currently ignored
4050 // FIXME: This should happen during attribute merging
4051 if (Redeclaration && Previous.isSingleResult()) {
4052 const FunctionDecl *Def;
4053 FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
4054 if (PrevFD && PrevFD->hasBody(Def) && D.hasAttributes()) {
4055 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
4056 Diag(Def->getLocation(), diag::note_previous_definition);
4060 AddKnownFunctionAttributes(NewFD);
4062 if (NewFD->hasAttr<OverloadableAttr>() &&
4063 !NewFD->getType()->getAs<FunctionProtoType>()) {
4064 Diag(NewFD->getLocation(),
4065 diag::err_attribute_overloadable_no_prototype)
4066 << NewFD;
4068 // Turn this into a variadic function with no parameters.
4069 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
4070 FunctionProtoType::ExtProtoInfo EPI;
4071 EPI.Variadic = true;
4072 EPI.ExtInfo = FT->getExtInfo();
4074 QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI);
4075 NewFD->setType(R);
4078 // If there's a #pragma GCC visibility in scope, and this isn't a class
4079 // member, set the visibility of this function.
4080 if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
4081 AddPushedVisibilityAttribute(NewFD);
4083 // If this is a locally-scoped extern C function, update the
4084 // map of such names.
4085 if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
4086 && !NewFD->isInvalidDecl())
4087 RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
4089 // Set this FunctionDecl's range up to the right paren.
4090 NewFD->setLocEnd(D.getSourceRange().getEnd());
4092 if (getLangOptions().CPlusPlus) {
4093 if (FunctionTemplate) {
4094 if (NewFD->isInvalidDecl())
4095 FunctionTemplate->setInvalidDecl();
4096 return FunctionTemplate;
4100 MarkUnusedFileScopedDecl(NewFD);
4101 return NewFD;
4104 /// \brief Perform semantic checking of a new function declaration.
4106 /// Performs semantic analysis of the new function declaration
4107 /// NewFD. This routine performs all semantic checking that does not
4108 /// require the actual declarator involved in the declaration, and is
4109 /// used both for the declaration of functions as they are parsed
4110 /// (called via ActOnDeclarator) and for the declaration of functions
4111 /// that have been instantiated via C++ template instantiation (called
4112 /// via InstantiateDecl).
4114 /// \param IsExplicitSpecialiation whether this new function declaration is
4115 /// an explicit specialization of the previous declaration.
4117 /// This sets NewFD->isInvalidDecl() to true if there was an error.
4118 void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
4119 LookupResult &Previous,
4120 bool IsExplicitSpecialization,
4121 bool &Redeclaration) {
4122 // If NewFD is already known erroneous, don't do any of this checking.
4123 if (NewFD->isInvalidDecl()) {
4124 // If this is a class member, mark the class invalid immediately.
4125 // This avoids some consistency errors later.
4126 if (isa<CXXMethodDecl>(NewFD))
4127 cast<CXXMethodDecl>(NewFD)->getParent()->setInvalidDecl();
4129 return;
4132 if (NewFD->getResultType()->isVariablyModifiedType()) {
4133 // Functions returning a variably modified type violate C99 6.7.5.2p2
4134 // because all functions have linkage.
4135 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
4136 return NewFD->setInvalidDecl();
4139 if (NewFD->isMain())
4140 CheckMain(NewFD);
4142 // Check for a previous declaration of this name.
4143 if (Previous.empty() && NewFD->isExternC()) {
4144 // Since we did not find anything by this name and we're declaring
4145 // an extern "C" function, look for a non-visible extern "C"
4146 // declaration with the same name.
4147 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4148 = LocallyScopedExternalDecls.find(NewFD->getDeclName());
4149 if (Pos != LocallyScopedExternalDecls.end())
4150 Previous.addDecl(Pos->second);
4153 // Merge or overload the declaration with an existing declaration of
4154 // the same name, if appropriate.
4155 if (!Previous.empty()) {
4156 // Determine whether NewFD is an overload of PrevDecl or
4157 // a declaration that requires merging. If it's an overload,
4158 // there's no more work to do here; we'll just add the new
4159 // function to the scope.
4161 NamedDecl *OldDecl = 0;
4162 if (!AllowOverloadingOfFunction(Previous, Context)) {
4163 Redeclaration = true;
4164 OldDecl = Previous.getFoundDecl();
4165 } else {
4166 switch (CheckOverload(S, NewFD, Previous, OldDecl,
4167 /*NewIsUsingDecl*/ false)) {
4168 case Ovl_Match:
4169 Redeclaration = true;
4170 break;
4172 case Ovl_NonFunction:
4173 Redeclaration = true;
4174 break;
4176 case Ovl_Overload:
4177 Redeclaration = false;
4178 break;
4181 if (!getLangOptions().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
4182 // If a function name is overloadable in C, then every function
4183 // with that name must be marked "overloadable".
4184 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
4185 << Redeclaration << NewFD;
4186 NamedDecl *OverloadedDecl = 0;
4187 if (Redeclaration)
4188 OverloadedDecl = OldDecl;
4189 else if (!Previous.empty())
4190 OverloadedDecl = Previous.getRepresentativeDecl();
4191 if (OverloadedDecl)
4192 Diag(OverloadedDecl->getLocation(),
4193 diag::note_attribute_overloadable_prev_overload);
4194 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
4195 Context));
4199 if (Redeclaration) {
4200 // NewFD and OldDecl represent declarations that need to be
4201 // merged.
4202 if (MergeFunctionDecl(NewFD, OldDecl))
4203 return NewFD->setInvalidDecl();
4205 Previous.clear();
4206 Previous.addDecl(OldDecl);
4208 if (FunctionTemplateDecl *OldTemplateDecl
4209 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
4210 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
4211 FunctionTemplateDecl *NewTemplateDecl
4212 = NewFD->getDescribedFunctionTemplate();
4213 assert(NewTemplateDecl && "Template/non-template mismatch");
4214 if (CXXMethodDecl *Method
4215 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
4216 Method->setAccess(OldTemplateDecl->getAccess());
4217 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
4220 // If this is an explicit specialization of a member that is a function
4221 // template, mark it as a member specialization.
4222 if (IsExplicitSpecialization &&
4223 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
4224 NewTemplateDecl->setMemberSpecialization();
4225 assert(OldTemplateDecl->isMemberSpecialization());
4227 } else {
4228 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
4229 NewFD->setAccess(OldDecl->getAccess());
4230 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
4235 // Semantic checking for this function declaration (in isolation).
4236 if (getLangOptions().CPlusPlus) {
4237 // C++-specific checks.
4238 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
4239 CheckConstructor(Constructor);
4240 } else if (CXXDestructorDecl *Destructor =
4241 dyn_cast<CXXDestructorDecl>(NewFD)) {
4242 CXXRecordDecl *Record = Destructor->getParent();
4243 QualType ClassType = Context.getTypeDeclType(Record);
4245 // FIXME: Shouldn't we be able to perform this check even when the class
4246 // type is dependent? Both gcc and edg can handle that.
4247 if (!ClassType->isDependentType()) {
4248 DeclarationName Name
4249 = Context.DeclarationNames.getCXXDestructorName(
4250 Context.getCanonicalType(ClassType));
4251 if (NewFD->getDeclName() != Name) {
4252 Diag(NewFD->getLocation(), diag::err_destructor_name);
4253 return NewFD->setInvalidDecl();
4256 } else if (CXXConversionDecl *Conversion
4257 = dyn_cast<CXXConversionDecl>(NewFD)) {
4258 ActOnConversionDeclarator(Conversion);
4261 // Find any virtual functions that this function overrides.
4262 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
4263 if (!Method->isFunctionTemplateSpecialization() &&
4264 !Method->getDescribedFunctionTemplate()) {
4265 if (AddOverriddenMethods(Method->getParent(), Method)) {
4266 // If the function was marked as "static", we have a problem.
4267 if (NewFD->getStorageClass() == SC_Static) {
4268 Diag(NewFD->getLocation(), diag::err_static_overrides_virtual)
4269 << NewFD->getDeclName();
4270 for (CXXMethodDecl::method_iterator
4271 Overridden = Method->begin_overridden_methods(),
4272 OverriddenEnd = Method->end_overridden_methods();
4273 Overridden != OverriddenEnd;
4274 ++Overridden) {
4275 Diag((*Overridden)->getLocation(),
4276 diag::note_overridden_virtual_function);
4283 // Extra checking for C++ overloaded operators (C++ [over.oper]).
4284 if (NewFD->isOverloadedOperator() &&
4285 CheckOverloadedOperatorDeclaration(NewFD))
4286 return NewFD->setInvalidDecl();
4288 // Extra checking for C++0x literal operators (C++0x [over.literal]).
4289 if (NewFD->getLiteralIdentifier() &&
4290 CheckLiteralOperatorDeclaration(NewFD))
4291 return NewFD->setInvalidDecl();
4293 // In C++, check default arguments now that we have merged decls. Unless
4294 // the lexical context is the class, because in this case this is done
4295 // during delayed parsing anyway.
4296 if (!CurContext->isRecord())
4297 CheckCXXDefaultArguments(NewFD);
4299 // If this function declares a builtin function, check the type of this
4300 // declaration against the expected type for the builtin.
4301 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
4302 ASTContext::GetBuiltinTypeError Error;
4303 QualType T = Context.GetBuiltinType(BuiltinID, Error);
4304 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
4305 // The type of this function differs from the type of the builtin,
4306 // so forget about the builtin entirely.
4307 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
4313 void Sema::CheckMain(FunctionDecl* FD) {
4314 // C++ [basic.start.main]p3: A program that declares main to be inline
4315 // or static is ill-formed.
4316 // C99 6.7.4p4: In a hosted environment, the inline function specifier
4317 // shall not appear in a declaration of main.
4318 // static main is not an error under C99, but we should warn about it.
4319 bool isInline = FD->isInlineSpecified();
4320 bool isStatic = FD->getStorageClass() == SC_Static;
4321 if (isInline || isStatic) {
4322 unsigned diagID = diag::warn_unusual_main_decl;
4323 if (isInline || getLangOptions().CPlusPlus)
4324 diagID = diag::err_unusual_main_decl;
4326 int which = isStatic + (isInline << 1) - 1;
4327 Diag(FD->getLocation(), diagID) << which;
4330 QualType T = FD->getType();
4331 assert(T->isFunctionType() && "function decl is not of function type");
4332 const FunctionType* FT = T->getAs<FunctionType>();
4334 if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
4335 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
4336 TypeLoc TL = TSI->getTypeLoc().IgnoreParens();
4337 const SemaDiagnosticBuilder& D = Diag(FD->getTypeSpecStartLoc(),
4338 diag::err_main_returns_nonint);
4339 if (FunctionTypeLoc* PTL = dyn_cast<FunctionTypeLoc>(&TL)) {
4340 D << FixItHint::CreateReplacement(PTL->getResultLoc().getSourceRange(),
4341 "int");
4343 FD->setInvalidDecl(true);
4346 // Treat protoless main() as nullary.
4347 if (isa<FunctionNoProtoType>(FT)) return;
4349 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
4350 unsigned nparams = FTP->getNumArgs();
4351 assert(FD->getNumParams() == nparams);
4353 bool HasExtraParameters = (nparams > 3);
4355 // Darwin passes an undocumented fourth argument of type char**. If
4356 // other platforms start sprouting these, the logic below will start
4357 // getting shifty.
4358 if (nparams == 4 &&
4359 Context.Target.getTriple().getOS() == llvm::Triple::Darwin)
4360 HasExtraParameters = false;
4362 if (HasExtraParameters) {
4363 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
4364 FD->setInvalidDecl(true);
4365 nparams = 3;
4368 // FIXME: a lot of the following diagnostics would be improved
4369 // if we had some location information about types.
4371 QualType CharPP =
4372 Context.getPointerType(Context.getPointerType(Context.CharTy));
4373 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
4375 for (unsigned i = 0; i < nparams; ++i) {
4376 QualType AT = FTP->getArgType(i);
4378 bool mismatch = true;
4380 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
4381 mismatch = false;
4382 else if (Expected[i] == CharPP) {
4383 // As an extension, the following forms are okay:
4384 // char const **
4385 // char const * const *
4386 // char * const *
4388 QualifierCollector qs;
4389 const PointerType* PT;
4390 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
4391 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
4392 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
4393 qs.removeConst();
4394 mismatch = !qs.empty();
4398 if (mismatch) {
4399 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
4400 // TODO: suggest replacing given type with expected type
4401 FD->setInvalidDecl(true);
4405 if (nparams == 1 && !FD->isInvalidDecl()) {
4406 Diag(FD->getLocation(), diag::warn_main_one_arg);
4409 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
4410 Diag(FD->getLocation(), diag::err_main_template_decl);
4411 FD->setInvalidDecl();
4415 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
4416 // FIXME: Need strict checking. In C89, we need to check for
4417 // any assignment, increment, decrement, function-calls, or
4418 // commas outside of a sizeof. In C99, it's the same list,
4419 // except that the aforementioned are allowed in unevaluated
4420 // expressions. Everything else falls under the
4421 // "may accept other forms of constant expressions" exception.
4422 // (We never end up here for C++, so the constant expression
4423 // rules there don't matter.)
4424 if (Init->isConstantInitializer(Context, false))
4425 return false;
4426 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
4427 << Init->getSourceRange();
4428 return true;
4431 void Sema::AddInitializerToDecl(Decl *dcl, Expr *init) {
4432 AddInitializerToDecl(dcl, init, /*DirectInit=*/false);
4435 /// AddInitializerToDecl - Adds the initializer Init to the
4436 /// declaration dcl. If DirectInit is true, this is C++ direct
4437 /// initialization rather than copy initialization.
4438 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
4439 // If there is no declaration, there was an error parsing it. Just ignore
4440 // the initializer.
4441 if (RealDecl == 0)
4442 return;
4444 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
4445 // With declarators parsed the way they are, the parser cannot
4446 // distinguish between a normal initializer and a pure-specifier.
4447 // Thus this grotesque test.
4448 IntegerLiteral *IL;
4449 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
4450 Context.getCanonicalType(IL->getType()) == Context.IntTy)
4451 CheckPureMethod(Method, Init->getSourceRange());
4452 else {
4453 Diag(Method->getLocation(), diag::err_member_function_initialization)
4454 << Method->getDeclName() << Init->getSourceRange();
4455 Method->setInvalidDecl();
4457 return;
4460 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4461 if (!VDecl) {
4462 if (getLangOptions().CPlusPlus &&
4463 RealDecl->getLexicalDeclContext()->isRecord() &&
4464 isa<NamedDecl>(RealDecl))
4465 Diag(RealDecl->getLocation(), diag::err_member_initialization);
4466 else
4467 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4468 RealDecl->setInvalidDecl();
4469 return;
4474 // A definition must end up with a complete type, which means it must be
4475 // complete with the restriction that an array type might be completed by the
4476 // initializer; note that later code assumes this restriction.
4477 QualType BaseDeclType = VDecl->getType();
4478 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
4479 BaseDeclType = Array->getElementType();
4480 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
4481 diag::err_typecheck_decl_incomplete_type)) {
4482 RealDecl->setInvalidDecl();
4483 return;
4486 // The variable can not have an abstract class type.
4487 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4488 diag::err_abstract_type_in_decl,
4489 AbstractVariableType))
4490 VDecl->setInvalidDecl();
4492 const VarDecl *Def;
4493 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
4494 Diag(VDecl->getLocation(), diag::err_redefinition)
4495 << VDecl->getDeclName();
4496 Diag(Def->getLocation(), diag::note_previous_definition);
4497 VDecl->setInvalidDecl();
4498 return;
4501 const VarDecl* PrevInit = 0;
4502 if (getLangOptions().CPlusPlus) {
4503 // C++ [class.static.data]p4
4504 // If a static data member is of const integral or const
4505 // enumeration type, its declaration in the class definition can
4506 // specify a constant-initializer which shall be an integral
4507 // constant expression (5.19). In that case, the member can appear
4508 // in integral constant expressions. The member shall still be
4509 // defined in a namespace scope if it is used in the program and the
4510 // namespace scope definition shall not contain an initializer.
4512 // We already performed a redefinition check above, but for static
4513 // data members we also need to check whether there was an in-class
4514 // declaration with an initializer.
4515 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
4516 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
4517 Diag(PrevInit->getLocation(), diag::note_previous_definition);
4518 return;
4521 if (VDecl->hasLocalStorage())
4522 getCurFunction()->setHasBranchProtectedScope();
4524 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
4525 VDecl->setInvalidDecl();
4526 return;
4530 // Capture the variable that is being initialized and the style of
4531 // initialization.
4532 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4534 // FIXME: Poor source location information.
4535 InitializationKind Kind
4536 = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(),
4537 Init->getLocStart(),
4538 Init->getLocEnd())
4539 : InitializationKind::CreateCopy(VDecl->getLocation(),
4540 Init->getLocStart());
4542 // Get the decls type and save a reference for later, since
4543 // CheckInitializerTypes may change it.
4544 QualType DclT = VDecl->getType(), SavT = DclT;
4545 if (VDecl->isLocalVarDecl()) {
4546 if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
4547 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
4548 VDecl->setInvalidDecl();
4549 } else if (!VDecl->isInvalidDecl()) {
4550 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
4551 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
4552 MultiExprArg(*this, &Init, 1),
4553 &DclT);
4554 if (Result.isInvalid()) {
4555 VDecl->setInvalidDecl();
4556 return;
4559 Init = Result.takeAs<Expr>();
4561 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
4562 // Don't check invalid declarations to avoid emitting useless diagnostics.
4563 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
4564 if (VDecl->getStorageClass() == SC_Static) // C99 6.7.8p4.
4565 CheckForConstantInitializer(Init, DclT);
4568 } else if (VDecl->isStaticDataMember() &&
4569 VDecl->getLexicalDeclContext()->isRecord()) {
4570 // This is an in-class initialization for a static data member, e.g.,
4572 // struct S {
4573 // static const int value = 17;
4574 // };
4576 // Try to perform the initialization regardless.
4577 if (!VDecl->isInvalidDecl()) {
4578 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
4579 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
4580 MultiExprArg(*this, &Init, 1),
4581 &DclT);
4582 if (Result.isInvalid()) {
4583 VDecl->setInvalidDecl();
4584 return;
4587 Init = Result.takeAs<Expr>();
4590 // C++ [class.mem]p4:
4591 // A member-declarator can contain a constant-initializer only
4592 // if it declares a static member (9.4) of const integral or
4593 // const enumeration type, see 9.4.2.
4594 QualType T = VDecl->getType();
4596 // Do nothing on dependent types.
4597 if (T->isDependentType()) {
4599 // Require constness.
4600 } else if (!T.isConstQualified()) {
4601 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
4602 << Init->getSourceRange();
4603 VDecl->setInvalidDecl();
4605 // We allow integer constant expressions in all cases.
4606 } else if (T->isIntegralOrEnumerationType()) {
4607 if (!Init->isValueDependent()) {
4608 // Check whether the expression is a constant expression.
4609 llvm::APSInt Value;
4610 SourceLocation Loc;
4611 if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) {
4612 Diag(Loc, diag::err_in_class_initializer_non_constant)
4613 << Init->getSourceRange();
4614 VDecl->setInvalidDecl();
4618 // We allow floating-point constants as an extension in C++03, and
4619 // C++0x has far more complicated rules that we don't really
4620 // implement fully.
4621 } else {
4622 bool Allowed = false;
4623 if (getLangOptions().CPlusPlus0x) {
4624 Allowed = T->isLiteralType();
4625 } else if (T->isFloatingType()) { // also permits complex, which is ok
4626 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
4627 << T << Init->getSourceRange();
4628 Allowed = true;
4631 if (!Allowed) {
4632 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
4633 << T << Init->getSourceRange();
4634 VDecl->setInvalidDecl();
4636 // TODO: there are probably expressions that pass here that shouldn't.
4637 } else if (!Init->isValueDependent() &&
4638 !Init->isConstantInitializer(Context, false)) {
4639 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
4640 << Init->getSourceRange();
4641 VDecl->setInvalidDecl();
4644 } else if (VDecl->isFileVarDecl()) {
4645 if (VDecl->getStorageClassAsWritten() == SC_Extern &&
4646 (!getLangOptions().CPlusPlus ||
4647 !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
4648 Diag(VDecl->getLocation(), diag::warn_extern_init);
4649 if (!VDecl->isInvalidDecl()) {
4650 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
4651 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
4652 MultiExprArg(*this, &Init, 1),
4653 &DclT);
4654 if (Result.isInvalid()) {
4655 VDecl->setInvalidDecl();
4656 return;
4659 Init = Result.takeAs<Expr>();
4662 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
4663 // Don't check invalid declarations to avoid emitting useless diagnostics.
4664 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
4665 // C99 6.7.8p4. All file scoped initializers need to be constant.
4666 CheckForConstantInitializer(Init, DclT);
4669 // If the type changed, it means we had an incomplete type that was
4670 // completed by the initializer. For example:
4671 // int ary[] = { 1, 3, 5 };
4672 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
4673 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
4674 VDecl->setType(DclT);
4675 Init->setType(DclT);
4679 // If this variable is a local declaration with record type, make sure it
4680 // doesn't have a flexible member initialization. We only support this as a
4681 // global/static definition.
4682 if (VDecl->hasLocalStorage())
4683 if (const RecordType *RT = VDecl->getType()->getAs<RecordType>())
4684 if (RT->getDecl()->hasFlexibleArrayMember()) {
4685 // Check whether the initializer tries to initialize the flexible
4686 // array member itself to anything other than an empty initializer list.
4687 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
4688 unsigned Index = std::distance(RT->getDecl()->field_begin(),
4689 RT->getDecl()->field_end()) - 1;
4690 if (Index < ILE->getNumInits() &&
4691 !(isa<InitListExpr>(ILE->getInit(Index)) &&
4692 cast<InitListExpr>(ILE->getInit(Index))->getNumInits() == 0)) {
4693 Diag(VDecl->getLocation(), diag::err_nonstatic_flexible_variable);
4694 VDecl->setInvalidDecl();
4699 // Check any implicit conversions within the expression.
4700 CheckImplicitConversions(Init, VDecl->getLocation());
4702 Init = MaybeCreateExprWithCleanups(Init);
4703 // Attach the initializer to the decl.
4704 VDecl->setInit(Init);
4706 CheckCompleteVariableDeclaration(VDecl);
4709 /// ActOnInitializerError - Given that there was an error parsing an
4710 /// initializer for the given declaration, try to return to some form
4711 /// of sanity.
4712 void Sema::ActOnInitializerError(Decl *D) {
4713 // Our main concern here is re-establishing invariants like "a
4714 // variable's type is either dependent or complete".
4715 if (!D || D->isInvalidDecl()) return;
4717 VarDecl *VD = dyn_cast<VarDecl>(D);
4718 if (!VD) return;
4720 QualType Ty = VD->getType();
4721 if (Ty->isDependentType()) return;
4723 // Require a complete type.
4724 if (RequireCompleteType(VD->getLocation(),
4725 Context.getBaseElementType(Ty),
4726 diag::err_typecheck_decl_incomplete_type)) {
4727 VD->setInvalidDecl();
4728 return;
4731 // Require an abstract type.
4732 if (RequireNonAbstractType(VD->getLocation(), Ty,
4733 diag::err_abstract_type_in_decl,
4734 AbstractVariableType)) {
4735 VD->setInvalidDecl();
4736 return;
4739 // Don't bother complaining about constructors or destructors,
4740 // though.
4743 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
4744 bool TypeContainsUndeducedAuto) {
4745 // If there is no declaration, there was an error parsing it. Just ignore it.
4746 if (RealDecl == 0)
4747 return;
4749 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
4750 QualType Type = Var->getType();
4752 // C++0x [dcl.spec.auto]p3
4753 if (TypeContainsUndeducedAuto) {
4754 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
4755 << Var->getDeclName() << Type;
4756 Var->setInvalidDecl();
4757 return;
4760 switch (Var->isThisDeclarationADefinition()) {
4761 case VarDecl::Definition:
4762 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
4763 break;
4765 // We have an out-of-line definition of a static data member
4766 // that has an in-class initializer, so we type-check this like
4767 // a declaration.
4769 // Fall through
4771 case VarDecl::DeclarationOnly:
4772 // It's only a declaration.
4774 // Block scope. C99 6.7p7: If an identifier for an object is
4775 // declared with no linkage (C99 6.2.2p6), the type for the
4776 // object shall be complete.
4777 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
4778 !Var->getLinkage() && !Var->isInvalidDecl() &&
4779 RequireCompleteType(Var->getLocation(), Type,
4780 diag::err_typecheck_decl_incomplete_type))
4781 Var->setInvalidDecl();
4783 // Make sure that the type is not abstract.
4784 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
4785 RequireNonAbstractType(Var->getLocation(), Type,
4786 diag::err_abstract_type_in_decl,
4787 AbstractVariableType))
4788 Var->setInvalidDecl();
4789 return;
4791 case VarDecl::TentativeDefinition:
4792 // File scope. C99 6.9.2p2: A declaration of an identifier for an
4793 // object that has file scope without an initializer, and without a
4794 // storage-class specifier or with the storage-class specifier "static",
4795 // constitutes a tentative definition. Note: A tentative definition with
4796 // external linkage is valid (C99 6.2.2p5).
4797 if (!Var->isInvalidDecl()) {
4798 if (const IncompleteArrayType *ArrayT
4799 = Context.getAsIncompleteArrayType(Type)) {
4800 if (RequireCompleteType(Var->getLocation(),
4801 ArrayT->getElementType(),
4802 diag::err_illegal_decl_array_incomplete_type))
4803 Var->setInvalidDecl();
4804 } else if (Var->getStorageClass() == SC_Static) {
4805 // C99 6.9.2p3: If the declaration of an identifier for an object is
4806 // a tentative definition and has internal linkage (C99 6.2.2p3), the
4807 // declared type shall not be an incomplete type.
4808 // NOTE: code such as the following
4809 // static struct s;
4810 // struct s { int a; };
4811 // is accepted by gcc. Hence here we issue a warning instead of
4812 // an error and we do not invalidate the static declaration.
4813 // NOTE: to avoid multiple warnings, only check the first declaration.
4814 if (Var->getPreviousDeclaration() == 0)
4815 RequireCompleteType(Var->getLocation(), Type,
4816 diag::ext_typecheck_decl_incomplete_type);
4820 // Record the tentative definition; we're done.
4821 if (!Var->isInvalidDecl())
4822 TentativeDefinitions.push_back(Var);
4823 return;
4826 // Provide a specific diagnostic for uninitialized variable
4827 // definitions with incomplete array type.
4828 if (Type->isIncompleteArrayType()) {
4829 Diag(Var->getLocation(),
4830 diag::err_typecheck_incomplete_array_needs_initializer);
4831 Var->setInvalidDecl();
4832 return;
4835 // Provide a specific diagnostic for uninitialized variable
4836 // definitions with reference type.
4837 if (Type->isReferenceType()) {
4838 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
4839 << Var->getDeclName()
4840 << SourceRange(Var->getLocation(), Var->getLocation());
4841 Var->setInvalidDecl();
4842 return;
4845 // Do not attempt to type-check the default initializer for a
4846 // variable with dependent type.
4847 if (Type->isDependentType())
4848 return;
4850 if (Var->isInvalidDecl())
4851 return;
4853 if (RequireCompleteType(Var->getLocation(),
4854 Context.getBaseElementType(Type),
4855 diag::err_typecheck_decl_incomplete_type)) {
4856 Var->setInvalidDecl();
4857 return;
4860 // The variable can not have an abstract class type.
4861 if (RequireNonAbstractType(Var->getLocation(), Type,
4862 diag::err_abstract_type_in_decl,
4863 AbstractVariableType)) {
4864 Var->setInvalidDecl();
4865 return;
4868 const RecordType *Record
4869 = Context.getBaseElementType(Type)->getAs<RecordType>();
4870 if (Record && getLangOptions().CPlusPlus && !getLangOptions().CPlusPlus0x &&
4871 cast<CXXRecordDecl>(Record->getDecl())->isPOD()) {
4872 // C++03 [dcl.init]p9:
4873 // If no initializer is specified for an object, and the
4874 // object is of (possibly cv-qualified) non-POD class type (or
4875 // array thereof), the object shall be default-initialized; if
4876 // the object is of const-qualified type, the underlying class
4877 // type shall have a user-declared default
4878 // constructor. Otherwise, if no initializer is specified for
4879 // a non- static object, the object and its subobjects, if
4880 // any, have an indeterminate initial value); if the object
4881 // or any of its subobjects are of const-qualified type, the
4882 // program is ill-formed.
4883 // FIXME: DPG thinks it is very fishy that C++0x disables this.
4884 } else {
4885 // Check for jumps past the implicit initializer. C++0x
4886 // clarifies that this applies to a "variable with automatic
4887 // storage duration", not a "local variable".
4888 if (getLangOptions().CPlusPlus && Var->hasLocalStorage())
4889 getCurFunction()->setHasBranchProtectedScope();
4891 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
4892 InitializationKind Kind
4893 = InitializationKind::CreateDefault(Var->getLocation());
4895 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
4896 ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
4897 MultiExprArg(*this, 0, 0));
4898 if (Init.isInvalid())
4899 Var->setInvalidDecl();
4900 else if (Init.get())
4901 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
4904 CheckCompleteVariableDeclaration(Var);
4908 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
4909 if (var->isInvalidDecl()) return;
4911 // All the following checks are C++ only.
4912 if (!getLangOptions().CPlusPlus) return;
4914 QualType baseType = Context.getBaseElementType(var->getType());
4915 if (baseType->isDependentType()) return;
4917 // __block variables might require us to capture a copy-initializer.
4918 if (var->hasAttr<BlocksAttr>()) {
4919 // It's currently invalid to ever have a __block variable with an
4920 // array type; should we diagnose that here?
4922 // Regardless, we don't want to ignore array nesting when
4923 // constructing this copy.
4924 QualType type = var->getType();
4926 if (type->isStructureOrClassType()) {
4927 SourceLocation poi = var->getLocation();
4928 Expr *varRef = new (Context) DeclRefExpr(var, type, VK_LValue, poi);
4929 ExprResult result =
4930 PerformCopyInitialization(
4931 InitializedEntity::InitializeBlock(poi, type, false),
4932 poi, Owned(varRef));
4933 if (!result.isInvalid()) {
4934 result = MaybeCreateExprWithCleanups(result);
4935 Expr *init = result.takeAs<Expr>();
4936 Context.setBlockVarCopyInits(var, init);
4941 // Check for global constructors.
4942 if (!var->getDeclContext()->isDependentContext() &&
4943 var->hasGlobalStorage() &&
4944 !var->isStaticLocal() &&
4945 var->getInit() &&
4946 !var->getInit()->isConstantInitializer(Context,
4947 baseType->isReferenceType()))
4948 Diag(var->getLocation(), diag::warn_global_constructor)
4949 << var->getInit()->getSourceRange();
4951 // Require the destructor.
4952 if (const RecordType *recordType = baseType->getAs<RecordType>())
4953 FinalizeVarWithDestructor(var, recordType);
4956 Sema::DeclGroupPtrTy
4957 Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
4958 Decl **Group, unsigned NumDecls) {
4959 llvm::SmallVector<Decl*, 8> Decls;
4961 if (DS.isTypeSpecOwned())
4962 Decls.push_back(DS.getRepAsDecl());
4964 for (unsigned i = 0; i != NumDecls; ++i)
4965 if (Decl *D = Group[i])
4966 Decls.push_back(D);
4968 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context,
4969 Decls.data(), Decls.size()));
4973 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
4974 /// to introduce parameters into function prototype scope.
4975 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
4976 const DeclSpec &DS = D.getDeclSpec();
4978 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
4979 VarDecl::StorageClass StorageClass = SC_None;
4980 VarDecl::StorageClass StorageClassAsWritten = SC_None;
4981 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
4982 StorageClass = SC_Register;
4983 StorageClassAsWritten = SC_Register;
4984 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
4985 Diag(DS.getStorageClassSpecLoc(),
4986 diag::err_invalid_storage_class_in_func_decl);
4987 D.getMutableDeclSpec().ClearStorageClassSpecs();
4990 if (D.getDeclSpec().isThreadSpecified())
4991 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4993 DiagnoseFunctionSpecifiers(D);
4995 TagDecl *OwnedDecl = 0;
4996 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedDecl);
4997 QualType parmDeclType = TInfo->getType();
4999 if (getLangOptions().CPlusPlus) {
5000 // Check that there are no default arguments inside the type of this
5001 // parameter.
5002 CheckExtraCXXDefaultArguments(D);
5004 if (OwnedDecl && OwnedDecl->isDefinition()) {
5005 // C++ [dcl.fct]p6:
5006 // Types shall not be defined in return or parameter types.
5007 Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
5008 << Context.getTypeDeclType(OwnedDecl);
5011 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
5012 if (D.getCXXScopeSpec().isSet()) {
5013 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
5014 << D.getCXXScopeSpec().getRange();
5015 D.getCXXScopeSpec().clear();
5019 // Ensure we have a valid name
5020 IdentifierInfo *II = 0;
5021 if (D.hasName()) {
5022 II = D.getIdentifier();
5023 if (!II) {
5024 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
5025 << GetNameForDeclarator(D).getName().getAsString();
5026 D.setInvalidType(true);
5030 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
5031 if (II) {
5032 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
5033 ForRedeclaration);
5034 LookupName(R, S);
5035 if (R.isSingleResult()) {
5036 NamedDecl *PrevDecl = R.getFoundDecl();
5037 if (PrevDecl->isTemplateParameter()) {
5038 // Maybe we will complain about the shadowed template parameter.
5039 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5040 // Just pretend that we didn't see the previous declaration.
5041 PrevDecl = 0;
5042 } else if (S->isDeclScope(PrevDecl)) {
5043 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
5044 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5046 // Recover by removing the name
5047 II = 0;
5048 D.SetIdentifier(0, D.getIdentifierLoc());
5049 D.setInvalidType(true);
5054 // Temporarily put parameter variables in the translation unit, not
5055 // the enclosing context. This prevents them from accidentally
5056 // looking like class members in C++.
5057 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
5058 TInfo, parmDeclType, II,
5059 D.getIdentifierLoc(),
5060 StorageClass, StorageClassAsWritten);
5062 if (D.isInvalidType())
5063 New->setInvalidDecl();
5065 // Add the parameter declaration into this scope.
5066 S->AddDecl(New);
5067 if (II)
5068 IdResolver.AddDecl(New);
5070 ProcessDeclAttributes(S, New, D);
5072 if (New->hasAttr<BlocksAttr>()) {
5073 Diag(New->getLocation(), diag::err_block_on_nonlocal);
5075 return New;
5078 /// \brief Synthesizes a variable for a parameter arising from a
5079 /// typedef.
5080 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
5081 SourceLocation Loc,
5082 QualType T) {
5083 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, 0,
5084 T, Context.getTrivialTypeSourceInfo(T, Loc),
5085 SC_None, SC_None, 0);
5086 Param->setImplicit();
5087 return Param;
5090 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
5091 ParmVarDecl * const *ParamEnd) {
5092 // Don't diagnose unused-parameter errors in template instantiations; we
5093 // will already have done so in the template itself.
5094 if (!ActiveTemplateInstantiations.empty())
5095 return;
5097 for (; Param != ParamEnd; ++Param) {
5098 if (!(*Param)->isUsed() && (*Param)->getDeclName() &&
5099 !(*Param)->hasAttr<UnusedAttr>()) {
5100 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
5101 << (*Param)->getDeclName();
5106 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
5107 ParmVarDecl * const *ParamEnd,
5108 QualType ReturnTy,
5109 NamedDecl *D) {
5110 if (LangOpts.NumLargeByValueCopy == 0) // No check.
5111 return;
5113 // Warn if the return value is pass-by-value and larger than the specified
5114 // threshold.
5115 if (ReturnTy->isPODType()) {
5116 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
5117 if (Size > LangOpts.NumLargeByValueCopy)
5118 Diag(D->getLocation(), diag::warn_return_value_size)
5119 << D->getDeclName() << Size;
5122 // Warn if any parameter is pass-by-value and larger than the specified
5123 // threshold.
5124 for (; Param != ParamEnd; ++Param) {
5125 QualType T = (*Param)->getType();
5126 if (!T->isPODType())
5127 continue;
5128 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
5129 if (Size > LangOpts.NumLargeByValueCopy)
5130 Diag((*Param)->getLocation(), diag::warn_parameter_size)
5131 << (*Param)->getDeclName() << Size;
5135 ParmVarDecl *Sema::CheckParameter(DeclContext *DC,
5136 TypeSourceInfo *TSInfo, QualType T,
5137 IdentifierInfo *Name,
5138 SourceLocation NameLoc,
5139 VarDecl::StorageClass StorageClass,
5140 VarDecl::StorageClass StorageClassAsWritten) {
5141 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, NameLoc, Name,
5142 adjustParameterType(T), TSInfo,
5143 StorageClass, StorageClassAsWritten,
5146 // Parameters can not be abstract class types.
5147 // For record types, this is done by the AbstractClassUsageDiagnoser once
5148 // the class has been completely parsed.
5149 if (!CurContext->isRecord() &&
5150 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
5151 AbstractParamType))
5152 New->setInvalidDecl();
5154 // Parameter declarators cannot be interface types. All ObjC objects are
5155 // passed by reference.
5156 if (T->isObjCObjectType()) {
5157 Diag(NameLoc,
5158 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
5159 New->setInvalidDecl();
5162 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
5163 // duration shall not be qualified by an address-space qualifier."
5164 // Since all parameters have automatic store duration, they can not have
5165 // an address space.
5166 if (T.getAddressSpace() != 0) {
5167 Diag(NameLoc, diag::err_arg_with_address_space);
5168 New->setInvalidDecl();
5171 return New;
5174 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
5175 SourceLocation LocAfterDecls) {
5176 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5178 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
5179 // for a K&R function.
5180 if (!FTI.hasPrototype) {
5181 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
5182 --i;
5183 if (FTI.ArgInfo[i].Param == 0) {
5184 llvm::SmallString<256> Code;
5185 llvm::raw_svector_ostream(Code) << " int "
5186 << FTI.ArgInfo[i].Ident->getName()
5187 << ";\n";
5188 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
5189 << FTI.ArgInfo[i].Ident
5190 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
5192 // Implicitly declare the argument as type 'int' for lack of a better
5193 // type.
5194 DeclSpec DS;
5195 const char* PrevSpec; // unused
5196 unsigned DiagID; // unused
5197 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
5198 PrevSpec, DiagID);
5199 Declarator ParamD(DS, Declarator::KNRTypeListContext);
5200 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
5201 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
5207 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
5208 Declarator &D) {
5209 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
5210 assert(D.isFunctionDeclarator() && "Not a function declarator!");
5211 Scope *ParentScope = FnBodyScope->getParent();
5213 Decl *DP = HandleDeclarator(ParentScope, D,
5214 MultiTemplateParamsArg(*this),
5215 /*IsFunctionDefinition=*/true);
5216 return ActOnStartOfFunctionDef(FnBodyScope, DP);
5219 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
5220 // Don't warn about invalid declarations.
5221 if (FD->isInvalidDecl())
5222 return false;
5224 // Or declarations that aren't global.
5225 if (!FD->isGlobal())
5226 return false;
5228 // Don't warn about C++ member functions.
5229 if (isa<CXXMethodDecl>(FD))
5230 return false;
5232 // Don't warn about 'main'.
5233 if (FD->isMain())
5234 return false;
5236 // Don't warn about inline functions.
5237 if (FD->isInlineSpecified())
5238 return false;
5240 // Don't warn about function templates.
5241 if (FD->getDescribedFunctionTemplate())
5242 return false;
5244 // Don't warn about function template specializations.
5245 if (FD->isFunctionTemplateSpecialization())
5246 return false;
5248 bool MissingPrototype = true;
5249 for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
5250 Prev; Prev = Prev->getPreviousDeclaration()) {
5251 // Ignore any declarations that occur in function or method
5252 // scope, because they aren't visible from the header.
5253 if (Prev->getDeclContext()->isFunctionOrMethod())
5254 continue;
5256 MissingPrototype = !Prev->getType()->isFunctionProtoType();
5257 break;
5260 return MissingPrototype;
5263 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
5264 // Clear the last template instantiation error context.
5265 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
5267 if (!D)
5268 return D;
5269 FunctionDecl *FD = 0;
5271 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
5272 FD = FunTmpl->getTemplatedDecl();
5273 else
5274 FD = cast<FunctionDecl>(D);
5276 // Enter a new function scope
5277 PushFunctionScope();
5279 // See if this is a redefinition.
5280 // But don't complain if we're in GNU89 mode and the previous definition
5281 // was an extern inline function.
5282 const FunctionDecl *Definition;
5283 if (FD->hasBody(Definition) &&
5284 !canRedefineFunction(Definition, getLangOptions())) {
5285 if (getLangOptions().GNUMode && Definition->isInlineSpecified() &&
5286 Definition->getStorageClass() == SC_Extern)
5287 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
5288 << FD->getDeclName() << getLangOptions().CPlusPlus;
5289 else
5290 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
5291 Diag(Definition->getLocation(), diag::note_previous_definition);
5294 // Builtin functions cannot be defined.
5295 if (unsigned BuiltinID = FD->getBuiltinID()) {
5296 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
5297 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
5298 FD->setInvalidDecl();
5302 // The return type of a function definition must be complete
5303 // (C99 6.9.1p3, C++ [dcl.fct]p6).
5304 QualType ResultType = FD->getResultType();
5305 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
5306 !FD->isInvalidDecl() &&
5307 RequireCompleteType(FD->getLocation(), ResultType,
5308 diag::err_func_def_incomplete_result))
5309 FD->setInvalidDecl();
5311 // GNU warning -Wmissing-prototypes:
5312 // Warn if a global function is defined without a previous
5313 // prototype declaration. This warning is issued even if the
5314 // definition itself provides a prototype. The aim is to detect
5315 // global functions that fail to be declared in header files.
5316 if (ShouldWarnAboutMissingPrototype(FD))
5317 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
5319 if (FnBodyScope)
5320 PushDeclContext(FnBodyScope, FD);
5322 // Check the validity of our function parameters
5323 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
5324 /*CheckParameterNames=*/true);
5326 // Introduce our parameters into the function scope
5327 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
5328 ParmVarDecl *Param = FD->getParamDecl(p);
5329 Param->setOwningFunction(FD);
5331 // If this has an identifier, add it to the scope stack.
5332 if (Param->getIdentifier() && FnBodyScope) {
5333 CheckShadow(FnBodyScope, Param);
5335 PushOnScopeChains(Param, FnBodyScope);
5339 // Checking attributes of current function definition
5340 // dllimport attribute.
5341 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
5342 if (DA && (!FD->getAttr<DLLExportAttr>())) {
5343 // dllimport attribute cannot be directly applied to definition.
5344 if (!DA->isInherited()) {
5345 Diag(FD->getLocation(),
5346 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
5347 << "dllimport";
5348 FD->setInvalidDecl();
5349 return FD;
5352 // Visual C++ appears to not think this is an issue, so only issue
5353 // a warning when Microsoft extensions are disabled.
5354 if (!LangOpts.Microsoft) {
5355 // If a symbol previously declared dllimport is later defined, the
5356 // attribute is ignored in subsequent references, and a warning is
5357 // emitted.
5358 Diag(FD->getLocation(),
5359 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5360 << FD->getName() << "dllimport";
5363 return FD;
5366 /// \brief Given the set of return statements within a function body,
5367 /// compute the variables that are subject to the named return value
5368 /// optimization.
5370 /// Each of the variables that is subject to the named return value
5371 /// optimization will be marked as NRVO variables in the AST, and any
5372 /// return statement that has a marked NRVO variable as its NRVO candidate can
5373 /// use the named return value optimization.
5375 /// This function applies a very simplistic algorithm for NRVO: if every return
5376 /// statement in the function has the same NRVO candidate, that candidate is
5377 /// the NRVO variable.
5379 /// FIXME: Employ a smarter algorithm that accounts for multiple return
5380 /// statements and the lifetimes of the NRVO candidates. We should be able to
5381 /// find a maximal set of NRVO variables.
5382 static void ComputeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
5383 ReturnStmt **Returns = Scope->Returns.data();
5385 const VarDecl *NRVOCandidate = 0;
5386 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
5387 if (!Returns[I]->getNRVOCandidate())
5388 return;
5390 if (!NRVOCandidate)
5391 NRVOCandidate = Returns[I]->getNRVOCandidate();
5392 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
5393 return;
5396 if (NRVOCandidate)
5397 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
5400 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
5401 return ActOnFinishFunctionBody(D, move(BodyArg), false);
5404 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
5405 bool IsInstantiation) {
5406 FunctionDecl *FD = 0;
5407 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
5408 if (FunTmpl)
5409 FD = FunTmpl->getTemplatedDecl();
5410 else
5411 FD = dyn_cast_or_null<FunctionDecl>(dcl);
5413 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
5415 if (FD) {
5416 FD->setBody(Body);
5417 if (FD->isMain()) {
5418 // C and C++ allow for main to automagically return 0.
5419 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
5420 FD->setHasImplicitReturnZero(true);
5421 WP.disableCheckFallThrough();
5424 if (!FD->isInvalidDecl()) {
5425 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
5426 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
5427 FD->getResultType(), FD);
5429 // If this is a constructor, we need a vtable.
5430 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
5431 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
5433 ComputeNRVO(Body, getCurFunction());
5436 assert(FD == getCurFunctionDecl() && "Function parsing confused");
5437 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
5438 assert(MD == getCurMethodDecl() && "Method parsing confused");
5439 MD->setBody(Body);
5440 if (Body)
5441 MD->setEndLoc(Body->getLocEnd());
5442 if (!MD->isInvalidDecl()) {
5443 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
5444 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
5445 MD->getResultType(), MD);
5447 } else {
5448 return 0;
5451 // Verify and clean out per-function state.
5453 // Check goto/label use.
5454 FunctionScopeInfo *CurFn = getCurFunction();
5455 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
5456 I = CurFn->LabelMap.begin(), E = CurFn->LabelMap.end(); I != E; ++I) {
5457 LabelStmt *L = I->second;
5459 // Verify that we have no forward references left. If so, there was a goto
5460 // or address of a label taken, but no definition of it. Label fwd
5461 // definitions are indicated with a null substmt.
5462 if (L->getSubStmt() != 0) {
5463 if (!L->isUsed())
5464 Diag(L->getIdentLoc(), diag::warn_unused_label) << L->getName();
5465 continue;
5468 // Emit error.
5469 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
5471 // At this point, we have gotos that use the bogus label. Stitch it into
5472 // the function body so that they aren't leaked and that the AST is well
5473 // formed.
5474 if (Body == 0) {
5475 // The whole function wasn't parsed correctly.
5476 continue;
5479 // Otherwise, the body is valid: we want to stitch the label decl into the
5480 // function somewhere so that it is properly owned and so that the goto
5481 // has a valid target. Do this by creating a new compound stmt with the
5482 // label in it.
5484 // Give the label a sub-statement.
5485 L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
5487 CompoundStmt *Compound = isa<CXXTryStmt>(Body) ?
5488 cast<CXXTryStmt>(Body)->getTryBlock() :
5489 cast<CompoundStmt>(Body);
5490 llvm::SmallVector<Stmt*, 64> Elements(Compound->body_begin(),
5491 Compound->body_end());
5492 Elements.push_back(L);
5493 Compound->setStmts(Context, Elements.data(), Elements.size());
5496 if (Body) {
5497 // C++ constructors that have function-try-blocks can't have return
5498 // statements in the handlers of that block. (C++ [except.handle]p14)
5499 // Verify this.
5500 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
5501 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
5503 // Verify that that gotos and switch cases don't jump into scopes illegally.
5504 // Verify that that gotos and switch cases don't jump into scopes illegally.
5505 if (getCurFunction()->NeedsScopeChecking() &&
5506 !dcl->isInvalidDecl() &&
5507 !hasAnyErrorsInThisFunction())
5508 DiagnoseInvalidJumps(Body);
5510 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
5511 if (!Destructor->getParent()->isDependentType())
5512 CheckDestructor(Destructor);
5514 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
5515 Destructor->getParent());
5518 // If any errors have occurred, clear out any temporaries that may have
5519 // been leftover. This ensures that these temporaries won't be picked up for
5520 // deletion in some later function.
5521 if (PP.getDiagnostics().hasErrorOccurred())
5522 ExprTemporaries.clear();
5523 else if (!isa<FunctionTemplateDecl>(dcl)) {
5524 // Since the body is valid, issue any analysis-based warnings that are
5525 // enabled.
5526 QualType ResultType;
5527 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
5528 AnalysisWarnings.IssueWarnings(WP, FD);
5529 } else {
5530 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(dcl);
5531 AnalysisWarnings.IssueWarnings(WP, MD);
5535 assert(ExprTemporaries.empty() && "Leftover temporaries in function");
5538 if (!IsInstantiation)
5539 PopDeclContext();
5541 PopFunctionOrBlockScope();
5543 // If any errors have occurred, clear out any temporaries that may have
5544 // been leftover. This ensures that these temporaries won't be picked up for
5545 // deletion in some later function.
5546 if (getDiagnostics().hasErrorOccurred())
5547 ExprTemporaries.clear();
5549 return dcl;
5552 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
5553 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
5554 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
5555 IdentifierInfo &II, Scope *S) {
5556 // Before we produce a declaration for an implicitly defined
5557 // function, see whether there was a locally-scoped declaration of
5558 // this name as a function or variable. If so, use that
5559 // (non-visible) declaration, and complain about it.
5560 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
5561 = LocallyScopedExternalDecls.find(&II);
5562 if (Pos != LocallyScopedExternalDecls.end()) {
5563 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
5564 Diag(Pos->second->getLocation(), diag::note_previous_declaration);
5565 return Pos->second;
5568 // Extension in C99. Legal in C90, but warn about it.
5569 if (II.getName().startswith("__builtin_"))
5570 Diag(Loc, diag::warn_builtin_unknown) << &II;
5571 else if (getLangOptions().C99)
5572 Diag(Loc, diag::ext_implicit_function_decl) << &II;
5573 else
5574 Diag(Loc, diag::warn_implicit_function_decl) << &II;
5576 // Set a Declarator for the implicit definition: int foo();
5577 const char *Dummy;
5578 DeclSpec DS;
5579 unsigned DiagID;
5580 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
5581 (void)Error; // Silence warning.
5582 assert(!Error && "Error setting up implicit decl!");
5583 Declarator D(DS, Declarator::BlockContext);
5584 D.AddTypeInfo(DeclaratorChunk::getFunction(ParsedAttributes(),
5585 false, false, SourceLocation(), 0,
5586 0, 0, true, SourceLocation(),
5587 false, SourceLocation(),
5588 false, 0,0,0, Loc, Loc, D),
5589 SourceLocation());
5590 D.SetIdentifier(&II, Loc);
5592 // Insert this function into translation-unit scope.
5594 DeclContext *PrevDC = CurContext;
5595 CurContext = Context.getTranslationUnitDecl();
5597 FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
5598 FD->setImplicit();
5600 CurContext = PrevDC;
5602 AddKnownFunctionAttributes(FD);
5604 return FD;
5607 /// \brief Adds any function attributes that we know a priori based on
5608 /// the declaration of this function.
5610 /// These attributes can apply both to implicitly-declared builtins
5611 /// (like __builtin___printf_chk) or to library-declared functions
5612 /// like NSLog or printf.
5613 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
5614 if (FD->isInvalidDecl())
5615 return;
5617 // If this is a built-in function, map its builtin attributes to
5618 // actual attributes.
5619 if (unsigned BuiltinID = FD->getBuiltinID()) {
5620 // Handle printf-formatting attributes.
5621 unsigned FormatIdx;
5622 bool HasVAListArg;
5623 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
5624 if (!FD->getAttr<FormatAttr>())
5625 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
5626 "printf", FormatIdx+1,
5627 HasVAListArg ? 0 : FormatIdx+2));
5629 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
5630 HasVAListArg)) {
5631 if (!FD->getAttr<FormatAttr>())
5632 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
5633 "scanf", FormatIdx+1,
5634 HasVAListArg ? 0 : FormatIdx+2));
5637 // Mark const if we don't care about errno and that is the only
5638 // thing preventing the function from being const. This allows
5639 // IRgen to use LLVM intrinsics for such functions.
5640 if (!getLangOptions().MathErrno &&
5641 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
5642 if (!FD->getAttr<ConstAttr>())
5643 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
5646 if (Context.BuiltinInfo.isNoThrow(BuiltinID))
5647 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
5648 if (Context.BuiltinInfo.isConst(BuiltinID))
5649 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
5652 IdentifierInfo *Name = FD->getIdentifier();
5653 if (!Name)
5654 return;
5655 if ((!getLangOptions().CPlusPlus &&
5656 FD->getDeclContext()->isTranslationUnit()) ||
5657 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
5658 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
5659 LinkageSpecDecl::lang_c)) {
5660 // Okay: this could be a libc/libm/Objective-C function we know
5661 // about.
5662 } else
5663 return;
5665 if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
5666 // FIXME: NSLog and NSLogv should be target specific
5667 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
5668 // FIXME: We known better than our headers.
5669 const_cast<FormatAttr *>(Format)->setType(Context, "printf");
5670 } else
5671 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
5672 "printf", 1,
5673 Name->isStr("NSLogv") ? 0 : 2));
5674 } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
5675 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
5676 // target-specific builtins, perhaps?
5677 if (!FD->getAttr<FormatAttr>())
5678 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
5679 "printf", 2,
5680 Name->isStr("vasprintf") ? 0 : 3));
5684 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
5685 TypeSourceInfo *TInfo) {
5686 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
5687 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
5689 if (!TInfo) {
5690 assert(D.isInvalidType() && "no declarator info for valid type");
5691 TInfo = Context.getTrivialTypeSourceInfo(T);
5694 // Scope manipulation handled by caller.
5695 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
5696 D.getIdentifierLoc(),
5697 D.getIdentifier(),
5698 TInfo);
5700 if (const TagType *TT = T->getAs<TagType>()) {
5701 TagDecl *TD = TT->getDecl();
5703 // If the TagDecl that the TypedefDecl points to is an anonymous decl
5704 // keep track of the TypedefDecl.
5705 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
5706 TD->setTypedefForAnonDecl(NewTD);
5709 if (D.isInvalidType())
5710 NewTD->setInvalidDecl();
5711 return NewTD;
5715 /// \brief Determine whether a tag with a given kind is acceptable
5716 /// as a redeclaration of the given tag declaration.
5718 /// \returns true if the new tag kind is acceptable, false otherwise.
5719 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
5720 TagTypeKind NewTag,
5721 SourceLocation NewTagLoc,
5722 const IdentifierInfo &Name) {
5723 // C++ [dcl.type.elab]p3:
5724 // The class-key or enum keyword present in the
5725 // elaborated-type-specifier shall agree in kind with the
5726 // declaration to which the name in the elaborated-type-specifier
5727 // refers. This rule also applies to the form of
5728 // elaborated-type-specifier that declares a class-name or
5729 // friend class since it can be construed as referring to the
5730 // definition of the class. Thus, in any
5731 // elaborated-type-specifier, the enum keyword shall be used to
5732 // refer to an enumeration (7.2), the union class-key shall be
5733 // used to refer to a union (clause 9), and either the class or
5734 // struct class-key shall be used to refer to a class (clause 9)
5735 // declared using the class or struct class-key.
5736 TagTypeKind OldTag = Previous->getTagKind();
5737 if (OldTag == NewTag)
5738 return true;
5740 if ((OldTag == TTK_Struct || OldTag == TTK_Class) &&
5741 (NewTag == TTK_Struct || NewTag == TTK_Class)) {
5742 // Warn about the struct/class tag mismatch.
5743 bool isTemplate = false;
5744 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
5745 isTemplate = Record->getDescribedClassTemplate();
5747 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
5748 << (NewTag == TTK_Class)
5749 << isTemplate << &Name
5750 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
5751 OldTag == TTK_Class? "class" : "struct");
5752 Diag(Previous->getLocation(), diag::note_previous_use);
5753 return true;
5755 return false;
5758 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
5759 /// former case, Name will be non-null. In the later case, Name will be null.
5760 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
5761 /// reference/declaration/definition of a tag.
5762 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5763 SourceLocation KWLoc, CXXScopeSpec &SS,
5764 IdentifierInfo *Name, SourceLocation NameLoc,
5765 AttributeList *Attr, AccessSpecifier AS,
5766 MultiTemplateParamsArg TemplateParameterLists,
5767 bool &OwnedDecl, bool &IsDependent,
5768 bool ScopedEnum, bool ScopedEnumUsesClassTag,
5769 TypeResult UnderlyingType) {
5770 // If this is not a definition, it must have a name.
5771 assert((Name != 0 || TUK == TUK_Definition) &&
5772 "Nameless record must be a definition!");
5773 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
5775 OwnedDecl = false;
5776 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5778 // FIXME: Check explicit specializations more carefully.
5779 bool isExplicitSpecialization = false;
5780 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
5781 bool Invalid = false;
5783 // We only need to do this matching if we have template parameters
5784 // or a scope specifier, which also conveniently avoids this work
5785 // for non-C++ cases.
5786 if (NumMatchedTemplateParamLists ||
5787 (SS.isNotEmpty() && TUK != TUK_Reference)) {
5788 if (TemplateParameterList *TemplateParams
5789 = MatchTemplateParametersToScopeSpecifier(KWLoc, SS,
5790 TemplateParameterLists.get(),
5791 TemplateParameterLists.size(),
5792 TUK == TUK_Friend,
5793 isExplicitSpecialization,
5794 Invalid)) {
5795 // All but one template parameter lists have been matching.
5796 --NumMatchedTemplateParamLists;
5798 if (TemplateParams->size() > 0) {
5799 // This is a declaration or definition of a class template (which may
5800 // be a member of another template).
5801 if (Invalid)
5802 return 0;
5804 OwnedDecl = false;
5805 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
5806 SS, Name, NameLoc, Attr,
5807 TemplateParams,
5808 AS);
5809 TemplateParameterLists.release();
5810 return Result.get();
5811 } else {
5812 // The "template<>" header is extraneous.
5813 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
5814 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
5815 isExplicitSpecialization = true;
5820 // Figure out the underlying type if this a enum declaration. We need to do
5821 // this early, because it's needed to detect if this is an incompatible
5822 // redeclaration.
5823 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
5825 if (Kind == TTK_Enum) {
5826 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
5827 // No underlying type explicitly specified, or we failed to parse the
5828 // type, default to int.
5829 EnumUnderlying = Context.IntTy.getTypePtr();
5830 else if (UnderlyingType.get()) {
5831 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
5832 // integral type; any cv-qualification is ignored.
5833 TypeSourceInfo *TI = 0;
5834 QualType T = GetTypeFromParser(UnderlyingType.get(), &TI);
5835 EnumUnderlying = TI;
5837 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
5839 if (!T->isDependentType() && !T->isIntegralType(Context)) {
5840 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
5841 << T;
5842 // Recover by falling back to int.
5843 EnumUnderlying = Context.IntTy.getTypePtr();
5846 if (DiagnoseUnexpandedParameterPack(UnderlyingLoc, TI,
5847 UPPC_FixedUnderlyingType))
5848 EnumUnderlying = Context.IntTy.getTypePtr();
5850 } else if (getLangOptions().Microsoft)
5851 // Microsoft enums are always of int type.
5852 EnumUnderlying = Context.IntTy.getTypePtr();
5855 DeclContext *SearchDC = CurContext;
5856 DeclContext *DC = CurContext;
5857 bool isStdBadAlloc = false;
5859 RedeclarationKind Redecl = ForRedeclaration;
5860 if (TUK == TUK_Friend || TUK == TUK_Reference)
5861 Redecl = NotForRedeclaration;
5863 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
5865 if (Name && SS.isNotEmpty()) {
5866 // We have a nested-name tag ('struct foo::bar').
5868 // Check for invalid 'foo::'.
5869 if (SS.isInvalid()) {
5870 Name = 0;
5871 goto CreateNewDecl;
5874 // If this is a friend or a reference to a class in a dependent
5875 // context, don't try to make a decl for it.
5876 if (TUK == TUK_Friend || TUK == TUK_Reference) {
5877 DC = computeDeclContext(SS, false);
5878 if (!DC) {
5879 IsDependent = true;
5880 return 0;
5882 } else {
5883 DC = computeDeclContext(SS, true);
5884 if (!DC) {
5885 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
5886 << SS.getRange();
5887 return 0;
5891 if (RequireCompleteDeclContext(SS, DC))
5892 return 0;
5894 SearchDC = DC;
5895 // Look-up name inside 'foo::'.
5896 LookupQualifiedName(Previous, DC);
5898 if (Previous.isAmbiguous())
5899 return 0;
5901 if (Previous.empty()) {
5902 // Name lookup did not find anything. However, if the
5903 // nested-name-specifier refers to the current instantiation,
5904 // and that current instantiation has any dependent base
5905 // classes, we might find something at instantiation time: treat
5906 // this as a dependent elaborated-type-specifier.
5907 // But this only makes any sense for reference-like lookups.
5908 if (Previous.wasNotFoundInCurrentInstantiation() &&
5909 (TUK == TUK_Reference || TUK == TUK_Friend)) {
5910 IsDependent = true;
5911 return 0;
5914 // A tag 'foo::bar' must already exist.
5915 Diag(NameLoc, diag::err_not_tag_in_scope)
5916 << Kind << Name << DC << SS.getRange();
5917 Name = 0;
5918 Invalid = true;
5919 goto CreateNewDecl;
5921 } else if (Name) {
5922 // If this is a named struct, check to see if there was a previous forward
5923 // declaration or definition.
5924 // FIXME: We're looking into outer scopes here, even when we
5925 // shouldn't be. Doing so can result in ambiguities that we
5926 // shouldn't be diagnosing.
5927 LookupName(Previous, S);
5929 // Note: there used to be some attempt at recovery here.
5930 if (Previous.isAmbiguous())
5931 return 0;
5933 if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
5934 // FIXME: This makes sure that we ignore the contexts associated
5935 // with C structs, unions, and enums when looking for a matching
5936 // tag declaration or definition. See the similar lookup tweak
5937 // in Sema::LookupName; is there a better way to deal with this?
5938 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
5939 SearchDC = SearchDC->getParent();
5941 } else if (S->isFunctionPrototypeScope()) {
5942 // If this is an enum declaration in function prototype scope, set its
5943 // initial context to the translation unit.
5944 SearchDC = Context.getTranslationUnitDecl();
5947 if (Previous.isSingleResult() &&
5948 Previous.getFoundDecl()->isTemplateParameter()) {
5949 // Maybe we will complain about the shadowed template parameter.
5950 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
5951 // Just pretend that we didn't see the previous declaration.
5952 Previous.clear();
5955 if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
5956 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
5957 // This is a declaration of or a reference to "std::bad_alloc".
5958 isStdBadAlloc = true;
5960 if (Previous.empty() && StdBadAlloc) {
5961 // std::bad_alloc has been implicitly declared (but made invisible to
5962 // name lookup). Fill in this implicit declaration as the previous
5963 // declaration, so that the declarations get chained appropriately.
5964 Previous.addDecl(getStdBadAlloc());
5968 // If we didn't find a previous declaration, and this is a reference
5969 // (or friend reference), move to the correct scope. In C++, we
5970 // also need to do a redeclaration lookup there, just in case
5971 // there's a shadow friend decl.
5972 if (Name && Previous.empty() &&
5973 (TUK == TUK_Reference || TUK == TUK_Friend)) {
5974 if (Invalid) goto CreateNewDecl;
5975 assert(SS.isEmpty());
5977 if (TUK == TUK_Reference) {
5978 // C++ [basic.scope.pdecl]p5:
5979 // -- for an elaborated-type-specifier of the form
5981 // class-key identifier
5983 // if the elaborated-type-specifier is used in the
5984 // decl-specifier-seq or parameter-declaration-clause of a
5985 // function defined in namespace scope, the identifier is
5986 // declared as a class-name in the namespace that contains
5987 // the declaration; otherwise, except as a friend
5988 // declaration, the identifier is declared in the smallest
5989 // non-class, non-function-prototype scope that contains the
5990 // declaration.
5992 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
5993 // C structs and unions.
5995 // It is an error in C++ to declare (rather than define) an enum
5996 // type, including via an elaborated type specifier. We'll
5997 // diagnose that later; for now, declare the enum in the same
5998 // scope as we would have picked for any other tag type.
6000 // GNU C also supports this behavior as part of its incomplete
6001 // enum types extension, while GNU C++ does not.
6003 // Find the context where we'll be declaring the tag.
6004 // FIXME: We would like to maintain the current DeclContext as the
6005 // lexical context,
6006 while (SearchDC->isRecord() || SearchDC->isTransparentContext())
6007 SearchDC = SearchDC->getParent();
6009 // Find the scope where we'll be declaring the tag.
6010 while (S->isClassScope() ||
6011 (getLangOptions().CPlusPlus &&
6012 S->isFunctionPrototypeScope()) ||
6013 ((S->getFlags() & Scope::DeclScope) == 0) ||
6014 (S->getEntity() &&
6015 ((DeclContext *)S->getEntity())->isTransparentContext()))
6016 S = S->getParent();
6017 } else {
6018 assert(TUK == TUK_Friend);
6019 // C++ [namespace.memdef]p3:
6020 // If a friend declaration in a non-local class first declares a
6021 // class or function, the friend class or function is a member of
6022 // the innermost enclosing namespace.
6023 SearchDC = SearchDC->getEnclosingNamespaceContext();
6026 // In C++, we need to do a redeclaration lookup to properly
6027 // diagnose some problems.
6028 if (getLangOptions().CPlusPlus) {
6029 Previous.setRedeclarationKind(ForRedeclaration);
6030 LookupQualifiedName(Previous, SearchDC);
6034 if (!Previous.empty()) {
6035 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
6037 // It's okay to have a tag decl in the same scope as a typedef
6038 // which hides a tag decl in the same scope. Finding this
6039 // insanity with a redeclaration lookup can only actually happen
6040 // in C++.
6042 // This is also okay for elaborated-type-specifiers, which is
6043 // technically forbidden by the current standard but which is
6044 // okay according to the likely resolution of an open issue;
6045 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
6046 if (getLangOptions().CPlusPlus) {
6047 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(PrevDecl)) {
6048 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
6049 TagDecl *Tag = TT->getDecl();
6050 if (Tag->getDeclName() == Name &&
6051 Tag->getDeclContext()->getRedeclContext()
6052 ->Equals(TD->getDeclContext()->getRedeclContext())) {
6053 PrevDecl = Tag;
6054 Previous.clear();
6055 Previous.addDecl(Tag);
6056 Previous.resolveKind();
6062 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
6063 // If this is a use of a previous tag, or if the tag is already declared
6064 // in the same scope (so that the definition/declaration completes or
6065 // rementions the tag), reuse the decl.
6066 if (TUK == TUK_Reference || TUK == TUK_Friend ||
6067 isDeclInScope(PrevDecl, SearchDC, S)) {
6068 // Make sure that this wasn't declared as an enum and now used as a
6069 // struct or something similar.
6070 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) {
6071 bool SafeToContinue
6072 = (PrevTagDecl->getTagKind() != TTK_Enum &&
6073 Kind != TTK_Enum);
6074 if (SafeToContinue)
6075 Diag(KWLoc, diag::err_use_with_wrong_tag)
6076 << Name
6077 << FixItHint::CreateReplacement(SourceRange(KWLoc),
6078 PrevTagDecl->getKindName());
6079 else
6080 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
6081 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
6083 if (SafeToContinue)
6084 Kind = PrevTagDecl->getTagKind();
6085 else {
6086 // Recover by making this an anonymous redefinition.
6087 Name = 0;
6088 Previous.clear();
6089 Invalid = true;
6093 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
6094 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
6096 // All conflicts with previous declarations are recovered by
6097 // returning the previous declaration.
6098 if (ScopedEnum != PrevEnum->isScoped()) {
6099 Diag(KWLoc, diag::err_enum_redeclare_scoped_mismatch)
6100 << PrevEnum->isScoped();
6101 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
6102 return PrevTagDecl;
6104 else if (EnumUnderlying && PrevEnum->isFixed()) {
6105 QualType T;
6106 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
6107 T = TI->getType();
6108 else
6109 T = QualType(EnumUnderlying.get<const Type*>(), 0);
6111 if (!Context.hasSameUnqualifiedType(T, PrevEnum->getIntegerType())) {
6112 Diag(NameLoc.isValid() ? NameLoc : KWLoc,
6113 diag::err_enum_redeclare_type_mismatch)
6114 << T
6115 << PrevEnum->getIntegerType();
6116 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
6117 return PrevTagDecl;
6120 else if (!EnumUnderlying.isNull() != PrevEnum->isFixed()) {
6121 Diag(KWLoc, diag::err_enum_redeclare_fixed_mismatch)
6122 << PrevEnum->isFixed();
6123 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
6124 return PrevTagDecl;
6128 if (!Invalid) {
6129 // If this is a use, just return the declaration we found.
6131 // FIXME: In the future, return a variant or some other clue
6132 // for the consumer of this Decl to know it doesn't own it.
6133 // For our current ASTs this shouldn't be a problem, but will
6134 // need to be changed with DeclGroups.
6135 if ((TUK == TUK_Reference && !PrevTagDecl->getFriendObjectKind()) ||
6136 TUK == TUK_Friend)
6137 return PrevTagDecl;
6139 // Diagnose attempts to redefine a tag.
6140 if (TUK == TUK_Definition) {
6141 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
6142 // If we're defining a specialization and the previous definition
6143 // is from an implicit instantiation, don't emit an error
6144 // here; we'll catch this in the general case below.
6145 if (!isExplicitSpecialization ||
6146 !isa<CXXRecordDecl>(Def) ||
6147 cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
6148 == TSK_ExplicitSpecialization) {
6149 Diag(NameLoc, diag::err_redefinition) << Name;
6150 Diag(Def->getLocation(), diag::note_previous_definition);
6151 // If this is a redefinition, recover by making this
6152 // struct be anonymous, which will make any later
6153 // references get the previous definition.
6154 Name = 0;
6155 Previous.clear();
6156 Invalid = true;
6158 } else {
6159 // If the type is currently being defined, complain
6160 // about a nested redefinition.
6161 const TagType *Tag
6162 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
6163 if (Tag->isBeingDefined()) {
6164 Diag(NameLoc, diag::err_nested_redefinition) << Name;
6165 Diag(PrevTagDecl->getLocation(),
6166 diag::note_previous_definition);
6167 Name = 0;
6168 Previous.clear();
6169 Invalid = true;
6173 // Okay, this is definition of a previously declared or referenced
6174 // tag PrevDecl. We're going to create a new Decl for it.
6177 // If we get here we have (another) forward declaration or we
6178 // have a definition. Just create a new decl.
6180 } else {
6181 // If we get here, this is a definition of a new tag type in a nested
6182 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
6183 // new decl/type. We set PrevDecl to NULL so that the entities
6184 // have distinct types.
6185 Previous.clear();
6187 // If we get here, we're going to create a new Decl. If PrevDecl
6188 // is non-NULL, it's a definition of the tag declared by
6189 // PrevDecl. If it's NULL, we have a new definition.
6192 // Otherwise, PrevDecl is not a tag, but was found with tag
6193 // lookup. This is only actually possible in C++, where a few
6194 // things like templates still live in the tag namespace.
6195 } else {
6196 assert(getLangOptions().CPlusPlus);
6198 // Use a better diagnostic if an elaborated-type-specifier
6199 // found the wrong kind of type on the first
6200 // (non-redeclaration) lookup.
6201 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
6202 !Previous.isForRedeclaration()) {
6203 unsigned Kind = 0;
6204 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
6205 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 2;
6206 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
6207 Diag(PrevDecl->getLocation(), diag::note_declared_at);
6208 Invalid = true;
6210 // Otherwise, only diagnose if the declaration is in scope.
6211 } else if (!isDeclInScope(PrevDecl, SearchDC, S)) {
6212 // do nothing
6214 // Diagnose implicit declarations introduced by elaborated types.
6215 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
6216 unsigned Kind = 0;
6217 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
6218 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 2;
6219 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
6220 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
6221 Invalid = true;
6223 // Otherwise it's a declaration. Call out a particularly common
6224 // case here.
6225 } else if (isa<TypedefDecl>(PrevDecl)) {
6226 Diag(NameLoc, diag::err_tag_definition_of_typedef)
6227 << Name
6228 << cast<TypedefDecl>(PrevDecl)->getUnderlyingType();
6229 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
6230 Invalid = true;
6232 // Otherwise, diagnose.
6233 } else {
6234 // The tag name clashes with something else in the target scope,
6235 // issue an error and recover by making this tag be anonymous.
6236 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
6237 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6238 Name = 0;
6239 Invalid = true;
6242 // The existing declaration isn't relevant to us; we're in a
6243 // new scope, so clear out the previous declaration.
6244 Previous.clear();
6248 CreateNewDecl:
6250 TagDecl *PrevDecl = 0;
6251 if (Previous.isSingleResult())
6252 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
6254 // If there is an identifier, use the location of the identifier as the
6255 // location of the decl, otherwise use the location of the struct/union
6256 // keyword.
6257 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
6259 // Otherwise, create a new declaration. If there is a previous
6260 // declaration of the same entity, the two will be linked via
6261 // PrevDecl.
6262 TagDecl *New;
6264 bool IsForwardReference = false;
6265 if (Kind == TTK_Enum) {
6266 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
6267 // enum X { A, B, C } D; D should chain to X.
6268 New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc,
6269 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
6270 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
6271 // If this is an undefined enum, warn.
6272 if (TUK != TUK_Definition && !Invalid) {
6273 TagDecl *Def;
6274 if (getLangOptions().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) {
6275 // C++0x: 7.2p2: opaque-enum-declaration.
6276 // Conflicts are diagnosed above. Do nothing.
6278 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
6279 Diag(Loc, diag::ext_forward_ref_enum_def)
6280 << New;
6281 Diag(Def->getLocation(), diag::note_previous_definition);
6282 } else {
6283 unsigned DiagID = diag::ext_forward_ref_enum;
6284 if (getLangOptions().Microsoft)
6285 DiagID = diag::ext_ms_forward_ref_enum;
6286 else if (getLangOptions().CPlusPlus)
6287 DiagID = diag::err_forward_ref_enum;
6288 Diag(Loc, DiagID);
6290 // If this is a forward-declared reference to an enumeration, make a
6291 // note of it; we won't actually be introducing the declaration into
6292 // the declaration context.
6293 if (TUK == TUK_Reference)
6294 IsForwardReference = true;
6298 if (EnumUnderlying) {
6299 EnumDecl *ED = cast<EnumDecl>(New);
6300 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
6301 ED->setIntegerTypeSourceInfo(TI);
6302 else
6303 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
6304 ED->setPromotionType(ED->getIntegerType());
6307 } else {
6308 // struct/union/class
6310 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
6311 // struct X { int A; } D; D should chain to X.
6312 if (getLangOptions().CPlusPlus) {
6313 // FIXME: Look for a way to use RecordDecl for simple structs.
6314 New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
6315 cast_or_null<CXXRecordDecl>(PrevDecl));
6317 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
6318 StdBadAlloc = cast<CXXRecordDecl>(New);
6319 } else
6320 New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
6321 cast_or_null<RecordDecl>(PrevDecl));
6324 // Maybe add qualifier info.
6325 if (SS.isNotEmpty()) {
6326 if (SS.isSet()) {
6327 NestedNameSpecifier *NNS
6328 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6329 New->setQualifierInfo(NNS, SS.getRange());
6330 if (NumMatchedTemplateParamLists > 0) {
6331 New->setTemplateParameterListsInfo(Context,
6332 NumMatchedTemplateParamLists,
6333 (TemplateParameterList**) TemplateParameterLists.release());
6336 else
6337 Invalid = true;
6340 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
6341 // Add alignment attributes if necessary; these attributes are checked when
6342 // the ASTContext lays out the structure.
6344 // It is important for implementing the correct semantics that this
6345 // happen here (in act on tag decl). The #pragma pack stack is
6346 // maintained as a result of parser callbacks which can occur at
6347 // many points during the parsing of a struct declaration (because
6348 // the #pragma tokens are effectively skipped over during the
6349 // parsing of the struct).
6350 AddAlignmentAttributesForRecord(RD);
6353 // If this is a specialization of a member class (of a class template),
6354 // check the specialization.
6355 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
6356 Invalid = true;
6358 if (Invalid)
6359 New->setInvalidDecl();
6361 if (Attr)
6362 ProcessDeclAttributeList(S, New, Attr);
6364 // If we're declaring or defining a tag in function prototype scope
6365 // in C, note that this type can only be used within the function.
6366 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
6367 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
6369 // Set the lexical context. If the tag has a C++ scope specifier, the
6370 // lexical context will be different from the semantic context.
6371 New->setLexicalDeclContext(CurContext);
6373 // Mark this as a friend decl if applicable.
6374 if (TUK == TUK_Friend)
6375 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty());
6377 // Set the access specifier.
6378 if (!Invalid && SearchDC->isRecord())
6379 SetMemberAccessSpecifier(New, PrevDecl, AS);
6381 if (TUK == TUK_Definition)
6382 New->startDefinition();
6384 // If this has an identifier, add it to the scope stack.
6385 if (TUK == TUK_Friend) {
6386 // We might be replacing an existing declaration in the lookup tables;
6387 // if so, borrow its access specifier.
6388 if (PrevDecl)
6389 New->setAccess(PrevDecl->getAccess());
6391 DeclContext *DC = New->getDeclContext()->getRedeclContext();
6392 DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
6393 if (Name) // can be null along some error paths
6394 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
6395 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
6396 } else if (Name) {
6397 S = getNonFieldDeclScope(S);
6398 PushOnScopeChains(New, S, !IsForwardReference);
6399 if (IsForwardReference)
6400 SearchDC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
6402 } else {
6403 CurContext->addDecl(New);
6406 // If this is the C FILE type, notify the AST context.
6407 if (IdentifierInfo *II = New->getIdentifier())
6408 if (!New->isInvalidDecl() &&
6409 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6410 II->isStr("FILE"))
6411 Context.setFILEDecl(New);
6413 OwnedDecl = true;
6414 return New;
6417 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
6418 AdjustDeclIfTemplate(TagD);
6419 TagDecl *Tag = cast<TagDecl>(TagD);
6421 // Enter the tag context.
6422 PushDeclContext(S, Tag);
6425 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
6426 ClassVirtSpecifiers &CVS,
6427 SourceLocation LBraceLoc) {
6428 AdjustDeclIfTemplate(TagD);
6429 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
6431 FieldCollector->StartClass();
6433 if (!Record->getIdentifier())
6434 return;
6436 if (CVS.isFinalSpecified())
6437 Record->addAttr(new (Context) FinalAttr(CVS.getFinalLoc(), Context));
6438 if (CVS.isExplicitSpecified())
6439 Record->addAttr(new (Context) ExplicitAttr(CVS.getExplicitLoc(), Context));
6441 // C++ [class]p2:
6442 // [...] The class-name is also inserted into the scope of the
6443 // class itself; this is known as the injected-class-name. For
6444 // purposes of access checking, the injected-class-name is treated
6445 // as if it were a public member name.
6446 CXXRecordDecl *InjectedClassName
6447 = CXXRecordDecl::Create(Context, Record->getTagKind(),
6448 CurContext, Record->getLocation(),
6449 Record->getIdentifier(),
6450 Record->getTagKeywordLoc(),
6451 /*PrevDecl=*/0,
6452 /*DelayTypeCreation=*/true);
6453 Context.getTypeDeclType(InjectedClassName, Record);
6454 InjectedClassName->setImplicit();
6455 InjectedClassName->setAccess(AS_public);
6456 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
6457 InjectedClassName->setDescribedClassTemplate(Template);
6458 PushOnScopeChains(InjectedClassName, S);
6459 assert(InjectedClassName->isInjectedClassName() &&
6460 "Broken injected-class-name");
6463 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
6464 SourceLocation RBraceLoc) {
6465 AdjustDeclIfTemplate(TagD);
6466 TagDecl *Tag = cast<TagDecl>(TagD);
6467 Tag->setRBraceLoc(RBraceLoc);
6469 if (isa<CXXRecordDecl>(Tag))
6470 FieldCollector->FinishClass();
6472 // Exit this scope of this tag's definition.
6473 PopDeclContext();
6475 // Notify the consumer that we've defined a tag.
6476 Consumer.HandleTagDeclDefinition(Tag);
6479 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
6480 AdjustDeclIfTemplate(TagD);
6481 TagDecl *Tag = cast<TagDecl>(TagD);
6482 Tag->setInvalidDecl();
6484 // We're undoing ActOnTagStartDefinition here, not
6485 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
6486 // the FieldCollector.
6488 PopDeclContext();
6491 // Note that FieldName may be null for anonymous bitfields.
6492 bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
6493 QualType FieldTy, const Expr *BitWidth,
6494 bool *ZeroWidth) {
6495 // Default to true; that shouldn't confuse checks for emptiness
6496 if (ZeroWidth)
6497 *ZeroWidth = true;
6499 // C99 6.7.2.1p4 - verify the field type.
6500 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
6501 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
6502 // Handle incomplete types with specific error.
6503 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
6504 return true;
6505 if (FieldName)
6506 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
6507 << FieldName << FieldTy << BitWidth->getSourceRange();
6508 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
6509 << FieldTy << BitWidth->getSourceRange();
6510 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
6511 UPPC_BitFieldWidth))
6512 return true;
6514 // If the bit-width is type- or value-dependent, don't try to check
6515 // it now.
6516 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
6517 return false;
6519 llvm::APSInt Value;
6520 if (VerifyIntegerConstantExpression(BitWidth, &Value))
6521 return true;
6523 if (Value != 0 && ZeroWidth)
6524 *ZeroWidth = false;
6526 // Zero-width bitfield is ok for anonymous field.
6527 if (Value == 0 && FieldName)
6528 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
6530 if (Value.isSigned() && Value.isNegative()) {
6531 if (FieldName)
6532 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
6533 << FieldName << Value.toString(10);
6534 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
6535 << Value.toString(10);
6538 if (!FieldTy->isDependentType()) {
6539 uint64_t TypeSize = Context.getTypeSize(FieldTy);
6540 if (Value.getZExtValue() > TypeSize) {
6541 if (!getLangOptions().CPlusPlus) {
6542 if (FieldName)
6543 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
6544 << FieldName << (unsigned)Value.getZExtValue()
6545 << (unsigned)TypeSize;
6547 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
6548 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
6551 if (FieldName)
6552 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
6553 << FieldName << (unsigned)Value.getZExtValue()
6554 << (unsigned)TypeSize;
6555 else
6556 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
6557 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
6561 return false;
6564 /// ActOnField - Each field of a struct/union/class is passed into this in order
6565 /// to create a FieldDecl object for it.
6566 Decl *Sema::ActOnField(Scope *S, Decl *TagD,
6567 SourceLocation DeclStart,
6568 Declarator &D, ExprTy *BitfieldWidth) {
6569 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
6570 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
6571 AS_public);
6572 return Res;
6575 /// HandleField - Analyze a field of a C struct or a C++ data member.
6577 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
6578 SourceLocation DeclStart,
6579 Declarator &D, Expr *BitWidth,
6580 AccessSpecifier AS) {
6581 IdentifierInfo *II = D.getIdentifier();
6582 SourceLocation Loc = DeclStart;
6583 if (II) Loc = D.getIdentifierLoc();
6585 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6586 QualType T = TInfo->getType();
6587 if (getLangOptions().CPlusPlus) {
6588 CheckExtraCXXDefaultArguments(D);
6590 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6591 UPPC_DataMemberType)) {
6592 D.setInvalidType();
6593 T = Context.IntTy;
6594 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
6598 DiagnoseFunctionSpecifiers(D);
6600 if (D.getDeclSpec().isThreadSpecified())
6601 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
6603 // Check to see if this name was declared as a member previously
6604 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
6605 LookupName(Previous, S);
6606 assert((Previous.empty() || Previous.isOverloadedResult() ||
6607 Previous.isSingleResult())
6608 && "Lookup of member name should be either overloaded, single or null");
6610 // If the name is overloaded then get any declaration else get the single result
6611 NamedDecl *PrevDecl = Previous.isOverloadedResult() ?
6612 Previous.getRepresentativeDecl() : Previous.getAsSingle<NamedDecl>();
6614 if (PrevDecl && PrevDecl->isTemplateParameter()) {
6615 // Maybe we will complain about the shadowed template parameter.
6616 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
6617 // Just pretend that we didn't see the previous declaration.
6618 PrevDecl = 0;
6621 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
6622 PrevDecl = 0;
6624 bool Mutable
6625 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
6626 SourceLocation TSSL = D.getSourceRange().getBegin();
6627 FieldDecl *NewFD
6628 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, TSSL,
6629 AS, PrevDecl, &D);
6631 if (NewFD->isInvalidDecl())
6632 Record->setInvalidDecl();
6634 if (NewFD->isInvalidDecl() && PrevDecl) {
6635 // Don't introduce NewFD into scope; there's already something
6636 // with the same name in the same scope.
6637 } else if (II) {
6638 PushOnScopeChains(NewFD, S);
6639 } else
6640 Record->addDecl(NewFD);
6642 return NewFD;
6645 /// \brief Build a new FieldDecl and check its well-formedness.
6647 /// This routine builds a new FieldDecl given the fields name, type,
6648 /// record, etc. \p PrevDecl should refer to any previous declaration
6649 /// with the same name and in the same scope as the field to be
6650 /// created.
6652 /// \returns a new FieldDecl.
6654 /// \todo The Declarator argument is a hack. It will be removed once
6655 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
6656 TypeSourceInfo *TInfo,
6657 RecordDecl *Record, SourceLocation Loc,
6658 bool Mutable, Expr *BitWidth,
6659 SourceLocation TSSL,
6660 AccessSpecifier AS, NamedDecl *PrevDecl,
6661 Declarator *D) {
6662 IdentifierInfo *II = Name.getAsIdentifierInfo();
6663 bool InvalidDecl = false;
6664 if (D) InvalidDecl = D->isInvalidType();
6666 // If we receive a broken type, recover by assuming 'int' and
6667 // marking this declaration as invalid.
6668 if (T.isNull()) {
6669 InvalidDecl = true;
6670 T = Context.IntTy;
6673 QualType EltTy = Context.getBaseElementType(T);
6674 if (!EltTy->isDependentType() &&
6675 RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
6676 // Fields of incomplete type force their record to be invalid.
6677 Record->setInvalidDecl();
6678 InvalidDecl = true;
6681 // C99 6.7.2.1p8: A member of a structure or union may have any type other
6682 // than a variably modified type.
6683 if (!InvalidDecl && T->isVariablyModifiedType()) {
6684 bool SizeIsNegative;
6685 llvm::APSInt Oversized;
6686 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
6687 SizeIsNegative,
6688 Oversized);
6689 if (!FixedTy.isNull()) {
6690 Diag(Loc, diag::warn_illegal_constant_array_size);
6691 T = FixedTy;
6692 } else {
6693 if (SizeIsNegative)
6694 Diag(Loc, diag::err_typecheck_negative_array_size);
6695 else if (Oversized.getBoolValue())
6696 Diag(Loc, diag::err_array_too_large)
6697 << Oversized.toString(10);
6698 else
6699 Diag(Loc, diag::err_typecheck_field_variable_size);
6700 InvalidDecl = true;
6704 // Fields can not have abstract class types
6705 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
6706 diag::err_abstract_type_in_decl,
6707 AbstractFieldType))
6708 InvalidDecl = true;
6710 bool ZeroWidth = false;
6711 // If this is declared as a bit-field, check the bit-field.
6712 if (!InvalidDecl && BitWidth &&
6713 VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
6714 InvalidDecl = true;
6715 BitWidth = 0;
6716 ZeroWidth = false;
6719 // Check that 'mutable' is consistent with the type of the declaration.
6720 if (!InvalidDecl && Mutable) {
6721 unsigned DiagID = 0;
6722 if (T->isReferenceType())
6723 DiagID = diag::err_mutable_reference;
6724 else if (T.isConstQualified())
6725 DiagID = diag::err_mutable_const;
6727 if (DiagID) {
6728 SourceLocation ErrLoc = Loc;
6729 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
6730 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
6731 Diag(ErrLoc, DiagID);
6732 Mutable = false;
6733 InvalidDecl = true;
6737 FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, TInfo,
6738 BitWidth, Mutable);
6739 if (InvalidDecl)
6740 NewFD->setInvalidDecl();
6742 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
6743 Diag(Loc, diag::err_duplicate_member) << II;
6744 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
6745 NewFD->setInvalidDecl();
6748 if (!InvalidDecl && getLangOptions().CPlusPlus) {
6749 if (Record->isUnion()) {
6750 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
6751 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
6752 if (RDecl->getDefinition()) {
6753 // C++ [class.union]p1: An object of a class with a non-trivial
6754 // constructor, a non-trivial copy constructor, a non-trivial
6755 // destructor, or a non-trivial copy assignment operator
6756 // cannot be a member of a union, nor can an array of such
6757 // objects.
6758 // TODO: C++0x alters this restriction significantly.
6759 if (CheckNontrivialField(NewFD))
6760 NewFD->setInvalidDecl();
6764 // C++ [class.union]p1: If a union contains a member of reference type,
6765 // the program is ill-formed.
6766 if (EltTy->isReferenceType()) {
6767 Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
6768 << NewFD->getDeclName() << EltTy;
6769 NewFD->setInvalidDecl();
6774 // FIXME: We need to pass in the attributes given an AST
6775 // representation, not a parser representation.
6776 if (D)
6777 // FIXME: What to pass instead of TUScope?
6778 ProcessDeclAttributes(TUScope, NewFD, *D);
6780 if (T.isObjCGCWeak())
6781 Diag(Loc, diag::warn_attribute_weak_on_field);
6783 NewFD->setAccess(AS);
6784 return NewFD;
6787 bool Sema::CheckNontrivialField(FieldDecl *FD) {
6788 assert(FD);
6789 assert(getLangOptions().CPlusPlus && "valid check only for C++");
6791 if (FD->isInvalidDecl())
6792 return true;
6794 QualType EltTy = Context.getBaseElementType(FD->getType());
6795 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
6796 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
6797 if (RDecl->getDefinition()) {
6798 // We check for copy constructors before constructors
6799 // because otherwise we'll never get complaints about
6800 // copy constructors.
6802 CXXSpecialMember member = CXXInvalid;
6803 if (!RDecl->hasTrivialCopyConstructor())
6804 member = CXXCopyConstructor;
6805 else if (!RDecl->hasTrivialConstructor())
6806 member = CXXConstructor;
6807 else if (!RDecl->hasTrivialCopyAssignment())
6808 member = CXXCopyAssignment;
6809 else if (!RDecl->hasTrivialDestructor())
6810 member = CXXDestructor;
6812 if (member != CXXInvalid) {
6813 Diag(FD->getLocation(), diag::err_illegal_union_or_anon_struct_member)
6814 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
6815 DiagnoseNontrivial(RT, member);
6816 return true;
6821 return false;
6824 /// DiagnoseNontrivial - Given that a class has a non-trivial
6825 /// special member, figure out why.
6826 void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
6827 QualType QT(T, 0U);
6828 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
6830 // Check whether the member was user-declared.
6831 switch (member) {
6832 case CXXInvalid:
6833 break;
6835 case CXXConstructor:
6836 if (RD->hasUserDeclaredConstructor()) {
6837 typedef CXXRecordDecl::ctor_iterator ctor_iter;
6838 for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
6839 const FunctionDecl *body = 0;
6840 ci->hasBody(body);
6841 if (!body || !cast<CXXConstructorDecl>(body)->isImplicitlyDefined()) {
6842 SourceLocation CtorLoc = ci->getLocation();
6843 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
6844 return;
6848 assert(0 && "found no user-declared constructors");
6849 return;
6851 break;
6853 case CXXCopyConstructor:
6854 if (RD->hasUserDeclaredCopyConstructor()) {
6855 SourceLocation CtorLoc =
6856 RD->getCopyConstructor(Context, 0)->getLocation();
6857 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
6858 return;
6860 break;
6862 case CXXCopyAssignment:
6863 if (RD->hasUserDeclaredCopyAssignment()) {
6864 // FIXME: this should use the location of the copy
6865 // assignment, not the type.
6866 SourceLocation TyLoc = RD->getSourceRange().getBegin();
6867 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
6868 return;
6870 break;
6872 case CXXDestructor:
6873 if (RD->hasUserDeclaredDestructor()) {
6874 SourceLocation DtorLoc = LookupDestructor(RD)->getLocation();
6875 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
6876 return;
6878 break;
6881 typedef CXXRecordDecl::base_class_iterator base_iter;
6883 // Virtual bases and members inhibit trivial copying/construction,
6884 // but not trivial destruction.
6885 if (member != CXXDestructor) {
6886 // Check for virtual bases. vbases includes indirect virtual bases,
6887 // so we just iterate through the direct bases.
6888 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
6889 if (bi->isVirtual()) {
6890 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
6891 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
6892 return;
6895 // Check for virtual methods.
6896 typedef CXXRecordDecl::method_iterator meth_iter;
6897 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
6898 ++mi) {
6899 if (mi->isVirtual()) {
6900 SourceLocation MLoc = mi->getSourceRange().getBegin();
6901 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
6902 return;
6907 bool (CXXRecordDecl::*hasTrivial)() const;
6908 switch (member) {
6909 case CXXConstructor:
6910 hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break;
6911 case CXXCopyConstructor:
6912 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
6913 case CXXCopyAssignment:
6914 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
6915 case CXXDestructor:
6916 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
6917 default:
6918 assert(0 && "unexpected special member"); return;
6921 // Check for nontrivial bases (and recurse).
6922 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
6923 const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
6924 assert(BaseRT && "Don't know how to handle dependent bases");
6925 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
6926 if (!(BaseRecTy->*hasTrivial)()) {
6927 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
6928 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
6929 DiagnoseNontrivial(BaseRT, member);
6930 return;
6934 // Check for nontrivial members (and recurse).
6935 typedef RecordDecl::field_iterator field_iter;
6936 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
6937 ++fi) {
6938 QualType EltTy = Context.getBaseElementType((*fi)->getType());
6939 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
6940 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
6942 if (!(EltRD->*hasTrivial)()) {
6943 SourceLocation FLoc = (*fi)->getLocation();
6944 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
6945 DiagnoseNontrivial(EltRT, member);
6946 return;
6951 assert(0 && "found no explanation for non-trivial member");
6954 /// TranslateIvarVisibility - Translate visibility from a token ID to an
6955 /// AST enum value.
6956 static ObjCIvarDecl::AccessControl
6957 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
6958 switch (ivarVisibility) {
6959 default: assert(0 && "Unknown visitibility kind");
6960 case tok::objc_private: return ObjCIvarDecl::Private;
6961 case tok::objc_public: return ObjCIvarDecl::Public;
6962 case tok::objc_protected: return ObjCIvarDecl::Protected;
6963 case tok::objc_package: return ObjCIvarDecl::Package;
6967 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
6968 /// in order to create an IvarDecl object for it.
6969 Decl *Sema::ActOnIvar(Scope *S,
6970 SourceLocation DeclStart,
6971 Decl *IntfDecl,
6972 Declarator &D, ExprTy *BitfieldWidth,
6973 tok::ObjCKeywordKind Visibility) {
6975 IdentifierInfo *II = D.getIdentifier();
6976 Expr *BitWidth = (Expr*)BitfieldWidth;
6977 SourceLocation Loc = DeclStart;
6978 if (II) Loc = D.getIdentifierLoc();
6980 // FIXME: Unnamed fields can be handled in various different ways, for
6981 // example, unnamed unions inject all members into the struct namespace!
6983 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6984 QualType T = TInfo->getType();
6986 if (BitWidth) {
6987 // 6.7.2.1p3, 6.7.2.1p4
6988 if (VerifyBitField(Loc, II, T, BitWidth)) {
6989 D.setInvalidType();
6990 BitWidth = 0;
6992 } else {
6993 // Not a bitfield.
6995 // validate II.
6998 if (T->isReferenceType()) {
6999 Diag(Loc, diag::err_ivar_reference_type);
7000 D.setInvalidType();
7002 // C99 6.7.2.1p8: A member of a structure or union may have any type other
7003 // than a variably modified type.
7004 else if (T->isVariablyModifiedType()) {
7005 Diag(Loc, diag::err_typecheck_ivar_variable_size);
7006 D.setInvalidType();
7009 // Get the visibility (access control) for this ivar.
7010 ObjCIvarDecl::AccessControl ac =
7011 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
7012 : ObjCIvarDecl::None;
7013 // Must set ivar's DeclContext to its enclosing interface.
7014 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(IntfDecl);
7015 ObjCContainerDecl *EnclosingContext;
7016 if (ObjCImplementationDecl *IMPDecl =
7017 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
7018 if (!LangOpts.ObjCNonFragileABI2) {
7019 // Case of ivar declared in an implementation. Context is that of its class.
7020 EnclosingContext = IMPDecl->getClassInterface();
7021 assert(EnclosingContext && "Implementation has no class interface!");
7023 else
7024 EnclosingContext = EnclosingDecl;
7025 } else {
7026 if (ObjCCategoryDecl *CDecl =
7027 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
7028 if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) {
7029 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
7030 return 0;
7033 EnclosingContext = EnclosingDecl;
7036 // Construct the decl.
7037 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context,
7038 EnclosingContext, Loc, II, T,
7039 TInfo, ac, (Expr *)BitfieldWidth);
7041 if (II) {
7042 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
7043 ForRedeclaration);
7044 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
7045 && !isa<TagDecl>(PrevDecl)) {
7046 Diag(Loc, diag::err_duplicate_member) << II;
7047 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
7048 NewID->setInvalidDecl();
7052 // Process attributes attached to the ivar.
7053 ProcessDeclAttributes(S, NewID, D);
7055 if (D.isInvalidType())
7056 NewID->setInvalidDecl();
7058 if (II) {
7059 // FIXME: When interfaces are DeclContexts, we'll need to add
7060 // these to the interface.
7061 S->AddDecl(NewID);
7062 IdResolver.AddDecl(NewID);
7065 return NewID;
7068 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
7069 /// class and class extensions. For every class @interface and class
7070 /// extension @interface, if the last ivar is a bitfield of any type,
7071 /// then add an implicit `char :0` ivar to the end of that interface.
7072 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, Decl *EnclosingDecl,
7073 llvm::SmallVectorImpl<Decl *> &AllIvarDecls) {
7074 if (!LangOpts.ObjCNonFragileABI2 || AllIvarDecls.empty())
7075 return;
7077 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
7078 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
7080 if (!Ivar->isBitField())
7081 return;
7082 uint64_t BitFieldSize =
7083 Ivar->getBitWidth()->EvaluateAsInt(Context).getZExtValue();
7084 if (BitFieldSize == 0)
7085 return;
7086 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl);
7087 if (!ID) {
7088 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
7089 if (!CD->IsClassExtension())
7090 return;
7092 // No need to add this to end of @implementation.
7093 else
7094 return;
7096 // All conditions are met. Add a new bitfield to the tail end of ivars.
7097 llvm::APInt Zero(Context.getTypeSize(Context.CharTy), 0);
7098 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.CharTy, DeclLoc);
7100 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(EnclosingDecl),
7101 DeclLoc, 0,
7102 Context.CharTy,
7103 Context.CreateTypeSourceInfo(Context.CharTy),
7104 ObjCIvarDecl::Private, BW,
7105 true);
7106 AllIvarDecls.push_back(Ivar);
7109 void Sema::ActOnFields(Scope* S,
7110 SourceLocation RecLoc, Decl *EnclosingDecl,
7111 Decl **Fields, unsigned NumFields,
7112 SourceLocation LBrac, SourceLocation RBrac,
7113 AttributeList *Attr) {
7114 assert(EnclosingDecl && "missing record or interface decl");
7116 // If the decl this is being inserted into is invalid, then it may be a
7117 // redeclaration or some other bogus case. Don't try to add fields to it.
7118 if (EnclosingDecl->isInvalidDecl()) {
7119 // FIXME: Deallocate fields?
7120 return;
7124 // Verify that all the fields are okay.
7125 unsigned NumNamedMembers = 0;
7126 llvm::SmallVector<FieldDecl*, 32> RecFields;
7128 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
7129 for (unsigned i = 0; i != NumFields; ++i) {
7130 FieldDecl *FD = cast<FieldDecl>(Fields[i]);
7132 // Get the type for the field.
7133 const Type *FDTy = FD->getType().getTypePtr();
7135 if (!FD->isAnonymousStructOrUnion()) {
7136 // Remember all fields written by the user.
7137 RecFields.push_back(FD);
7140 // If the field is already invalid for some reason, don't emit more
7141 // diagnostics about it.
7142 if (FD->isInvalidDecl()) {
7143 EnclosingDecl->setInvalidDecl();
7144 continue;
7147 // C99 6.7.2.1p2:
7148 // A structure or union shall not contain a member with
7149 // incomplete or function type (hence, a structure shall not
7150 // contain an instance of itself, but may contain a pointer to
7151 // an instance of itself), except that the last member of a
7152 // structure with more than one named member may have incomplete
7153 // array type; such a structure (and any union containing,
7154 // possibly recursively, a member that is such a structure)
7155 // shall not be a member of a structure or an element of an
7156 // array.
7157 if (FDTy->isFunctionType()) {
7158 // Field declared as a function.
7159 Diag(FD->getLocation(), diag::err_field_declared_as_function)
7160 << FD->getDeclName();
7161 FD->setInvalidDecl();
7162 EnclosingDecl->setInvalidDecl();
7163 continue;
7164 } else if (FDTy->isIncompleteArrayType() && Record &&
7165 ((i == NumFields - 1 && !Record->isUnion()) ||
7166 (getLangOptions().Microsoft &&
7167 (i == NumFields - 1 || Record->isUnion())))) {
7168 // Flexible array member.
7169 // Microsoft is more permissive regarding flexible array.
7170 // It will accept flexible array in union and also
7171 // as the sole element of a struct/class.
7172 if (getLangOptions().Microsoft) {
7173 if (Record->isUnion())
7174 Diag(FD->getLocation(), diag::ext_flexible_array_union)
7175 << FD->getDeclName();
7176 else if (NumFields == 1)
7177 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate)
7178 << FD->getDeclName() << Record->getTagKind();
7179 } else if (NumNamedMembers < 1) {
7180 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
7181 << FD->getDeclName();
7182 FD->setInvalidDecl();
7183 EnclosingDecl->setInvalidDecl();
7184 continue;
7186 if (!FD->getType()->isDependentType() &&
7187 !Context.getBaseElementType(FD->getType())->isPODType()) {
7188 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
7189 << FD->getDeclName() << FD->getType();
7190 FD->setInvalidDecl();
7191 EnclosingDecl->setInvalidDecl();
7192 continue;
7194 // Okay, we have a legal flexible array member at the end of the struct.
7195 if (Record)
7196 Record->setHasFlexibleArrayMember(true);
7197 } else if (!FDTy->isDependentType() &&
7198 RequireCompleteType(FD->getLocation(), FD->getType(),
7199 diag::err_field_incomplete)) {
7200 // Incomplete type
7201 FD->setInvalidDecl();
7202 EnclosingDecl->setInvalidDecl();
7203 continue;
7204 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
7205 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
7206 // If this is a member of a union, then entire union becomes "flexible".
7207 if (Record && Record->isUnion()) {
7208 Record->setHasFlexibleArrayMember(true);
7209 } else {
7210 // If this is a struct/class and this is not the last element, reject
7211 // it. Note that GCC supports variable sized arrays in the middle of
7212 // structures.
7213 if (i != NumFields-1)
7214 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
7215 << FD->getDeclName() << FD->getType();
7216 else {
7217 // We support flexible arrays at the end of structs in
7218 // other structs as an extension.
7219 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
7220 << FD->getDeclName();
7221 if (Record)
7222 Record->setHasFlexibleArrayMember(true);
7226 if (Record && FDTTy->getDecl()->hasObjectMember())
7227 Record->setHasObjectMember(true);
7228 } else if (FDTy->isObjCObjectType()) {
7229 /// A field cannot be an Objective-c object
7230 Diag(FD->getLocation(), diag::err_statically_allocated_object);
7231 FD->setInvalidDecl();
7232 EnclosingDecl->setInvalidDecl();
7233 continue;
7234 } else if (getLangOptions().ObjC1 &&
7235 getLangOptions().getGCMode() != LangOptions::NonGC &&
7236 Record &&
7237 (FD->getType()->isObjCObjectPointerType() ||
7238 FD->getType().isObjCGCStrong()))
7239 Record->setHasObjectMember(true);
7240 else if (Context.getAsArrayType(FD->getType())) {
7241 QualType BaseType = Context.getBaseElementType(FD->getType());
7242 if (Record && BaseType->isRecordType() &&
7243 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
7244 Record->setHasObjectMember(true);
7246 // Keep track of the number of named members.
7247 if (FD->getIdentifier())
7248 ++NumNamedMembers;
7251 // Okay, we successfully defined 'Record'.
7252 if (Record) {
7253 bool Completed = false;
7254 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
7255 if (!CXXRecord->isInvalidDecl()) {
7256 // Set access bits correctly on the directly-declared conversions.
7257 UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions();
7258 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end();
7259 I != E; ++I)
7260 Convs->setAccess(I, (*I)->getAccess());
7262 if (!CXXRecord->isDependentType()) {
7263 // Add any implicitly-declared members to this class.
7264 AddImplicitlyDeclaredMembersToClass(CXXRecord);
7266 // If we have virtual base classes, we may end up finding multiple
7267 // final overriders for a given virtual function. Check for this
7268 // problem now.
7269 if (CXXRecord->getNumVBases()) {
7270 CXXFinalOverriderMap FinalOverriders;
7271 CXXRecord->getFinalOverriders(FinalOverriders);
7273 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
7274 MEnd = FinalOverriders.end();
7275 M != MEnd; ++M) {
7276 for (OverridingMethods::iterator SO = M->second.begin(),
7277 SOEnd = M->second.end();
7278 SO != SOEnd; ++SO) {
7279 assert(SO->second.size() > 0 &&
7280 "Virtual function without overridding functions?");
7281 if (SO->second.size() == 1)
7282 continue;
7284 // C++ [class.virtual]p2:
7285 // In a derived class, if a virtual member function of a base
7286 // class subobject has more than one final overrider the
7287 // program is ill-formed.
7288 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
7289 << (NamedDecl *)M->first << Record;
7290 Diag(M->first->getLocation(),
7291 diag::note_overridden_virtual_function);
7292 for (OverridingMethods::overriding_iterator
7293 OM = SO->second.begin(),
7294 OMEnd = SO->second.end();
7295 OM != OMEnd; ++OM)
7296 Diag(OM->Method->getLocation(), diag::note_final_overrider)
7297 << (NamedDecl *)M->first << OM->Method->getParent();
7299 Record->setInvalidDecl();
7302 CXXRecord->completeDefinition(&FinalOverriders);
7303 Completed = true;
7309 if (!Completed)
7310 Record->completeDefinition();
7311 } else {
7312 ObjCIvarDecl **ClsFields =
7313 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
7314 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
7315 ID->setLocEnd(RBrac);
7316 // Add ivar's to class's DeclContext.
7317 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
7318 ClsFields[i]->setLexicalDeclContext(ID);
7319 ID->addDecl(ClsFields[i]);
7321 // Must enforce the rule that ivars in the base classes may not be
7322 // duplicates.
7323 if (ID->getSuperClass())
7324 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
7325 } else if (ObjCImplementationDecl *IMPDecl =
7326 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
7327 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
7328 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
7329 // Ivar declared in @implementation never belongs to the implementation.
7330 // Only it is in implementation's lexical context.
7331 ClsFields[I]->setLexicalDeclContext(IMPDecl);
7332 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
7333 } else if (ObjCCategoryDecl *CDecl =
7334 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
7335 // case of ivars in class extension; all other cases have been
7336 // reported as errors elsewhere.
7337 // FIXME. Class extension does not have a LocEnd field.
7338 // CDecl->setLocEnd(RBrac);
7339 // Add ivar's to class extension's DeclContext.
7340 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
7341 ClsFields[i]->setLexicalDeclContext(CDecl);
7342 CDecl->addDecl(ClsFields[i]);
7347 if (Attr)
7348 ProcessDeclAttributeList(S, Record, Attr);
7350 // If there's a #pragma GCC visibility in scope, and this isn't a subclass,
7351 // set the visibility of this record.
7352 if (Record && !Record->getDeclContext()->isRecord())
7353 AddPushedVisibilityAttribute(Record);
7356 /// \brief Determine whether the given integral value is representable within
7357 /// the given type T.
7358 static bool isRepresentableIntegerValue(ASTContext &Context,
7359 llvm::APSInt &Value,
7360 QualType T) {
7361 assert(T->isIntegralType(Context) && "Integral type required!");
7362 unsigned BitWidth = Context.getIntWidth(T);
7364 if (Value.isUnsigned() || Value.isNonNegative()) {
7365 if (T->isSignedIntegerType())
7366 --BitWidth;
7367 return Value.getActiveBits() <= BitWidth;
7369 return Value.getMinSignedBits() <= BitWidth;
7372 // \brief Given an integral type, return the next larger integral type
7373 // (or a NULL type of no such type exists).
7374 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
7375 // FIXME: Int128/UInt128 support, which also needs to be introduced into
7376 // enum checking below.
7377 assert(T->isIntegralType(Context) && "Integral type required!");
7378 const unsigned NumTypes = 4;
7379 QualType SignedIntegralTypes[NumTypes] = {
7380 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
7382 QualType UnsignedIntegralTypes[NumTypes] = {
7383 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
7384 Context.UnsignedLongLongTy
7387 unsigned BitWidth = Context.getTypeSize(T);
7388 QualType *Types = T->isSignedIntegerType()? SignedIntegralTypes
7389 : UnsignedIntegralTypes;
7390 for (unsigned I = 0; I != NumTypes; ++I)
7391 if (Context.getTypeSize(Types[I]) > BitWidth)
7392 return Types[I];
7394 return QualType();
7397 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
7398 EnumConstantDecl *LastEnumConst,
7399 SourceLocation IdLoc,
7400 IdentifierInfo *Id,
7401 Expr *Val) {
7402 unsigned IntWidth = Context.Target.getIntWidth();
7403 llvm::APSInt EnumVal(IntWidth);
7404 QualType EltTy;
7406 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
7407 Val = 0;
7409 if (Val) {
7410 if (Enum->isDependentType() || Val->isTypeDependent())
7411 EltTy = Context.DependentTy;
7412 else {
7413 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
7414 SourceLocation ExpLoc;
7415 if (!Val->isValueDependent() &&
7416 VerifyIntegerConstantExpression(Val, &EnumVal)) {
7417 Val = 0;
7418 } else {
7419 if (!getLangOptions().CPlusPlus) {
7420 // C99 6.7.2.2p2:
7421 // The expression that defines the value of an enumeration constant
7422 // shall be an integer constant expression that has a value
7423 // representable as an int.
7425 // Complain if the value is not representable in an int.
7426 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
7427 Diag(IdLoc, diag::ext_enum_value_not_int)
7428 << EnumVal.toString(10) << Val->getSourceRange()
7429 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
7430 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
7431 // Force the type of the expression to 'int'.
7432 ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast);
7436 if (Enum->isFixed()) {
7437 EltTy = Enum->getIntegerType();
7439 // C++0x [dcl.enum]p5:
7440 // ... if the initializing value of an enumerator cannot be
7441 // represented by the underlying type, the program is ill-formed.
7442 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
7443 if (getLangOptions().Microsoft) {
7444 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
7445 ImpCastExprToType(Val, EltTy, CK_IntegralCast);
7446 } else
7447 Diag(IdLoc, diag::err_enumerator_too_large)
7448 << EltTy;
7449 } else
7450 ImpCastExprToType(Val, EltTy, CK_IntegralCast);
7452 else {
7453 // C++0x [dcl.enum]p5:
7454 // If the underlying type is not fixed, the type of each enumerator
7455 // is the type of its initializing value:
7456 // - If an initializer is specified for an enumerator, the
7457 // initializing value has the same type as the expression.
7458 EltTy = Val->getType();
7464 if (!Val) {
7465 if (Enum->isDependentType())
7466 EltTy = Context.DependentTy;
7467 else if (!LastEnumConst) {
7468 // C++0x [dcl.enum]p5:
7469 // If the underlying type is not fixed, the type of each enumerator
7470 // is the type of its initializing value:
7471 // - If no initializer is specified for the first enumerator, the
7472 // initializing value has an unspecified integral type.
7474 // GCC uses 'int' for its unspecified integral type, as does
7475 // C99 6.7.2.2p3.
7476 if (Enum->isFixed()) {
7477 EltTy = Enum->getIntegerType();
7479 else {
7480 EltTy = Context.IntTy;
7482 } else {
7483 // Assign the last value + 1.
7484 EnumVal = LastEnumConst->getInitVal();
7485 ++EnumVal;
7486 EltTy = LastEnumConst->getType();
7488 // Check for overflow on increment.
7489 if (EnumVal < LastEnumConst->getInitVal()) {
7490 // C++0x [dcl.enum]p5:
7491 // If the underlying type is not fixed, the type of each enumerator
7492 // is the type of its initializing value:
7494 // - Otherwise the type of the initializing value is the same as
7495 // the type of the initializing value of the preceding enumerator
7496 // unless the incremented value is not representable in that type,
7497 // in which case the type is an unspecified integral type
7498 // sufficient to contain the incremented value. If no such type
7499 // exists, the program is ill-formed.
7500 QualType T = getNextLargerIntegralType(Context, EltTy);
7501 if (T.isNull() || Enum->isFixed()) {
7502 // There is no integral type larger enough to represent this
7503 // value. Complain, then allow the value to wrap around.
7504 EnumVal = LastEnumConst->getInitVal();
7505 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
7506 ++EnumVal;
7507 if (Enum->isFixed())
7508 // When the underlying type is fixed, this is ill-formed.
7509 Diag(IdLoc, diag::err_enumerator_wrapped)
7510 << EnumVal.toString(10)
7511 << EltTy;
7512 else
7513 Diag(IdLoc, diag::warn_enumerator_too_large)
7514 << EnumVal.toString(10);
7515 } else {
7516 EltTy = T;
7519 // Retrieve the last enumerator's value, extent that type to the
7520 // type that is supposed to be large enough to represent the incremented
7521 // value, then increment.
7522 EnumVal = LastEnumConst->getInitVal();
7523 EnumVal.setIsSigned(EltTy->isSignedIntegerType());
7524 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
7525 ++EnumVal;
7527 // If we're not in C++, diagnose the overflow of enumerator values,
7528 // which in C99 means that the enumerator value is not representable in
7529 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
7530 // permits enumerator values that are representable in some larger
7531 // integral type.
7532 if (!getLangOptions().CPlusPlus && !T.isNull())
7533 Diag(IdLoc, diag::warn_enum_value_overflow);
7534 } else if (!getLangOptions().CPlusPlus &&
7535 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
7536 // Enforce C99 6.7.2.2p2 even when we compute the next value.
7537 Diag(IdLoc, diag::ext_enum_value_not_int)
7538 << EnumVal.toString(10) << 1;
7543 if (!EltTy->isDependentType()) {
7544 // Make the enumerator value match the signedness and size of the
7545 // enumerator's type.
7546 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
7547 EnumVal.setIsSigned(EltTy->isSignedIntegerType());
7550 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
7551 Val, EnumVal);
7555 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
7556 SourceLocation IdLoc, IdentifierInfo *Id,
7557 AttributeList *Attr,
7558 SourceLocation EqualLoc, ExprTy *val) {
7559 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
7560 EnumConstantDecl *LastEnumConst =
7561 cast_or_null<EnumConstantDecl>(lastEnumConst);
7562 Expr *Val = static_cast<Expr*>(val);
7564 // The scope passed in may not be a decl scope. Zip up the scope tree until
7565 // we find one that is.
7566 S = getNonFieldDeclScope(S);
7568 // Verify that there isn't already something declared with this name in this
7569 // scope.
7570 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
7571 ForRedeclaration);
7572 if (PrevDecl && PrevDecl->isTemplateParameter()) {
7573 // Maybe we will complain about the shadowed template parameter.
7574 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
7575 // Just pretend that we didn't see the previous declaration.
7576 PrevDecl = 0;
7579 if (PrevDecl) {
7580 // When in C++, we may get a TagDecl with the same name; in this case the
7581 // enum constant will 'hide' the tag.
7582 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
7583 "Received TagDecl when not in C++!");
7584 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
7585 if (isa<EnumConstantDecl>(PrevDecl))
7586 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
7587 else
7588 Diag(IdLoc, diag::err_redefinition) << Id;
7589 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7590 return 0;
7594 // C++ [class.mem]p13:
7595 // If T is the name of a class, then each of the following shall have a
7596 // name different from T:
7597 // - every enumerator of every member of class T that is an enumerated
7598 // type
7599 if (CXXRecordDecl *Record
7600 = dyn_cast<CXXRecordDecl>(
7601 TheEnumDecl->getDeclContext()->getRedeclContext()))
7602 if (Record->getIdentifier() && Record->getIdentifier() == Id)
7603 Diag(IdLoc, diag::err_member_name_of_class) << Id;
7605 EnumConstantDecl *New =
7606 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
7608 if (New) {
7609 // Process attributes.
7610 if (Attr) ProcessDeclAttributeList(S, New, Attr);
7612 // Register this decl in the current scope stack.
7613 New->setAccess(TheEnumDecl->getAccess());
7614 PushOnScopeChains(New, S);
7617 return New;
7620 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
7621 SourceLocation RBraceLoc, Decl *EnumDeclX,
7622 Decl **Elements, unsigned NumElements,
7623 Scope *S, AttributeList *Attr) {
7624 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
7625 QualType EnumType = Context.getTypeDeclType(Enum);
7627 if (Attr)
7628 ProcessDeclAttributeList(S, Enum, Attr);
7630 if (Enum->isDependentType()) {
7631 for (unsigned i = 0; i != NumElements; ++i) {
7632 EnumConstantDecl *ECD =
7633 cast_or_null<EnumConstantDecl>(Elements[i]);
7634 if (!ECD) continue;
7636 ECD->setType(EnumType);
7639 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
7640 return;
7643 // TODO: If the result value doesn't fit in an int, it must be a long or long
7644 // long value. ISO C does not support this, but GCC does as an extension,
7645 // emit a warning.
7646 unsigned IntWidth = Context.Target.getIntWidth();
7647 unsigned CharWidth = Context.Target.getCharWidth();
7648 unsigned ShortWidth = Context.Target.getShortWidth();
7650 // Verify that all the values are okay, compute the size of the values, and
7651 // reverse the list.
7652 unsigned NumNegativeBits = 0;
7653 unsigned NumPositiveBits = 0;
7655 // Keep track of whether all elements have type int.
7656 bool AllElementsInt = true;
7658 for (unsigned i = 0; i != NumElements; ++i) {
7659 EnumConstantDecl *ECD =
7660 cast_or_null<EnumConstantDecl>(Elements[i]);
7661 if (!ECD) continue; // Already issued a diagnostic.
7663 const llvm::APSInt &InitVal = ECD->getInitVal();
7665 // Keep track of the size of positive and negative values.
7666 if (InitVal.isUnsigned() || InitVal.isNonNegative())
7667 NumPositiveBits = std::max(NumPositiveBits,
7668 (unsigned)InitVal.getActiveBits());
7669 else
7670 NumNegativeBits = std::max(NumNegativeBits,
7671 (unsigned)InitVal.getMinSignedBits());
7673 // Keep track of whether every enum element has type int (very commmon).
7674 if (AllElementsInt)
7675 AllElementsInt = ECD->getType() == Context.IntTy;
7678 // Figure out the type that should be used for this enum.
7679 QualType BestType;
7680 unsigned BestWidth;
7682 // C++0x N3000 [conv.prom]p3:
7683 // An rvalue of an unscoped enumeration type whose underlying
7684 // type is not fixed can be converted to an rvalue of the first
7685 // of the following types that can represent all the values of
7686 // the enumeration: int, unsigned int, long int, unsigned long
7687 // int, long long int, or unsigned long long int.
7688 // C99 6.4.4.3p2:
7689 // An identifier declared as an enumeration constant has type int.
7690 // The C99 rule is modified by a gcc extension
7691 QualType BestPromotionType;
7693 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
7694 // -fshort-enums is the equivalent to specifying the packed attribute on all
7695 // enum definitions.
7696 if (LangOpts.ShortEnums)
7697 Packed = true;
7699 if (Enum->isFixed()) {
7700 BestType = BestPromotionType = Enum->getIntegerType();
7701 // We don't need to set BestWidth, because BestType is going to be the type
7702 // of the enumerators, but we do anyway because otherwise some compilers
7703 // warn that it might be used uninitialized.
7704 BestWidth = CharWidth;
7706 else if (NumNegativeBits) {
7707 // If there is a negative value, figure out the smallest integer type (of
7708 // int/long/longlong) that fits.
7709 // If it's packed, check also if it fits a char or a short.
7710 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
7711 BestType = Context.SignedCharTy;
7712 BestWidth = CharWidth;
7713 } else if (Packed && NumNegativeBits <= ShortWidth &&
7714 NumPositiveBits < ShortWidth) {
7715 BestType = Context.ShortTy;
7716 BestWidth = ShortWidth;
7717 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
7718 BestType = Context.IntTy;
7719 BestWidth = IntWidth;
7720 } else {
7721 BestWidth = Context.Target.getLongWidth();
7723 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
7724 BestType = Context.LongTy;
7725 } else {
7726 BestWidth = Context.Target.getLongLongWidth();
7728 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
7729 Diag(Enum->getLocation(), diag::warn_enum_too_large);
7730 BestType = Context.LongLongTy;
7733 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
7734 } else {
7735 // If there is no negative value, figure out the smallest type that fits
7736 // all of the enumerator values.
7737 // If it's packed, check also if it fits a char or a short.
7738 if (Packed && NumPositiveBits <= CharWidth) {
7739 BestType = Context.UnsignedCharTy;
7740 BestPromotionType = Context.IntTy;
7741 BestWidth = CharWidth;
7742 } else if (Packed && NumPositiveBits <= ShortWidth) {
7743 BestType = Context.UnsignedShortTy;
7744 BestPromotionType = Context.IntTy;
7745 BestWidth = ShortWidth;
7746 } else if (NumPositiveBits <= IntWidth) {
7747 BestType = Context.UnsignedIntTy;
7748 BestWidth = IntWidth;
7749 BestPromotionType
7750 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
7751 ? Context.UnsignedIntTy : Context.IntTy;
7752 } else if (NumPositiveBits <=
7753 (BestWidth = Context.Target.getLongWidth())) {
7754 BestType = Context.UnsignedLongTy;
7755 BestPromotionType
7756 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
7757 ? Context.UnsignedLongTy : Context.LongTy;
7758 } else {
7759 BestWidth = Context.Target.getLongLongWidth();
7760 assert(NumPositiveBits <= BestWidth &&
7761 "How could an initializer get larger than ULL?");
7762 BestType = Context.UnsignedLongLongTy;
7763 BestPromotionType
7764 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
7765 ? Context.UnsignedLongLongTy : Context.LongLongTy;
7769 // Loop over all of the enumerator constants, changing their types to match
7770 // the type of the enum if needed.
7771 for (unsigned i = 0; i != NumElements; ++i) {
7772 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
7773 if (!ECD) continue; // Already issued a diagnostic.
7775 // Standard C says the enumerators have int type, but we allow, as an
7776 // extension, the enumerators to be larger than int size. If each
7777 // enumerator value fits in an int, type it as an int, otherwise type it the
7778 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
7779 // that X has type 'int', not 'unsigned'.
7781 // Determine whether the value fits into an int.
7782 llvm::APSInt InitVal = ECD->getInitVal();
7784 // If it fits into an integer type, force it. Otherwise force it to match
7785 // the enum decl type.
7786 QualType NewTy;
7787 unsigned NewWidth;
7788 bool NewSign;
7789 if (!getLangOptions().CPlusPlus &&
7790 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
7791 NewTy = Context.IntTy;
7792 NewWidth = IntWidth;
7793 NewSign = true;
7794 } else if (ECD->getType() == BestType) {
7795 // Already the right type!
7796 if (getLangOptions().CPlusPlus)
7797 // C++ [dcl.enum]p4: Following the closing brace of an
7798 // enum-specifier, each enumerator has the type of its
7799 // enumeration.
7800 ECD->setType(EnumType);
7801 continue;
7802 } else {
7803 NewTy = BestType;
7804 NewWidth = BestWidth;
7805 NewSign = BestType->isSignedIntegerType();
7808 // Adjust the APSInt value.
7809 InitVal = InitVal.extOrTrunc(NewWidth);
7810 InitVal.setIsSigned(NewSign);
7811 ECD->setInitVal(InitVal);
7813 // Adjust the Expr initializer and type.
7814 if (ECD->getInitExpr() &&
7815 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
7816 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
7817 CK_IntegralCast,
7818 ECD->getInitExpr(),
7819 /*base paths*/ 0,
7820 VK_RValue));
7821 if (getLangOptions().CPlusPlus)
7822 // C++ [dcl.enum]p4: Following the closing brace of an
7823 // enum-specifier, each enumerator has the type of its
7824 // enumeration.
7825 ECD->setType(EnumType);
7826 else
7827 ECD->setType(NewTy);
7830 Enum->completeDefinition(BestType, BestPromotionType,
7831 NumPositiveBits, NumNegativeBits);
7834 Decl *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc, Expr *expr) {
7835 StringLiteral *AsmString = cast<StringLiteral>(expr);
7837 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
7838 Loc, AsmString);
7839 CurContext->addDecl(New);
7840 return New;
7843 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
7844 SourceLocation PragmaLoc,
7845 SourceLocation NameLoc) {
7846 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
7848 if (PrevDecl) {
7849 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
7850 } else {
7851 (void)WeakUndeclaredIdentifiers.insert(
7852 std::pair<IdentifierInfo*,WeakInfo>
7853 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
7857 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
7858 IdentifierInfo* AliasName,
7859 SourceLocation PragmaLoc,
7860 SourceLocation NameLoc,
7861 SourceLocation AliasNameLoc) {
7862 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
7863 LookupOrdinaryName);
7864 WeakInfo W = WeakInfo(Name, NameLoc);
7866 if (PrevDecl) {
7867 if (!PrevDecl->hasAttr<AliasAttr>())
7868 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
7869 DeclApplyPragmaWeak(TUScope, ND, W);
7870 } else {
7871 (void)WeakUndeclaredIdentifiers.insert(
7872 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));