blob: e12902bff6bdd2f3fe381e61fa2e4b2b96061609 [file] [log] [blame]
Shih-wei Liaof8fd82b2010-02-10 11:10:31 -08001//===--- 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.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "SemaInit.h"
16#include "Lookup.h"
17#include "clang/Analysis/AnalysisContext.h"
18#include "clang/AST/APValue.h"
19#include "clang/AST/ASTConsumer.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/CXXInheritance.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/StmtCXX.h"
25#include "clang/Parse/DeclSpec.h"
26#include "clang/Parse/ParseDiagnostic.h"
27#include "clang/Parse/Template.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/SourceManager.h"
30#include "clang/Basic/TargetInfo.h"
31// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
32#include "clang/Lex/Preprocessor.h"
33#include "clang/Lex/HeaderSearch.h"
34#include "llvm/ADT/Triple.h"
35#include <algorithm>
36#include <cstring>
37#include <functional>
38using namespace clang;
39
40/// getDeclName - Return a pretty name for the specified decl if possible, or
41/// an empty string if not. This is used for pretty crash reporting.
42std::string Sema::getDeclName(DeclPtrTy d) {
43 Decl *D = d.getAs<Decl>();
44 if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(D))
45 return DN->getQualifiedNameAsString();
46 return "";
47}
48
49Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(DeclPtrTy Ptr) {
50 return DeclGroupPtrTy::make(DeclGroupRef(Ptr.getAs<Decl>()));
51}
52
53/// \brief If the identifier refers to a type name within this scope,
54/// return the declaration of that type.
55///
56/// This routine performs ordinary name lookup of the identifier II
57/// within the given scope, with optional C++ scope specifier SS, to
58/// determine whether the name refers to a type. If so, returns an
59/// opaque pointer (actually a QualType) corresponding to that
60/// type. Otherwise, returns NULL.
61///
62/// If name lookup results in an ambiguity, this routine will complain
63/// and then return NULL.
64Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
65 Scope *S, const CXXScopeSpec *SS,
66 bool isClassName,
67 TypeTy *ObjectTypePtr) {
68 // Determine where we will perform name lookup.
69 DeclContext *LookupCtx = 0;
70 if (ObjectTypePtr) {
71 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
72 if (ObjectType->isRecordType())
73 LookupCtx = computeDeclContext(ObjectType);
74 } else if (SS && SS->isSet()) {
75 LookupCtx = computeDeclContext(*SS, false);
76
77 if (!LookupCtx) {
78 if (isDependentScopeSpecifier(*SS)) {
79 // C++ [temp.res]p3:
80 // A qualified-id that refers to a type and in which the
81 // nested-name-specifier depends on a template-parameter (14.6.2)
82 // shall be prefixed by the keyword typename to indicate that the
83 // qualified-id denotes a type, forming an
84 // elaborated-type-specifier (7.1.5.3).
85 //
86 // We therefore do not perform any name lookup if the result would
87 // refer to a member of an unknown specialization.
88 if (!isClassName)
89 return 0;
90
91 // We know from the grammar that this name refers to a type, so build a
92 // TypenameType node to describe the type.
93 // FIXME: Record somewhere that this TypenameType node has no "typename"
94 // keyword associated with it.
95 return CheckTypenameType((NestedNameSpecifier *)SS->getScopeRep(),
96 II, SS->getRange()).getAsOpaquePtr();
97 }
98
99 return 0;
100 }
101
102 if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(*SS))
103 return 0;
104 }
105
106 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
107 // lookup for class-names.
108 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
109 LookupOrdinaryName;
110 LookupResult Result(*this, &II, NameLoc, Kind);
111 if (LookupCtx) {
112 // Perform "qualified" name lookup into the declaration context we
113 // computed, which is either the type of the base of a member access
114 // expression or the declaration context associated with a prior
115 // nested-name-specifier.
116 LookupQualifiedName(Result, LookupCtx);
117
118 if (ObjectTypePtr && Result.empty()) {
119 // C++ [basic.lookup.classref]p3:
120 // If the unqualified-id is ~type-name, the type-name is looked up
121 // in the context of the entire postfix-expression. If the type T of
122 // the object expression is of a class type C, the type-name is also
123 // looked up in the scope of class C. At least one of the lookups shall
124 // find a name that refers to (possibly cv-qualified) T.
125 LookupName(Result, S);
126 }
127 } else {
128 // Perform unqualified name lookup.
129 LookupName(Result, S);
130 }
131
132 NamedDecl *IIDecl = 0;
133 switch (Result.getResultKind()) {
134 case LookupResult::NotFound:
135 case LookupResult::NotFoundInCurrentInstantiation:
136 case LookupResult::FoundOverloaded:
137 case LookupResult::FoundUnresolvedValue:
138 Result.suppressDiagnostics();
139 return 0;
140
141 case LookupResult::Ambiguous:
142 // Recover from type-hiding ambiguities by hiding the type. We'll
143 // do the lookup again when looking for an object, and we can
144 // diagnose the error then. If we don't do this, then the error
145 // about hiding the type will be immediately followed by an error
146 // that only makes sense if the identifier was treated like a type.
147 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
148 Result.suppressDiagnostics();
149 return 0;
150 }
151
152 // Look to see if we have a type anywhere in the list of results.
153 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
154 Res != ResEnd; ++Res) {
155 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
156 if (!IIDecl ||
157 (*Res)->getLocation().getRawEncoding() <
158 IIDecl->getLocation().getRawEncoding())
159 IIDecl = *Res;
160 }
161 }
162
163 if (!IIDecl) {
164 // None of the entities we found is a type, so there is no way
165 // to even assume that the result is a type. In this case, don't
166 // complain about the ambiguity. The parser will either try to
167 // perform this lookup again (e.g., as an object name), which
168 // will produce the ambiguity, or will complain that it expected
169 // a type name.
170 Result.suppressDiagnostics();
171 return 0;
172 }
173
174 // We found a type within the ambiguous lookup; diagnose the
175 // ambiguity and then return that type. This might be the right
176 // answer, or it might not be, but it suppresses any attempt to
177 // perform the name lookup again.
178 break;
179
180 case LookupResult::Found:
181 IIDecl = Result.getFoundDecl();
182 break;
183 }
184
185 assert(IIDecl && "Didn't find decl");
186
187 QualType T;
188 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
189 DiagnoseUseOfDecl(IIDecl, NameLoc);
190
191 // C++ [temp.local]p2:
192 // Within the scope of a class template specialization or
193 // partial specialization, when the injected-class-name is
194 // not followed by a <, it is equivalent to the
195 // injected-class-name followed by the template-argument s
196 // of the class template specialization or partial
197 // specialization enclosed in <>.
198 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD))
199 if (RD->isInjectedClassName())
200 if (ClassTemplateDecl *Template = RD->getDescribedClassTemplate())
201 T = Template->getInjectedClassNameType(Context);
202
203 if (T.isNull())
204 T = Context.getTypeDeclType(TD);
205
206 if (SS)
207 T = getQualifiedNameType(*SS, T);
208
209 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
210 T = Context.getObjCInterfaceType(IDecl);
211 } else if (UnresolvedUsingTypenameDecl *UUDecl =
212 dyn_cast<UnresolvedUsingTypenameDecl>(IIDecl)) {
213 // FIXME: preserve source structure information.
214 T = Context.getTypenameType(UUDecl->getTargetNestedNameSpecifier(), &II);
215 } else {
216 // If it's not plausibly a type, suppress diagnostics.
217 Result.suppressDiagnostics();
218 return 0;
219 }
220
221 return T.getAsOpaquePtr();
222}
223
224/// isTagName() - This method is called *for error recovery purposes only*
225/// to determine if the specified name is a valid tag name ("struct foo"). If
226/// so, this returns the TST for the tag corresponding to it (TST_enum,
227/// TST_union, TST_struct, TST_class). This is used to diagnose cases in C
228/// where the user forgot to specify the tag.
229DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
230 // Do a tag name lookup in this scope.
231 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
232 LookupName(R, S, false);
233 R.suppressDiagnostics();
234 if (R.getResultKind() == LookupResult::Found)
235 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
236 switch (TD->getTagKind()) {
237 case TagDecl::TK_struct: return DeclSpec::TST_struct;
238 case TagDecl::TK_union: return DeclSpec::TST_union;
239 case TagDecl::TK_class: return DeclSpec::TST_class;
240 case TagDecl::TK_enum: return DeclSpec::TST_enum;
241 }
242 }
243
244 return DeclSpec::TST_unspecified;
245}
246
247bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
248 SourceLocation IILoc,
249 Scope *S,
250 const CXXScopeSpec *SS,
251 TypeTy *&SuggestedType) {
252 // We don't have anything to suggest (yet).
253 SuggestedType = 0;
254
255 // There may have been a typo in the name of the type. Look up typo
256 // results, in case we have something that we can suggest.
257 LookupResult Lookup(*this, &II, IILoc, LookupOrdinaryName,
258 NotForRedeclaration);
259
260 // FIXME: It would be nice if we could correct for typos in built-in
261 // names, such as "itn" for "int".
262
263 if (CorrectTypo(Lookup, S, SS) && Lookup.isSingleResult()) {
264 NamedDecl *Result = Lookup.getAsSingle<NamedDecl>();
265 if ((isa<TypeDecl>(Result) || isa<ObjCInterfaceDecl>(Result)) &&
266 !Result->isInvalidDecl()) {
267 // We found a similarly-named type or interface; suggest that.
268 if (!SS || !SS->isSet())
269 Diag(IILoc, diag::err_unknown_typename_suggest)
270 << &II << Lookup.getLookupName()
271 << CodeModificationHint::CreateReplacement(SourceRange(IILoc),
272 Result->getNameAsString());
273 else if (DeclContext *DC = computeDeclContext(*SS, false))
274 Diag(IILoc, diag::err_unknown_nested_typename_suggest)
275 << &II << DC << Lookup.getLookupName() << SS->getRange()
276 << CodeModificationHint::CreateReplacement(SourceRange(IILoc),
277 Result->getNameAsString());
278 else
279 llvm_unreachable("could not have corrected a typo here");
280
281 Diag(Result->getLocation(), diag::note_previous_decl)
282 << Result->getDeclName();
283
284 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS);
285 return true;
286 }
287 }
288
289 // FIXME: Should we move the logic that tries to recover from a missing tag
290 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
291
292 if (!SS || (!SS->isSet() && !SS->isInvalid()))
293 Diag(IILoc, diag::err_unknown_typename) << &II;
294 else if (DeclContext *DC = computeDeclContext(*SS, false))
295 Diag(IILoc, diag::err_typename_nested_not_found)
296 << &II << DC << SS->getRange();
297 else if (isDependentScopeSpecifier(*SS)) {
298 Diag(SS->getRange().getBegin(), diag::err_typename_missing)
299 << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
300 << SourceRange(SS->getRange().getBegin(), IILoc)
301 << CodeModificationHint::CreateInsertion(SS->getRange().getBegin(),
302 "typename ");
303 SuggestedType = ActOnTypenameType(SourceLocation(), *SS, II, IILoc).get();
304 } else {
305 assert(SS && SS->isInvalid() &&
306 "Invalid scope specifier has already been diagnosed");
307 }
308
309 return true;
310}
311
312// Determines the context to return to after temporarily entering a
313// context. This depends in an unnecessarily complicated way on the
314// exact ordering of callbacks from the parser.
315DeclContext *Sema::getContainingDC(DeclContext *DC) {
316
317 // Functions defined inline within classes aren't parsed until we've
318 // finished parsing the top-level class, so the top-level class is
319 // the context we'll need to return to.
320 if (isa<FunctionDecl>(DC)) {
321 DC = DC->getLexicalParent();
322
323 // A function not defined within a class will always return to its
324 // lexical context.
325 if (!isa<CXXRecordDecl>(DC))
326 return DC;
327
328 // A C++ inline method/friend is parsed *after* the topmost class
329 // it was declared in is fully parsed ("complete"); the topmost
330 // class is the context we need to return to.
331 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
332 DC = RD;
333
334 // Return the declaration context of the topmost class the inline method is
335 // declared in.
336 return DC;
337 }
338
339 if (isa<ObjCMethodDecl>(DC))
340 return Context.getTranslationUnitDecl();
341
342 return DC->getLexicalParent();
343}
344
345void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
346 assert(getContainingDC(DC) == CurContext &&
347 "The next DeclContext should be lexically contained in the current one.");
348 CurContext = DC;
349 S->setEntity(DC);
350}
351
352void Sema::PopDeclContext() {
353 assert(CurContext && "DeclContext imbalance!");
354
355 CurContext = getContainingDC(CurContext);
356}
357
358/// EnterDeclaratorContext - Used when we must lookup names in the context
359/// of a declarator's nested name specifier.
360///
361void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
362 // C++0x [basic.lookup.unqual]p13:
363 // A name used in the definition of a static data member of class
364 // X (after the qualified-id of the static member) is looked up as
365 // if the name was used in a member function of X.
366 // C++0x [basic.lookup.unqual]p14:
367 // If a variable member of a namespace is defined outside of the
368 // scope of its namespace then any name used in the definition of
369 // the variable member (after the declarator-id) is looked up as
370 // if the definition of the variable member occurred in its
371 // namespace.
372 // Both of these imply that we should push a scope whose context
373 // is the semantic context of the declaration. We can't use
374 // PushDeclContext here because that context is not necessarily
375 // lexically contained in the current context. Fortunately,
376 // the containing scope should have the appropriate information.
377
378 assert(!S->getEntity() && "scope already has entity");
379
380#ifndef NDEBUG
381 Scope *Ancestor = S->getParent();
382 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
383 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
384#endif
385
386 CurContext = DC;
387 S->setEntity(DC);
388}
389
390void Sema::ExitDeclaratorContext(Scope *S) {
391 assert(S->getEntity() == CurContext && "Context imbalance!");
392
393 // Switch back to the lexical context. The safety of this is
394 // enforced by an assert in EnterDeclaratorContext.
395 Scope *Ancestor = S->getParent();
396 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
397 CurContext = (DeclContext*) Ancestor->getEntity();
398
399 // We don't need to do anything with the scope, which is going to
400 // disappear.
401}
402
403/// \brief Determine whether we allow overloading of the function
404/// PrevDecl with another declaration.
405///
406/// This routine determines whether overloading is possible, not
407/// whether some new function is actually an overload. It will return
408/// true in C++ (where we can always provide overloads) or, as an
409/// extension, in C when the previous function is already an
410/// overloaded function declaration or has the "overloadable"
411/// attribute.
412static bool AllowOverloadingOfFunction(LookupResult &Previous,
413 ASTContext &Context) {
414 if (Context.getLangOptions().CPlusPlus)
415 return true;
416
417 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
418 return true;
419
420 return (Previous.getResultKind() == LookupResult::Found
421 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
422}
423
424/// Add this decl to the scope shadowed decl chains.
425void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
426 // Move up the scope chain until we find the nearest enclosing
427 // non-transparent context. The declaration will be introduced into this
428 // scope.
429 while (S->getEntity() &&
430 ((DeclContext *)S->getEntity())->isTransparentContext())
431 S = S->getParent();
432
433 // Add scoped declarations into their context, so that they can be
434 // found later. Declarations without a context won't be inserted
435 // into any context.
436 if (AddToContext)
437 CurContext->addDecl(D);
438
439 // Out-of-line function and variable definitions should not be pushed into
440 // scope.
441 if ((isa<FunctionTemplateDecl>(D) &&
442 cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->isOutOfLine()) ||
443 (isa<FunctionDecl>(D) &&
444 (cast<FunctionDecl>(D)->isFunctionTemplateSpecialization() ||
445 cast<FunctionDecl>(D)->isOutOfLine())) ||
446 (isa<VarDecl>(D) && cast<VarDecl>(D)->isOutOfLine()))
447 return;
448
449 // If this replaces anything in the current scope,
450 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
451 IEnd = IdResolver.end();
452 for (; I != IEnd; ++I) {
453 if (S->isDeclScope(DeclPtrTy::make(*I)) && D->declarationReplaces(*I)) {
454 S->RemoveDecl(DeclPtrTy::make(*I));
455 IdResolver.RemoveDecl(*I);
456
457 // Should only need to replace one decl.
458 break;
459 }
460 }
461
462 S->AddDecl(DeclPtrTy::make(D));
463 IdResolver.AddDecl(D);
464}
465
466bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S) {
467 return IdResolver.isDeclInScope(D, Ctx, Context, S);
468}
469
470static bool isOutOfScopePreviousDeclaration(NamedDecl *,
471 DeclContext*,
472 ASTContext&);
473
474/// Filters out lookup results that don't fall within the given scope
475/// as determined by isDeclInScope.
476static void FilterLookupForScope(Sema &SemaRef, LookupResult &R,
477 DeclContext *Ctx, Scope *S,
478 bool ConsiderLinkage) {
479 LookupResult::Filter F = R.makeFilter();
480 while (F.hasNext()) {
481 NamedDecl *D = F.next();
482
483 if (SemaRef.isDeclInScope(D, Ctx, S))
484 continue;
485
486 if (ConsiderLinkage &&
487 isOutOfScopePreviousDeclaration(D, Ctx, SemaRef.Context))
488 continue;
489
490 F.erase();
491 }
492
493 F.done();
494}
495
496static bool isUsingDecl(NamedDecl *D) {
497 return isa<UsingShadowDecl>(D) ||
498 isa<UnresolvedUsingTypenameDecl>(D) ||
499 isa<UnresolvedUsingValueDecl>(D);
500}
501
502/// Removes using shadow declarations from the lookup results.
503static void RemoveUsingDecls(LookupResult &R) {
504 LookupResult::Filter F = R.makeFilter();
505 while (F.hasNext())
506 if (isUsingDecl(F.next()))
507 F.erase();
508
509 F.done();
510}
511
512static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
513 if (D->isInvalidDecl())
514 return false;
515
516 if (D->isUsed() || D->hasAttr<UnusedAttr>())
517 return false;
518
519 // White-list anything that isn't a local variable.
520 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
521 !D->getDeclContext()->isFunctionOrMethod())
522 return false;
523
524 // Types of valid local variables should be complete, so this should succeed.
525 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
526 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
527 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
528 if (!RD->hasTrivialConstructor())
529 return false;
530 if (!RD->hasTrivialDestructor())
531 return false;
532 }
533 }
534 }
535
536 return true;
537}
538
539void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
540 if (S->decl_empty()) return;
541 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
542 "Scope shouldn't contain decls!");
543
544 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
545 I != E; ++I) {
546 Decl *TmpD = (*I).getAs<Decl>();
547 assert(TmpD && "This decl didn't get pushed??");
548
549 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
550 NamedDecl *D = cast<NamedDecl>(TmpD);
551
552 if (!D->getDeclName()) continue;
553
554 // Diagnose unused variables in this scope.
555 if (ShouldDiagnoseUnusedDecl(D))
556 Diag(D->getLocation(), diag::warn_unused_variable) << D->getDeclName();
557
558 // Remove this name from our lexical scope.
559 IdResolver.RemoveDecl(D);
560 }
561}
562
563/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
564/// return 0 if one not found.
565///
566/// \param Id the name of the Objective-C class we're looking for. If
567/// typo-correction fixes this name, the Id will be updated
568/// to the fixed name.
569///
570/// \param RecoverLoc if provided, this routine will attempt to
571/// recover from a typo in the name of an existing Objective-C class
572/// and, if successful, will return the lookup that results from
573/// typo-correction.
574ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
575 SourceLocation RecoverLoc) {
576 // The third "scope" argument is 0 since we aren't enabling lazy built-in
577 // creation from this context.
578 NamedDecl *IDecl = LookupSingleName(TUScope, Id, LookupOrdinaryName);
579
580 if (!IDecl && !RecoverLoc.isInvalid()) {
581 // Perform typo correction at the given location, but only if we
582 // find an Objective-C class name.
583 LookupResult R(*this, Id, RecoverLoc, LookupOrdinaryName);
584 if (CorrectTypo(R, TUScope, 0) &&
585 (IDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
586 Diag(RecoverLoc, diag::err_undef_interface_suggest)
587 << Id << IDecl->getDeclName()
588 << CodeModificationHint::CreateReplacement(RecoverLoc,
589 IDecl->getNameAsString());
590 Diag(IDecl->getLocation(), diag::note_previous_decl)
591 << IDecl->getDeclName();
592
593 Id = IDecl->getIdentifier();
594 }
595 }
596
597 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
598}
599
600/// getNonFieldDeclScope - Retrieves the innermost scope, starting
601/// from S, where a non-field would be declared. This routine copes
602/// with the difference between C and C++ scoping rules in structs and
603/// unions. For example, the following code is well-formed in C but
604/// ill-formed in C++:
605/// @code
606/// struct S6 {
607/// enum { BAR } e;
608/// };
609///
610/// void test_S6() {
611/// struct S6 a;
612/// a.e = BAR;
613/// }
614/// @endcode
615/// For the declaration of BAR, this routine will return a different
616/// scope. The scope S will be the scope of the unnamed enumeration
617/// within S6. In C++, this routine will return the scope associated
618/// with S6, because the enumeration's scope is a transparent
619/// context but structures can contain non-field names. In C, this
620/// routine will return the translation unit scope, since the
621/// enumeration's scope is a transparent context and structures cannot
622/// contain non-field names.
623Scope *Sema::getNonFieldDeclScope(Scope *S) {
624 while (((S->getFlags() & Scope::DeclScope) == 0) ||
625 (S->getEntity() &&
626 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
627 (S->isClassScope() && !getLangOptions().CPlusPlus))
628 S = S->getParent();
629 return S;
630}
631
632void Sema::InitBuiltinVaListType() {
633 if (!Context.getBuiltinVaListType().isNull())
634 return;
635
636 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
637 NamedDecl *VaDecl = LookupSingleName(TUScope, VaIdent, LookupOrdinaryName);
638 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
639 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
640}
641
642/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
643/// file scope. lazily create a decl for it. ForRedeclaration is true
644/// if we're creating this built-in in anticipation of redeclaring the
645/// built-in.
646NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
647 Scope *S, bool ForRedeclaration,
648 SourceLocation Loc) {
649 Builtin::ID BID = (Builtin::ID)bid;
650
651 if (Context.BuiltinInfo.hasVAListUse(BID))
652 InitBuiltinVaListType();
653
654 ASTContext::GetBuiltinTypeError Error;
655 QualType R = Context.GetBuiltinType(BID, Error);
656 switch (Error) {
657 case ASTContext::GE_None:
658 // Okay
659 break;
660
661 case ASTContext::GE_Missing_stdio:
662 if (ForRedeclaration)
663 Diag(Loc, diag::err_implicit_decl_requires_stdio)
664 << Context.BuiltinInfo.GetName(BID);
665 return 0;
666
667 case ASTContext::GE_Missing_setjmp:
668 if (ForRedeclaration)
669 Diag(Loc, diag::err_implicit_decl_requires_setjmp)
670 << Context.BuiltinInfo.GetName(BID);
671 return 0;
672 }
673
674 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
675 Diag(Loc, diag::ext_implicit_lib_function_decl)
676 << Context.BuiltinInfo.GetName(BID)
677 << R;
678 if (Context.BuiltinInfo.getHeaderName(BID) &&
679 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl)
680 != Diagnostic::Ignored)
681 Diag(Loc, diag::note_please_include_header)
682 << Context.BuiltinInfo.getHeaderName(BID)
683 << Context.BuiltinInfo.GetName(BID);
684 }
685
686 FunctionDecl *New = FunctionDecl::Create(Context,
687 Context.getTranslationUnitDecl(),
688 Loc, II, R, /*TInfo=*/0,
689 FunctionDecl::Extern, false,
690 /*hasPrototype=*/true);
691 New->setImplicit();
692
693 // Create Decl objects for each parameter, adding them to the
694 // FunctionDecl.
695 if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
696 llvm::SmallVector<ParmVarDecl*, 16> Params;
697 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
698 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
699 FT->getArgType(i), /*TInfo=*/0,
700 VarDecl::None, 0));
701 New->setParams(Context, Params.data(), Params.size());
702 }
703
704 AddKnownFunctionAttributes(New);
705
706 // TUScope is the translation-unit scope to insert this function into.
707 // FIXME: This is hideous. We need to teach PushOnScopeChains to
708 // relate Scopes to DeclContexts, and probably eliminate CurContext
709 // entirely, but we're not there yet.
710 DeclContext *SavedContext = CurContext;
711 CurContext = Context.getTranslationUnitDecl();
712 PushOnScopeChains(New, TUScope);
713 CurContext = SavedContext;
714 return New;
715}
716
717/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
718/// same name and scope as a previous declaration 'Old'. Figure out
719/// how to resolve this situation, merging decls or emitting
720/// diagnostics as appropriate. If there was an error, set New to be invalid.
721///
722void Sema::MergeTypeDefDecl(TypedefDecl *New, LookupResult &OldDecls) {
723 // If the new decl is known invalid already, don't bother doing any
724 // merging checks.
725 if (New->isInvalidDecl()) return;
726
727 // Allow multiple definitions for ObjC built-in typedefs.
728 // FIXME: Verify the underlying types are equivalent!
729 if (getLangOptions().ObjC1) {
730 const IdentifierInfo *TypeID = New->getIdentifier();
731 switch (TypeID->getLength()) {
732 default: break;
733 case 2:
734 if (!TypeID->isStr("id"))
735 break;
736 Context.ObjCIdRedefinitionType = New->getUnderlyingType();
737 // Install the built-in type for 'id', ignoring the current definition.
738 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
739 return;
740 case 5:
741 if (!TypeID->isStr("Class"))
742 break;
743 Context.ObjCClassRedefinitionType = New->getUnderlyingType();
744 // Install the built-in type for 'Class', ignoring the current definition.
745 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
746 return;
747 case 3:
748 if (!TypeID->isStr("SEL"))
749 break;
750 Context.ObjCSelRedefinitionType = New->getUnderlyingType();
751 // Install the built-in type for 'SEL', ignoring the current definition.
752 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
753 return;
754 case 8:
755 if (!TypeID->isStr("Protocol"))
756 break;
757 Context.setObjCProtoType(New->getUnderlyingType());
758 return;
759 }
760 // Fall through - the typedef name was not a builtin type.
761 }
762
763 // Verify the old decl was also a type.
764 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
765 if (!Old) {
766 Diag(New->getLocation(), diag::err_redefinition_different_kind)
767 << New->getDeclName();
768
769 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
770 if (OldD->getLocation().isValid())
771 Diag(OldD->getLocation(), diag::note_previous_definition);
772
773 return New->setInvalidDecl();
774 }
775
776 // If the old declaration is invalid, just give up here.
777 if (Old->isInvalidDecl())
778 return New->setInvalidDecl();
779
780 // Determine the "old" type we'll use for checking and diagnostics.
781 QualType OldType;
782 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
783 OldType = OldTypedef->getUnderlyingType();
784 else
785 OldType = Context.getTypeDeclType(Old);
786
787 // If the typedef types are not identical, reject them in all languages and
788 // with any extensions enabled.
789
790 if (OldType != New->getUnderlyingType() &&
791 Context.getCanonicalType(OldType) !=
792 Context.getCanonicalType(New->getUnderlyingType())) {
793 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
794 << New->getUnderlyingType() << OldType;
795 if (Old->getLocation().isValid())
796 Diag(Old->getLocation(), diag::note_previous_definition);
797 return New->setInvalidDecl();
798 }
799
800 // The types match. Link up the redeclaration chain if the old
801 // declaration was a typedef.
802 // FIXME: this is a potential source of wierdness if the type
803 // spellings don't match exactly.
804 if (isa<TypedefDecl>(Old))
805 New->setPreviousDeclaration(cast<TypedefDecl>(Old));
806
807 if (getLangOptions().Microsoft)
808 return;
809
810 if (getLangOptions().CPlusPlus) {
811 // C++ [dcl.typedef]p2:
812 // In a given non-class scope, a typedef specifier can be used to
813 // redefine the name of any type declared in that scope to refer
814 // to the type to which it already refers.
815 if (!isa<CXXRecordDecl>(CurContext))
816 return;
817
818 // C++0x [dcl.typedef]p4:
819 // In a given class scope, a typedef specifier can be used to redefine
820 // any class-name declared in that scope that is not also a typedef-name
821 // to refer to the type to which it already refers.
822 //
823 // This wording came in via DR424, which was a correction to the
824 // wording in DR56, which accidentally banned code like:
825 //
826 // struct S {
827 // typedef struct A { } A;
828 // };
829 //
830 // in the C++03 standard. We implement the C++0x semantics, which
831 // allow the above but disallow
832 //
833 // struct S {
834 // typedef int I;
835 // typedef int I;
836 // };
837 //
838 // since that was the intent of DR56.
839 if (!isa<TypedefDecl >(Old))
840 return;
841
842 Diag(New->getLocation(), diag::err_redefinition)
843 << New->getDeclName();
844 Diag(Old->getLocation(), diag::note_previous_definition);
845 return New->setInvalidDecl();
846 }
847
848 // If we have a redefinition of a typedef in C, emit a warning. This warning
849 // is normally mapped to an error, but can be controlled with
850 // -Wtypedef-redefinition. If either the original or the redefinition is
851 // in a system header, don't emit this for compatibility with GCC.
852 if (PP.getDiagnostics().getSuppressSystemWarnings() &&
853 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
854 Context.getSourceManager().isInSystemHeader(New->getLocation())))
855 return;
856
857 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
858 << New->getDeclName();
859 Diag(Old->getLocation(), diag::note_previous_definition);
860 return;
861}
862
863/// DeclhasAttr - returns true if decl Declaration already has the target
864/// attribute.
865static bool
866DeclHasAttr(const Decl *decl, const Attr *target) {
867 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
868 if (attr->getKind() == target->getKind())
869 return true;
870
871 return false;
872}
873
874/// MergeAttributes - append attributes from the Old decl to the New one.
875static void MergeAttributes(Decl *New, Decl *Old, ASTContext &C) {
876 for (const Attr *attr = Old->getAttrs(); attr; attr = attr->getNext()) {
877 if (!DeclHasAttr(New, attr) && attr->isMerged()) {
878 Attr *NewAttr = attr->clone(C);
879 NewAttr->setInherited(true);
880 New->addAttr(NewAttr);
881 }
882 }
883}
884
885/// Used in MergeFunctionDecl to keep track of function parameters in
886/// C.
887struct GNUCompatibleParamWarning {
888 ParmVarDecl *OldParm;
889 ParmVarDecl *NewParm;
890 QualType PromotedType;
891};
892
893
894/// getSpecialMember - get the special member enum for a method.
895static Sema::CXXSpecialMember getSpecialMember(ASTContext &Ctx,
896 const CXXMethodDecl *MD) {
897 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
898 if (Ctor->isDefaultConstructor())
899 return Sema::CXXDefaultConstructor;
900 if (Ctor->isCopyConstructor())
901 return Sema::CXXCopyConstructor;
902 }
903
904 if (isa<CXXDestructorDecl>(MD))
905 return Sema::CXXDestructor;
906
907 assert(MD->isCopyAssignment() && "Must have copy assignment operator");
908 return Sema::CXXCopyAssignment;
909}
910
911/// MergeFunctionDecl - We just parsed a function 'New' from
912/// declarator D which has the same name and scope as a previous
913/// declaration 'Old'. Figure out how to resolve this situation,
914/// merging decls or emitting diagnostics as appropriate.
915///
916/// In C++, New and Old must be declarations that are not
917/// overloaded. Use IsOverload to determine whether New and Old are
918/// overloaded, and to select the Old declaration that New should be
919/// merged with.
920///
921/// Returns true if there was an error, false otherwise.
922bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
923 // Verify the old decl was also a function.
924 FunctionDecl *Old = 0;
925 if (FunctionTemplateDecl *OldFunctionTemplate
926 = dyn_cast<FunctionTemplateDecl>(OldD))
927 Old = OldFunctionTemplate->getTemplatedDecl();
928 else
929 Old = dyn_cast<FunctionDecl>(OldD);
930 if (!Old) {
931 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
932 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
933 Diag(Shadow->getTargetDecl()->getLocation(),
934 diag::note_using_decl_target);
935 Diag(Shadow->getUsingDecl()->getLocation(),
936 diag::note_using_decl) << 0;
937 return true;
938 }
939
940 Diag(New->getLocation(), diag::err_redefinition_different_kind)
941 << New->getDeclName();
942 Diag(OldD->getLocation(), diag::note_previous_definition);
943 return true;
944 }
945
946 // Determine whether the previous declaration was a definition,
947 // implicit declaration, or a declaration.
948 diag::kind PrevDiag;
949 if (Old->isThisDeclarationADefinition())
950 PrevDiag = diag::note_previous_definition;
951 else if (Old->isImplicit())
952 PrevDiag = diag::note_previous_implicit_declaration;
953 else
954 PrevDiag = diag::note_previous_declaration;
955
956 QualType OldQType = Context.getCanonicalType(Old->getType());
957 QualType NewQType = Context.getCanonicalType(New->getType());
958
959 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
960 New->getStorageClass() == FunctionDecl::Static &&
961 Old->getStorageClass() != FunctionDecl::Static) {
962 Diag(New->getLocation(), diag::err_static_non_static)
963 << New;
964 Diag(Old->getLocation(), PrevDiag);
965 return true;
966 }
967
968 // If a function is first declared with a calling convention, but is
969 // later declared or defined without one, the second decl assumes the
970 // calling convention of the first.
971 //
972 // For the new decl, we have to look at the NON-canonical type to tell the
973 // difference between a function that really doesn't have a calling
974 // convention and one that is declared cdecl. That's because in
975 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
976 // because it is the default calling convention.
977 //
978 // Note also that we DO NOT return at this point, because we still have
979 // other tests to run.
980 const FunctionType *OldType = OldQType->getAs<FunctionType>();
981 const FunctionType *NewType = New->getType()->getAs<FunctionType>();
982 if (OldType->getCallConv() != CC_Default &&
983 NewType->getCallConv() == CC_Default) {
984 NewQType = Context.getCallConvType(NewQType, OldType->getCallConv());
985 New->setType(NewQType);
986 NewQType = Context.getCanonicalType(NewQType);
987 } else if (!Context.isSameCallConv(OldType->getCallConv(),
988 NewType->getCallConv())) {
989 // Calling conventions really aren't compatible, so complain.
990 Diag(New->getLocation(), diag::err_cconv_change)
991 << FunctionType::getNameForCallConv(NewType->getCallConv())
992 << (OldType->getCallConv() == CC_Default)
993 << (OldType->getCallConv() == CC_Default ? "" :
994 FunctionType::getNameForCallConv(OldType->getCallConv()));
995 Diag(Old->getLocation(), diag::note_previous_declaration);
996 return true;
997 }
998
999 // FIXME: diagnose the other way around?
1000 if (OldType->getNoReturnAttr() && !NewType->getNoReturnAttr()) {
1001 NewQType = Context.getNoReturnType(NewQType);
1002 New->setType(NewQType);
1003 assert(NewQType.isCanonical());
1004 }
1005
1006 if (getLangOptions().CPlusPlus) {
1007 // (C++98 13.1p2):
1008 // Certain function declarations cannot be overloaded:
1009 // -- Function declarations that differ only in the return type
1010 // cannot be overloaded.
1011 QualType OldReturnType
1012 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
1013 QualType NewReturnType
1014 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
1015 if (OldReturnType != NewReturnType) {
1016 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
1017 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1018 return true;
1019 }
1020
1021 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
1022 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
1023 if (OldMethod && NewMethod) {
1024 if (!NewMethod->getFriendObjectKind() &&
1025 NewMethod->getLexicalDeclContext()->isRecord()) {
1026 // -- Member function declarations with the same name and the
1027 // same parameter types cannot be overloaded if any of them
1028 // is a static member function declaration.
1029 if (OldMethod->isStatic() || NewMethod->isStatic()) {
1030 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
1031 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1032 return true;
1033 }
1034
1035 // C++ [class.mem]p1:
1036 // [...] A member shall not be declared twice in the
1037 // member-specification, except that a nested class or member
1038 // class template can be declared and then later defined.
1039 unsigned NewDiag;
1040 if (isa<CXXConstructorDecl>(OldMethod))
1041 NewDiag = diag::err_constructor_redeclared;
1042 else if (isa<CXXDestructorDecl>(NewMethod))
1043 NewDiag = diag::err_destructor_redeclared;
1044 else if (isa<CXXConversionDecl>(NewMethod))
1045 NewDiag = diag::err_conv_function_redeclared;
1046 else
1047 NewDiag = diag::err_member_redeclared;
1048
1049 Diag(New->getLocation(), NewDiag);
1050 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1051 } else {
1052 if (OldMethod->isImplicit()) {
1053 Diag(NewMethod->getLocation(),
1054 diag::err_definition_of_implicitly_declared_member)
1055 << New << getSpecialMember(Context, OldMethod);
1056
1057 Diag(OldMethod->getLocation(),
1058 diag::note_previous_implicit_declaration);
1059 return true;
1060 }
1061 }
1062 }
1063
1064 // (C++98 8.3.5p3):
1065 // All declarations for a function shall agree exactly in both the
1066 // return type and the parameter-type-list.
1067 // attributes should be ignored when comparing.
1068 if (Context.getNoReturnType(OldQType, false) ==
1069 Context.getNoReturnType(NewQType, false))
1070 return MergeCompatibleFunctionDecls(New, Old);
1071
1072 // Fall through for conflicting redeclarations and redefinitions.
1073 }
1074
1075 // C: Function types need to be compatible, not identical. This handles
1076 // duplicate function decls like "void f(int); void f(enum X);" properly.
1077 if (!getLangOptions().CPlusPlus &&
1078 Context.typesAreCompatible(OldQType, NewQType)) {
1079 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
1080 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
1081 const FunctionProtoType *OldProto = 0;
1082 if (isa<FunctionNoProtoType>(NewFuncType) &&
1083 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
1084 // The old declaration provided a function prototype, but the
1085 // new declaration does not. Merge in the prototype.
1086 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
1087 llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
1088 OldProto->arg_type_end());
1089 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
1090 ParamTypes.data(), ParamTypes.size(),
1091 OldProto->isVariadic(),
1092 OldProto->getTypeQuals());
1093 New->setType(NewQType);
1094 New->setHasInheritedPrototype();
1095
1096 // Synthesize a parameter for each argument type.
1097 llvm::SmallVector<ParmVarDecl*, 16> Params;
1098 for (FunctionProtoType::arg_type_iterator
1099 ParamType = OldProto->arg_type_begin(),
1100 ParamEnd = OldProto->arg_type_end();
1101 ParamType != ParamEnd; ++ParamType) {
1102 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
1103 SourceLocation(), 0,
1104 *ParamType, /*TInfo=*/0,
1105 VarDecl::None, 0);
1106 Param->setImplicit();
1107 Params.push_back(Param);
1108 }
1109
1110 New->setParams(Context, Params.data(), Params.size());
1111 }
1112
1113 return MergeCompatibleFunctionDecls(New, Old);
1114 }
1115
1116 // GNU C permits a K&R definition to follow a prototype declaration
1117 // if the declared types of the parameters in the K&R definition
1118 // match the types in the prototype declaration, even when the
1119 // promoted types of the parameters from the K&R definition differ
1120 // from the types in the prototype. GCC then keeps the types from
1121 // the prototype.
1122 //
1123 // If a variadic prototype is followed by a non-variadic K&R definition,
1124 // the K&R definition becomes variadic. This is sort of an edge case, but
1125 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
1126 // C99 6.9.1p8.
1127 if (!getLangOptions().CPlusPlus &&
1128 Old->hasPrototype() && !New->hasPrototype() &&
1129 New->getType()->getAs<FunctionProtoType>() &&
1130 Old->getNumParams() == New->getNumParams()) {
1131 llvm::SmallVector<QualType, 16> ArgTypes;
1132 llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
1133 const FunctionProtoType *OldProto
1134 = Old->getType()->getAs<FunctionProtoType>();
1135 const FunctionProtoType *NewProto
1136 = New->getType()->getAs<FunctionProtoType>();
1137
1138 // Determine whether this is the GNU C extension.
1139 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
1140 NewProto->getResultType());
1141 bool LooseCompatible = !MergedReturn.isNull();
1142 for (unsigned Idx = 0, End = Old->getNumParams();
1143 LooseCompatible && Idx != End; ++Idx) {
1144 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
1145 ParmVarDecl *NewParm = New->getParamDecl(Idx);
1146 if (Context.typesAreCompatible(OldParm->getType(),
1147 NewProto->getArgType(Idx))) {
1148 ArgTypes.push_back(NewParm->getType());
1149 } else if (Context.typesAreCompatible(OldParm->getType(),
1150 NewParm->getType())) {
1151 GNUCompatibleParamWarning Warn
1152 = { OldParm, NewParm, NewProto->getArgType(Idx) };
1153 Warnings.push_back(Warn);
1154 ArgTypes.push_back(NewParm->getType());
1155 } else
1156 LooseCompatible = false;
1157 }
1158
1159 if (LooseCompatible) {
1160 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
1161 Diag(Warnings[Warn].NewParm->getLocation(),
1162 diag::ext_param_promoted_not_compatible_with_prototype)
1163 << Warnings[Warn].PromotedType
1164 << Warnings[Warn].OldParm->getType();
1165 Diag(Warnings[Warn].OldParm->getLocation(),
1166 diag::note_previous_declaration);
1167 }
1168
1169 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
1170 ArgTypes.size(),
1171 OldProto->isVariadic(), 0));
1172 return MergeCompatibleFunctionDecls(New, Old);
1173 }
1174
1175 // Fall through to diagnose conflicting types.
1176 }
1177
1178 // A function that has already been declared has been redeclared or defined
1179 // with a different type- show appropriate diagnostic
1180 if (unsigned BuiltinID = Old->getBuiltinID()) {
1181 // The user has declared a builtin function with an incompatible
1182 // signature.
1183 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
1184 // The function the user is redeclaring is a library-defined
1185 // function like 'malloc' or 'printf'. Warn about the
1186 // redeclaration, then pretend that we don't know about this
1187 // library built-in.
1188 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
1189 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
1190 << Old << Old->getType();
1191 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
1192 Old->setInvalidDecl();
1193 return false;
1194 }
1195
1196 PrevDiag = diag::note_previous_builtin_declaration;
1197 }
1198
1199 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
1200 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1201 return true;
1202}
1203
1204/// \brief Completes the merge of two function declarations that are
1205/// known to be compatible.
1206///
1207/// This routine handles the merging of attributes and other
1208/// properties of function declarations form the old declaration to
1209/// the new declaration, once we know that New is in fact a
1210/// redeclaration of Old.
1211///
1212/// \returns false
1213bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
1214 // Merge the attributes
1215 MergeAttributes(New, Old, Context);
1216
1217 // Merge the storage class.
1218 if (Old->getStorageClass() != FunctionDecl::Extern &&
1219 Old->getStorageClass() != FunctionDecl::None)
1220 New->setStorageClass(Old->getStorageClass());
1221
1222 // Merge "pure" flag.
1223 if (Old->isPure())
1224 New->setPure();
1225
1226 // Merge the "deleted" flag.
1227 if (Old->isDeleted())
1228 New->setDeleted();
1229
1230 if (getLangOptions().CPlusPlus)
1231 return MergeCXXFunctionDecl(New, Old);
1232
1233 return false;
1234}
1235
1236/// MergeVarDecl - We just parsed a variable 'New' which has the same name
1237/// and scope as a previous declaration 'Old'. Figure out how to resolve this
1238/// situation, merging decls or emitting diagnostics as appropriate.
1239///
1240/// Tentative definition rules (C99 6.9.2p2) are checked by
1241/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
1242/// definitions here, since the initializer hasn't been attached.
1243///
1244void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
1245 // If the new decl is already invalid, don't do any other checking.
1246 if (New->isInvalidDecl())
1247 return;
1248
1249 // Verify the old decl was also a variable.
1250 VarDecl *Old = 0;
1251 if (!Previous.isSingleResult() ||
1252 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
1253 Diag(New->getLocation(), diag::err_redefinition_different_kind)
1254 << New->getDeclName();
1255 Diag(Previous.getRepresentativeDecl()->getLocation(),
1256 diag::note_previous_definition);
1257 return New->setInvalidDecl();
1258 }
1259
1260 MergeAttributes(New, Old, Context);
1261
1262 // Merge the types
1263 QualType MergedT;
1264 if (getLangOptions().CPlusPlus) {
1265 if (Context.hasSameType(New->getType(), Old->getType()))
1266 MergedT = New->getType();
1267 // C++ [basic.link]p10:
1268 // [...] the types specified by all declarations referring to a given
1269 // object or function shall be identical, except that declarations for an
1270 // array object can specify array types that differ by the presence or
1271 // absence of a major array bound (8.3.4).
1272 else if (Old->getType()->isIncompleteArrayType() &&
1273 New->getType()->isArrayType()) {
1274 CanQual<ArrayType> OldArray
1275 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1276 CanQual<ArrayType> NewArray
1277 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1278 if (OldArray->getElementType() == NewArray->getElementType())
1279 MergedT = New->getType();
1280 } else if (Old->getType()->isArrayType() &&
1281 New->getType()->isIncompleteArrayType()) {
1282 CanQual<ArrayType> OldArray
1283 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1284 CanQual<ArrayType> NewArray
1285 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1286 if (OldArray->getElementType() == NewArray->getElementType())
1287 MergedT = Old->getType();
1288 }
1289 } else {
1290 MergedT = Context.mergeTypes(New->getType(), Old->getType());
1291 }
1292 if (MergedT.isNull()) {
1293 Diag(New->getLocation(), diag::err_redefinition_different_type)
1294 << New->getDeclName();
1295 Diag(Old->getLocation(), diag::note_previous_definition);
1296 return New->setInvalidDecl();
1297 }
1298 New->setType(MergedT);
1299
1300 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
1301 if (New->getStorageClass() == VarDecl::Static &&
1302 (Old->getStorageClass() == VarDecl::None || Old->hasExternalStorage())) {
1303 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
1304 Diag(Old->getLocation(), diag::note_previous_definition);
1305 return New->setInvalidDecl();
1306 }
1307 // C99 6.2.2p4:
1308 // For an identifier declared with the storage-class specifier
1309 // extern in a scope in which a prior declaration of that
1310 // identifier is visible,23) if the prior declaration specifies
1311 // internal or external linkage, the linkage of the identifier at
1312 // the later declaration is the same as the linkage specified at
1313 // the prior declaration. If no prior declaration is visible, or
1314 // if the prior declaration specifies no linkage, then the
1315 // identifier has external linkage.
1316 if (New->hasExternalStorage() && Old->hasLinkage())
1317 /* Okay */;
1318 else if (New->getStorageClass() != VarDecl::Static &&
1319 Old->getStorageClass() == VarDecl::Static) {
1320 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
1321 Diag(Old->getLocation(), diag::note_previous_definition);
1322 return New->setInvalidDecl();
1323 }
1324
1325 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
1326
1327 // FIXME: The test for external storage here seems wrong? We still
1328 // need to check for mismatches.
1329 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
1330 // Don't complain about out-of-line definitions of static members.
1331 !(Old->getLexicalDeclContext()->isRecord() &&
1332 !New->getLexicalDeclContext()->isRecord())) {
1333 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
1334 Diag(Old->getLocation(), diag::note_previous_definition);
1335 return New->setInvalidDecl();
1336 }
1337
1338 if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
1339 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
1340 Diag(Old->getLocation(), diag::note_previous_definition);
1341 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
1342 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
1343 Diag(Old->getLocation(), diag::note_previous_definition);
1344 }
1345
1346 // C++ doesn't have tentative definitions, so go right ahead and check here.
1347 const VarDecl *Def;
1348 if (getLangOptions().CPlusPlus &&
1349 New->isThisDeclarationADefinition() == VarDecl::Definition &&
1350 (Def = Old->getDefinition())) {
1351 Diag(New->getLocation(), diag::err_redefinition)
1352 << New->getDeclName();
1353 Diag(Def->getLocation(), diag::note_previous_definition);
1354 New->setInvalidDecl();
1355 return;
1356 }
1357
1358 // Keep a chain of previous declarations.
1359 New->setPreviousDeclaration(Old);
1360
1361 // Inherit access appropriately.
1362 New->setAccess(Old->getAccess());
1363}
1364
1365/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
1366/// no declarator (e.g. "struct foo;") is parsed.
1367Sema::DeclPtrTy Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
1368 // FIXME: Error on auto/register at file scope
1369 // FIXME: Error on inline/virtual/explicit
1370 // FIXME: Warn on useless __thread
1371 // FIXME: Warn on useless const/volatile
1372 // FIXME: Warn on useless static/extern/typedef/private_extern/mutable
1373 // FIXME: Warn on useless attributes
1374 Decl *TagD = 0;
1375 TagDecl *Tag = 0;
1376 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
1377 DS.getTypeSpecType() == DeclSpec::TST_struct ||
1378 DS.getTypeSpecType() == DeclSpec::TST_union ||
1379 DS.getTypeSpecType() == DeclSpec::TST_enum) {
1380 TagD = static_cast<Decl *>(DS.getTypeRep());
1381
1382 if (!TagD) // We probably had an error
1383 return DeclPtrTy();
1384
1385 // Note that the above type specs guarantee that the
1386 // type rep is a Decl, whereas in many of the others
1387 // it's a Type.
1388 Tag = dyn_cast<TagDecl>(TagD);
1389 }
1390
1391 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1392 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
1393 // or incomplete types shall not be restrict-qualified."
1394 if (TypeQuals & DeclSpec::TQ_restrict)
1395 Diag(DS.getRestrictSpecLoc(),
1396 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
1397 << DS.getSourceRange();
1398 }
1399
1400 if (DS.isFriendSpecified()) {
1401 // If we're dealing with a class template decl, assume that the
1402 // template routines are handling it.
1403 if (TagD && isa<ClassTemplateDecl>(TagD))
1404 return DeclPtrTy();
1405 return ActOnFriendTypeDecl(S, DS, MultiTemplateParamsArg(*this, 0, 0));
1406 }
1407
1408 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
1409 // If there are attributes in the DeclSpec, apply them to the record.
1410 if (const AttributeList *AL = DS.getAttributes())
1411 ProcessDeclAttributeList(S, Record, AL);
1412
1413 if (!Record->getDeclName() && Record->isDefinition() &&
1414 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
1415 if (getLangOptions().CPlusPlus ||
1416 Record->getDeclContext()->isRecord())
1417 return BuildAnonymousStructOrUnion(S, DS, Record);
1418
1419 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
1420 << DS.getSourceRange();
1421 }
1422
1423 // Microsoft allows unnamed struct/union fields. Don't complain
1424 // about them.
1425 // FIXME: Should we support Microsoft's extensions in this area?
1426 if (Record->getDeclName() && getLangOptions().Microsoft)
1427 return DeclPtrTy::make(Tag);
1428 }
1429
1430 if (!DS.isMissingDeclaratorOk() &&
1431 DS.getTypeSpecType() != DeclSpec::TST_error) {
1432 // Warn about typedefs of enums without names, since this is an
1433 // extension in both Microsoft an GNU.
1434 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
1435 Tag && isa<EnumDecl>(Tag)) {
1436 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
1437 << DS.getSourceRange();
1438 return DeclPtrTy::make(Tag);
1439 }
1440
1441 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
1442 << DS.getSourceRange();
1443 return DeclPtrTy();
1444 }
1445
1446 return DeclPtrTy::make(Tag);
1447}
1448
1449/// We are trying to inject an anonymous member into the given scope;
1450/// check if there's an existing declaration that can't be overloaded.
1451///
1452/// \return true if this is a forbidden redeclaration
1453static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
1454 Scope *S,
1455 DeclContext *Owner,
1456 DeclarationName Name,
1457 SourceLocation NameLoc,
1458 unsigned diagnostic) {
1459 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
1460 Sema::ForRedeclaration);
1461 if (!SemaRef.LookupName(R, S)) return false;
1462
1463 if (R.getAsSingle<TagDecl>())
1464 return false;
1465
1466 // Pick a representative declaration.
1467 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
1468 if (PrevDecl && Owner->isRecord()) {
1469 RecordDecl *Record = cast<RecordDecl>(Owner);
1470 if (!SemaRef.isDeclInScope(PrevDecl, Record, S))
1471 return false;
1472 }
1473
1474 SemaRef.Diag(NameLoc, diagnostic) << Name;
1475 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
1476
1477 return true;
1478}
1479
1480/// InjectAnonymousStructOrUnionMembers - Inject the members of the
1481/// anonymous struct or union AnonRecord into the owning context Owner
1482/// and scope S. This routine will be invoked just after we realize
1483/// that an unnamed union or struct is actually an anonymous union or
1484/// struct, e.g.,
1485///
1486/// @code
1487/// union {
1488/// int i;
1489/// float f;
1490/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
1491/// // f into the surrounding scope.x
1492/// @endcode
1493///
1494/// This routine is recursive, injecting the names of nested anonymous
1495/// structs/unions into the owning context and scope as well.
1496bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
1497 RecordDecl *AnonRecord) {
1498 unsigned diagKind
1499 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
1500 : diag::err_anonymous_struct_member_redecl;
1501
1502 bool Invalid = false;
1503 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
1504 FEnd = AnonRecord->field_end();
1505 F != FEnd; ++F) {
1506 if ((*F)->getDeclName()) {
1507 if (CheckAnonMemberRedeclaration(*this, S, Owner, (*F)->getDeclName(),
1508 (*F)->getLocation(), diagKind)) {
1509 // C++ [class.union]p2:
1510 // The names of the members of an anonymous union shall be
1511 // distinct from the names of any other entity in the
1512 // scope in which the anonymous union is declared.
1513 Invalid = true;
1514 } else {
1515 // C++ [class.union]p2:
1516 // For the purpose of name lookup, after the anonymous union
1517 // definition, the members of the anonymous union are
1518 // considered to have been defined in the scope in which the
1519 // anonymous union is declared.
1520 Owner->makeDeclVisibleInContext(*F);
1521 S->AddDecl(DeclPtrTy::make(*F));
1522 IdResolver.AddDecl(*F);
1523 }
1524 } else if (const RecordType *InnerRecordType
1525 = (*F)->getType()->getAs<RecordType>()) {
1526 RecordDecl *InnerRecord = InnerRecordType->getDecl();
1527 if (InnerRecord->isAnonymousStructOrUnion())
1528 Invalid = Invalid ||
1529 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
1530 }
1531 }
1532
1533 return Invalid;
1534}
1535
1536/// ActOnAnonymousStructOrUnion - Handle the declaration of an
1537/// anonymous structure or union. Anonymous unions are a C++ feature
1538/// (C++ [class.union]) and a GNU C extension; anonymous structures
1539/// are a GNU C and GNU C++ extension.
1540Sema::DeclPtrTy Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1541 RecordDecl *Record) {
1542 DeclContext *Owner = Record->getDeclContext();
1543
1544 // Diagnose whether this anonymous struct/union is an extension.
1545 if (Record->isUnion() && !getLangOptions().CPlusPlus)
1546 Diag(Record->getLocation(), diag::ext_anonymous_union);
1547 else if (!Record->isUnion())
1548 Diag(Record->getLocation(), diag::ext_anonymous_struct);
1549
1550 // C and C++ require different kinds of checks for anonymous
1551 // structs/unions.
1552 bool Invalid = false;
1553 if (getLangOptions().CPlusPlus) {
1554 const char* PrevSpec = 0;
1555 unsigned DiagID;
1556 // C++ [class.union]p3:
1557 // Anonymous unions declared in a named namespace or in the
1558 // global namespace shall be declared static.
1559 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
1560 (isa<TranslationUnitDecl>(Owner) ||
1561 (isa<NamespaceDecl>(Owner) &&
1562 cast<NamespaceDecl>(Owner)->getDeclName()))) {
1563 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
1564 Invalid = true;
1565
1566 // Recover by adding 'static'.
1567 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(),
1568 PrevSpec, DiagID);
1569 }
1570 // C++ [class.union]p3:
1571 // A storage class is not allowed in a declaration of an
1572 // anonymous union in a class scope.
1573 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1574 isa<RecordDecl>(Owner)) {
1575 Diag(DS.getStorageClassSpecLoc(),
1576 diag::err_anonymous_union_with_storage_spec);
1577 Invalid = true;
1578
1579 // Recover by removing the storage specifier.
1580 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
1581 PrevSpec, DiagID);
1582 }
1583
1584 // C++ [class.union]p2:
1585 // The member-specification of an anonymous union shall only
1586 // define non-static data members. [Note: nested types and
1587 // functions cannot be declared within an anonymous union. ]
1588 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
1589 MemEnd = Record->decls_end();
1590 Mem != MemEnd; ++Mem) {
1591 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
1592 // C++ [class.union]p3:
1593 // An anonymous union shall not have private or protected
1594 // members (clause 11).
1595 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
1596 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
1597 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
1598 Invalid = true;
1599 }
1600 } else if ((*Mem)->isImplicit()) {
1601 // Any implicit members are fine.
1602 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
1603 // This is a type that showed up in an
1604 // elaborated-type-specifier inside the anonymous struct or
1605 // union, but which actually declares a type outside of the
1606 // anonymous struct or union. It's okay.
1607 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
1608 if (!MemRecord->isAnonymousStructOrUnion() &&
1609 MemRecord->getDeclName()) {
1610 // This is a nested type declaration.
1611 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
1612 << (int)Record->isUnion();
1613 Invalid = true;
1614 }
1615 } else {
1616 // We have something that isn't a non-static data
1617 // member. Complain about it.
1618 unsigned DK = diag::err_anonymous_record_bad_member;
1619 if (isa<TypeDecl>(*Mem))
1620 DK = diag::err_anonymous_record_with_type;
1621 else if (isa<FunctionDecl>(*Mem))
1622 DK = diag::err_anonymous_record_with_function;
1623 else if (isa<VarDecl>(*Mem))
1624 DK = diag::err_anonymous_record_with_static;
1625 Diag((*Mem)->getLocation(), DK)
1626 << (int)Record->isUnion();
1627 Invalid = true;
1628 }
1629 }
1630 }
1631
1632 if (!Record->isUnion() && !Owner->isRecord()) {
1633 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
1634 << (int)getLangOptions().CPlusPlus;
1635 Invalid = true;
1636 }
1637
1638 // Mock up a declarator.
1639 Declarator Dc(DS, Declarator::TypeNameContext);
1640 TypeSourceInfo *TInfo = 0;
1641 GetTypeForDeclarator(Dc, S, &TInfo);
1642 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
1643
1644 // Create a declaration for this anonymous struct/union.
1645 NamedDecl *Anon = 0;
1646 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
1647 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
1648 /*IdentifierInfo=*/0,
1649 Context.getTypeDeclType(Record),
1650 TInfo,
1651 /*BitWidth=*/0, /*Mutable=*/false);
1652 Anon->setAccess(AS_public);
1653 if (getLangOptions().CPlusPlus)
1654 FieldCollector->Add(cast<FieldDecl>(Anon));
1655 } else {
1656 VarDecl::StorageClass SC;
1657 switch (DS.getStorageClassSpec()) {
1658 default: assert(0 && "Unknown storage class!");
1659 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1660 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1661 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1662 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1663 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1664 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1665 case DeclSpec::SCS_mutable:
1666 // mutable can only appear on non-static class members, so it's always
1667 // an error here
1668 Diag(Record->getLocation(), diag::err_mutable_nonmember);
1669 Invalid = true;
1670 SC = VarDecl::None;
1671 break;
1672 }
1673
1674 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
1675 /*IdentifierInfo=*/0,
1676 Context.getTypeDeclType(Record),
1677 TInfo,
1678 SC);
1679 }
1680 Anon->setImplicit();
1681
1682 // Add the anonymous struct/union object to the current
1683 // context. We'll be referencing this object when we refer to one of
1684 // its members.
1685 Owner->addDecl(Anon);
1686
1687 // Inject the members of the anonymous struct/union into the owning
1688 // context and into the identifier resolver chain for name lookup
1689 // purposes.
1690 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
1691 Invalid = true;
1692
1693 // Mark this as an anonymous struct/union type. Note that we do not
1694 // do this until after we have already checked and injected the
1695 // members of this anonymous struct/union type, because otherwise
1696 // the members could be injected twice: once by DeclContext when it
1697 // builds its lookup table, and once by
1698 // InjectAnonymousStructOrUnionMembers.
1699 Record->setAnonymousStructOrUnion(true);
1700
1701 if (Invalid)
1702 Anon->setInvalidDecl();
1703
1704 return DeclPtrTy::make(Anon);
1705}
1706
1707
1708/// GetNameForDeclarator - Determine the full declaration name for the
1709/// given Declarator.
1710DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1711 return GetNameFromUnqualifiedId(D.getName());
1712}
1713
1714/// \brief Retrieves the canonicalized name from a parsed unqualified-id.
1715DeclarationName Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
1716 switch (Name.getKind()) {
1717 case UnqualifiedId::IK_Identifier:
1718 return DeclarationName(Name.Identifier);
1719
1720 case UnqualifiedId::IK_OperatorFunctionId:
1721 return Context.DeclarationNames.getCXXOperatorName(
1722 Name.OperatorFunctionId.Operator);
1723
1724 case UnqualifiedId::IK_LiteralOperatorId:
1725 return Context.DeclarationNames.getCXXLiteralOperatorName(
1726 Name.Identifier);
1727
1728 case UnqualifiedId::IK_ConversionFunctionId: {
1729 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId);
1730 if (Ty.isNull())
1731 return DeclarationName();
1732
1733 return Context.DeclarationNames.getCXXConversionFunctionName(
1734 Context.getCanonicalType(Ty));
1735 }
1736
1737 case UnqualifiedId::IK_ConstructorName: {
1738 QualType Ty = GetTypeFromParser(Name.ConstructorName);
1739 if (Ty.isNull())
1740 return DeclarationName();
1741
1742 return Context.DeclarationNames.getCXXConstructorName(
1743 Context.getCanonicalType(Ty));
1744 }
1745
1746 case UnqualifiedId::IK_ConstructorTemplateId: {
1747 // In well-formed code, we can only have a constructor
1748 // template-id that refers to the current context, so go there
1749 // to find the actual type being constructed.
1750 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
1751 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
1752 return DeclarationName();
1753
1754 // Determine the type of the class being constructed.
1755 QualType CurClassType;
1756 if (ClassTemplateDecl *ClassTemplate
1757 = CurClass->getDescribedClassTemplate())
1758 CurClassType = ClassTemplate->getInjectedClassNameType(Context);
1759 else
1760 CurClassType = Context.getTypeDeclType(CurClass);
1761
1762 // FIXME: Check two things: that the template-id names the same type as
1763 // CurClassType, and that the template-id does not occur when the name
1764 // was qualified.
1765
1766 return Context.DeclarationNames.getCXXConstructorName(
1767 Context.getCanonicalType(CurClassType));
1768 }
1769
1770 case UnqualifiedId::IK_DestructorName: {
1771 QualType Ty = GetTypeFromParser(Name.DestructorName);
1772 if (Ty.isNull())
1773 return DeclarationName();
1774
1775 return Context.DeclarationNames.getCXXDestructorName(
1776 Context.getCanonicalType(Ty));
1777 }
1778
1779 case UnqualifiedId::IK_TemplateId: {
1780 TemplateName TName
1781 = TemplateName::getFromVoidPointer(Name.TemplateId->Template);
1782 return Context.getNameForTemplate(TName);
1783 }
1784 }
1785
1786 assert(false && "Unknown name kind");
1787 return DeclarationName();
1788}
1789
1790/// isNearlyMatchingFunction - Determine whether the C++ functions
1791/// Declaration and Definition are "nearly" matching. This heuristic
1792/// is used to improve diagnostics in the case where an out-of-line
1793/// function definition doesn't match any declaration within
1794/// the class or namespace.
1795static bool isNearlyMatchingFunction(ASTContext &Context,
1796 FunctionDecl *Declaration,
1797 FunctionDecl *Definition) {
1798 if (Declaration->param_size() != Definition->param_size())
1799 return false;
1800 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1801 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1802 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1803
1804 if (!Context.hasSameUnqualifiedType(DeclParamTy.getNonReferenceType(),
1805 DefParamTy.getNonReferenceType()))
1806 return false;
1807 }
1808
1809 return true;
1810}
1811
1812Sema::DeclPtrTy
1813Sema::HandleDeclarator(Scope *S, Declarator &D,
1814 MultiTemplateParamsArg TemplateParamLists,
1815 bool IsFunctionDefinition) {
1816 DeclarationName Name = GetNameForDeclarator(D);
1817
1818 // All of these full declarators require an identifier. If it doesn't have
1819 // one, the ParsedFreeStandingDeclSpec action should be used.
1820 if (!Name) {
1821 if (!D.isInvalidType()) // Reject this if we think it is valid.
1822 Diag(D.getDeclSpec().getSourceRange().getBegin(),
1823 diag::err_declarator_need_ident)
1824 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
1825 return DeclPtrTy();
1826 }
1827
1828 // The scope passed in may not be a decl scope. Zip up the scope tree until
1829 // we find one that is.
1830 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1831 (S->getFlags() & Scope::TemplateParamScope) != 0)
1832 S = S->getParent();
1833
1834 // If this is an out-of-line definition of a member of a class template
1835 // or class template partial specialization, we may need to rebuild the
1836 // type specifier in the declarator. See RebuildTypeInCurrentInstantiation()
1837 // for more information.
1838 // FIXME: cope with decltype(expr) and typeof(expr) once the rebuilder can
1839 // handle expressions properly.
1840 DeclSpec &DS = const_cast<DeclSpec&>(D.getDeclSpec());
1841 if (D.getCXXScopeSpec().isSet() && !D.getCXXScopeSpec().isInvalid() &&
1842 isDependentScopeSpecifier(D.getCXXScopeSpec()) &&
1843 (DS.getTypeSpecType() == DeclSpec::TST_typename ||
1844 DS.getTypeSpecType() == DeclSpec::TST_typeofType ||
1845 DS.getTypeSpecType() == DeclSpec::TST_typeofExpr ||
1846 DS.getTypeSpecType() == DeclSpec::TST_decltype)) {
1847 if (DeclContext *DC = computeDeclContext(D.getCXXScopeSpec(), true)) {
1848 // FIXME: Preserve type source info.
1849 QualType T = GetTypeFromParser(DS.getTypeRep());
1850
1851 DeclContext *SavedContext = CurContext;
1852 CurContext = DC;
1853 T = RebuildTypeInCurrentInstantiation(T, D.getIdentifierLoc(), Name);
1854 CurContext = SavedContext;
1855
1856 if (T.isNull())
1857 return DeclPtrTy();
1858 DS.UpdateTypeRep(T.getAsOpaquePtr());
1859 }
1860 }
1861
1862 DeclContext *DC;
1863 NamedDecl *New;
1864
1865 TypeSourceInfo *TInfo = 0;
1866 QualType R = GetTypeForDeclarator(D, S, &TInfo);
1867
1868 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
1869 ForRedeclaration);
1870
1871 // See if this is a redefinition of a variable in the same scope.
1872 if (D.getCXXScopeSpec().isInvalid()) {
1873 DC = CurContext;
1874 D.setInvalidType();
1875 } else if (!D.getCXXScopeSpec().isSet()) {
1876 bool IsLinkageLookup = false;
1877
1878 // If the declaration we're planning to build will be a function
1879 // or object with linkage, then look for another declaration with
1880 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
1881 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1882 /* Do nothing*/;
1883 else if (R->isFunctionType()) {
1884 if (CurContext->isFunctionOrMethod() ||
1885 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
1886 IsLinkageLookup = true;
1887 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
1888 IsLinkageLookup = true;
1889 else if (CurContext->getLookupContext()->isTranslationUnit() &&
1890 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
1891 IsLinkageLookup = true;
1892
1893 if (IsLinkageLookup)
1894 Previous.clear(LookupRedeclarationWithLinkage);
1895
1896 DC = CurContext;
1897 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
1898 } else { // Something like "int foo::x;"
1899 DC = computeDeclContext(D.getCXXScopeSpec(), true);
1900
1901 if (!DC) {
1902 // If we could not compute the declaration context, it's because the
1903 // declaration context is dependent but does not refer to a class,
1904 // class template, or class template partial specialization. Complain
1905 // and return early, to avoid the coming semantic disaster.
1906 Diag(D.getIdentifierLoc(),
1907 diag::err_template_qualified_declarator_no_match)
1908 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
1909 << D.getCXXScopeSpec().getRange();
1910 return DeclPtrTy();
1911 }
1912
1913 if (!DC->isDependentContext() &&
1914 RequireCompleteDeclContext(D.getCXXScopeSpec()))
1915 return DeclPtrTy();
1916
1917 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
1918 Diag(D.getIdentifierLoc(),
1919 diag::err_member_def_undefined_record)
1920 << Name << DC << D.getCXXScopeSpec().getRange();
1921 D.setInvalidType();
1922 }
1923
1924 LookupQualifiedName(Previous, DC);
1925
1926 // Don't consider using declarations as previous declarations for
1927 // out-of-line members.
1928 RemoveUsingDecls(Previous);
1929
1930 // C++ 7.3.1.2p2:
1931 // Members (including explicit specializations of templates) of a named
1932 // namespace can also be defined outside that namespace by explicit
1933 // qualification of the name being defined, provided that the entity being
1934 // defined was already declared in the namespace and the definition appears
1935 // after the point of declaration in a namespace that encloses the
1936 // declarations namespace.
1937 //
1938 // Note that we only check the context at this point. We don't yet
1939 // have enough information to make sure that PrevDecl is actually
1940 // the declaration we want to match. For example, given:
1941 //
1942 // class X {
1943 // void f();
1944 // void f(float);
1945 // };
1946 //
1947 // void X::f(int) { } // ill-formed
1948 //
1949 // In this case, PrevDecl will point to the overload set
1950 // containing the two f's declared in X, but neither of them
1951 // matches.
1952
1953 // First check whether we named the global scope.
1954 if (isa<TranslationUnitDecl>(DC)) {
1955 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
1956 << Name << D.getCXXScopeSpec().getRange();
1957 } else {
1958 DeclContext *Cur = CurContext;
1959 while (isa<LinkageSpecDecl>(Cur))
1960 Cur = Cur->getParent();
1961 if (!Cur->Encloses(DC)) {
1962 // The qualifying scope doesn't enclose the original declaration.
1963 // Emit diagnostic based on current scope.
1964 SourceLocation L = D.getIdentifierLoc();
1965 SourceRange R = D.getCXXScopeSpec().getRange();
1966 if (isa<FunctionDecl>(Cur))
1967 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
1968 else
1969 Diag(L, diag::err_invalid_declarator_scope)
1970 << Name << cast<NamedDecl>(DC) << R;
1971 D.setInvalidType();
1972 }
1973 }
1974 }
1975
1976 if (Previous.isSingleResult() &&
1977 Previous.getFoundDecl()->isTemplateParameter()) {
1978 // Maybe we will complain about the shadowed template parameter.
1979 if (!D.isInvalidType())
1980 if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
1981 Previous.getFoundDecl()))
1982 D.setInvalidType();
1983
1984 // Just pretend that we didn't see the previous declaration.
1985 Previous.clear();
1986 }
1987
1988 // In C++, the previous declaration we find might be a tag type
1989 // (class or enum). In this case, the new declaration will hide the
1990 // tag type. Note that this does does not apply if we're declaring a
1991 // typedef (C++ [dcl.typedef]p4).
1992 if (Previous.isSingleTagDecl() &&
1993 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
1994 Previous.clear();
1995
1996 bool Redeclaration = false;
1997 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
1998 if (TemplateParamLists.size()) {
1999 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
2000 return DeclPtrTy();
2001 }
2002
2003 New = ActOnTypedefDeclarator(S, D, DC, R, TInfo, Previous, Redeclaration);
2004 } else if (R->isFunctionType()) {
2005 New = ActOnFunctionDeclarator(S, D, DC, R, TInfo, Previous,
2006 move(TemplateParamLists),
2007 IsFunctionDefinition, Redeclaration);
2008 } else {
2009 New = ActOnVariableDeclarator(S, D, DC, R, TInfo, Previous,
2010 move(TemplateParamLists),
2011 Redeclaration);
2012 }
2013
2014 if (New == 0)
2015 return DeclPtrTy();
2016
2017 // If this has an identifier and is not an invalid redeclaration or
2018 // function template specialization, add it to the scope stack.
2019 if (Name && !(Redeclaration && New->isInvalidDecl()))
2020 PushOnScopeChains(New, S);
2021
2022 return DeclPtrTy::make(New);
2023}
2024
2025/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2026/// types into constant array types in certain situations which would otherwise
2027/// be errors (for GCC compatibility).
2028static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2029 ASTContext &Context,
2030 bool &SizeIsNegative) {
2031 // This method tries to turn a variable array into a constant
2032 // array even when the size isn't an ICE. This is necessary
2033 // for compatibility with code that depends on gcc's buggy
2034 // constant expression folding, like struct {char x[(int)(char*)2];}
2035 SizeIsNegative = false;
2036
2037 QualifierCollector Qs;
2038 const Type *Ty = Qs.strip(T);
2039
2040 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
2041 QualType Pointee = PTy->getPointeeType();
2042 QualType FixedType =
2043 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative);
2044 if (FixedType.isNull()) return FixedType;
2045 FixedType = Context.getPointerType(FixedType);
2046 return Qs.apply(FixedType);
2047 }
2048
2049 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2050 if (!VLATy)
2051 return QualType();
2052 // FIXME: We should probably handle this case
2053 if (VLATy->getElementType()->isVariablyModifiedType())
2054 return QualType();
2055
2056 Expr::EvalResult EvalResult;
2057 if (!VLATy->getSizeExpr() ||
2058 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
2059 !EvalResult.Val.isInt())
2060 return QualType();
2061
2062 llvm::APSInt &Res = EvalResult.Val.getInt();
2063 if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) {
2064 // TODO: preserve the size expression in declarator info
2065 return Context.getConstantArrayType(VLATy->getElementType(),
2066 Res, ArrayType::Normal, 0);
2067 }
2068
2069 SizeIsNegative = true;
2070 return QualType();
2071}
2072
2073/// \brief Register the given locally-scoped external C declaration so
2074/// that it can be found later for redeclarations
2075void
2076Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
2077 const LookupResult &Previous,
2078 Scope *S) {
2079 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
2080 "Decl is not a locally-scoped decl!");
2081 // Note that we have a locally-scoped external with this name.
2082 LocallyScopedExternalDecls[ND->getDeclName()] = ND;
2083
2084 if (!Previous.isSingleResult())
2085 return;
2086
2087 NamedDecl *PrevDecl = Previous.getFoundDecl();
2088
2089 // If there was a previous declaration of this variable, it may be
2090 // in our identifier chain. Update the identifier chain with the new
2091 // declaration.
2092 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
2093 // The previous declaration was found on the identifer resolver
2094 // chain, so remove it from its scope.
2095 while (S && !S->isDeclScope(DeclPtrTy::make(PrevDecl)))
2096 S = S->getParent();
2097
2098 if (S)
2099 S->RemoveDecl(DeclPtrTy::make(PrevDecl));
2100 }
2101}
2102
2103/// \brief Diagnose function specifiers on a declaration of an identifier that
2104/// does not identify a function.
2105void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
2106 // FIXME: We should probably indicate the identifier in question to avoid
2107 // confusion for constructs like "inline int a(), b;"
2108 if (D.getDeclSpec().isInlineSpecified())
2109 Diag(D.getDeclSpec().getInlineSpecLoc(),
2110 diag::err_inline_non_function);
2111
2112 if (D.getDeclSpec().isVirtualSpecified())
2113 Diag(D.getDeclSpec().getVirtualSpecLoc(),
2114 diag::err_virtual_non_function);
2115
2116 if (D.getDeclSpec().isExplicitSpecified())
2117 Diag(D.getDeclSpec().getExplicitSpecLoc(),
2118 diag::err_explicit_non_function);
2119}
2120
2121NamedDecl*
2122Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2123 QualType R, TypeSourceInfo *TInfo,
2124 LookupResult &Previous, bool &Redeclaration) {
2125 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
2126 if (D.getCXXScopeSpec().isSet()) {
2127 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
2128 << D.getCXXScopeSpec().getRange();
2129 D.setInvalidType();
2130 // Pretend we didn't see the scope specifier.
2131 DC = 0;
2132 }
2133
2134 if (getLangOptions().CPlusPlus) {
2135 // Check that there are no default arguments (C++ only).
2136 CheckExtraCXXDefaultArguments(D);
2137 }
2138
2139 DiagnoseFunctionSpecifiers(D);
2140
2141 if (D.getDeclSpec().isThreadSpecified())
2142 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2143
2144 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, TInfo);
2145 if (!NewTD) return 0;
2146
2147 // Handle attributes prior to checking for duplicates in MergeVarDecl
2148 ProcessDeclAttributes(S, NewTD, D);
2149
2150 // Merge the decl with the existing one if appropriate. If the decl is
2151 // in an outer scope, it isn't the same thing.
2152 FilterLookupForScope(*this, Previous, DC, S, /*ConsiderLinkage*/ false);
2153 if (!Previous.empty()) {
2154 Redeclaration = true;
2155 MergeTypeDefDecl(NewTD, Previous);
2156 }
2157
2158 // C99 6.7.7p2: If a typedef name specifies a variably modified type
2159 // then it shall have block scope.
2160 QualType T = NewTD->getUnderlyingType();
2161 if (T->isVariablyModifiedType()) {
2162 CurFunctionNeedsScopeChecking = true;
2163
2164 if (S->getFnParent() == 0) {
2165 bool SizeIsNegative;
2166 QualType FixedTy =
2167 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
2168 if (!FixedTy.isNull()) {
2169 Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size);
2170 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
2171 } else {
2172 if (SizeIsNegative)
2173 Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size);
2174 else if (T->isVariableArrayType())
2175 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
2176 else
2177 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
2178 NewTD->setInvalidDecl();
2179 }
2180 }
2181 }
2182
2183 // If this is the C FILE type, notify the AST context.
2184 if (IdentifierInfo *II = NewTD->getIdentifier())
2185 if (!NewTD->isInvalidDecl() &&
2186 NewTD->getDeclContext()->getLookupContext()->isTranslationUnit()) {
2187 if (II->isStr("FILE"))
2188 Context.setFILEDecl(NewTD);
2189 else if (II->isStr("jmp_buf"))
2190 Context.setjmp_bufDecl(NewTD);
2191 else if (II->isStr("sigjmp_buf"))
2192 Context.setsigjmp_bufDecl(NewTD);
2193 }
2194
2195 return NewTD;
2196}
2197
2198/// \brief Determines whether the given declaration is an out-of-scope
2199/// previous declaration.
2200///
2201/// This routine should be invoked when name lookup has found a
2202/// previous declaration (PrevDecl) that is not in the scope where a
2203/// new declaration by the same name is being introduced. If the new
2204/// declaration occurs in a local scope, previous declarations with
2205/// linkage may still be considered previous declarations (C99
2206/// 6.2.2p4-5, C++ [basic.link]p6).
2207///
2208/// \param PrevDecl the previous declaration found by name
2209/// lookup
2210///
2211/// \param DC the context in which the new declaration is being
2212/// declared.
2213///
2214/// \returns true if PrevDecl is an out-of-scope previous declaration
2215/// for a new delcaration with the same name.
2216static bool
2217isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
2218 ASTContext &Context) {
2219 if (!PrevDecl)
2220 return 0;
2221
2222 if (!PrevDecl->hasLinkage())
2223 return false;
2224
2225 if (Context.getLangOptions().CPlusPlus) {
2226 // C++ [basic.link]p6:
2227 // If there is a visible declaration of an entity with linkage
2228 // having the same name and type, ignoring entities declared
2229 // outside the innermost enclosing namespace scope, the block
2230 // scope declaration declares that same entity and receives the
2231 // linkage of the previous declaration.
2232 DeclContext *OuterContext = DC->getLookupContext();
2233 if (!OuterContext->isFunctionOrMethod())
2234 // This rule only applies to block-scope declarations.
2235 return false;
2236 else {
2237 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
2238 if (PrevOuterContext->isRecord())
2239 // We found a member function: ignore it.
2240 return false;
2241 else {
2242 // Find the innermost enclosing namespace for the new and
2243 // previous declarations.
2244 while (!OuterContext->isFileContext())
2245 OuterContext = OuterContext->getParent();
2246 while (!PrevOuterContext->isFileContext())
2247 PrevOuterContext = PrevOuterContext->getParent();
2248
2249 // The previous declaration is in a different namespace, so it
2250 // isn't the same function.
2251 if (OuterContext->getPrimaryContext() !=
2252 PrevOuterContext->getPrimaryContext())
2253 return false;
2254 }
2255 }
2256 }
2257
2258 return true;
2259}
2260
2261NamedDecl*
2262Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2263 QualType R, TypeSourceInfo *TInfo,
2264 LookupResult &Previous,
2265 MultiTemplateParamsArg TemplateParamLists,
2266 bool &Redeclaration) {
2267 DeclarationName Name = GetNameForDeclarator(D);
2268
2269 // Check that there are no default arguments (C++ only).
2270 if (getLangOptions().CPlusPlus)
2271 CheckExtraCXXDefaultArguments(D);
2272
2273 VarDecl *NewVD;
2274 VarDecl::StorageClass SC;
2275 switch (D.getDeclSpec().getStorageClassSpec()) {
2276 default: assert(0 && "Unknown storage class!");
2277 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
2278 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
2279 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
2280 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
2281 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
2282 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
2283 case DeclSpec::SCS_mutable:
2284 // mutable can only appear on non-static class members, so it's always
2285 // an error here
2286 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
2287 D.setInvalidType();
2288 SC = VarDecl::None;
2289 break;
2290 }
2291
2292 IdentifierInfo *II = Name.getAsIdentifierInfo();
2293 if (!II) {
2294 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
2295 << Name.getAsString();
2296 return 0;
2297 }
2298
2299 DiagnoseFunctionSpecifiers(D);
2300
2301 if (!DC->isRecord() && S->getFnParent() == 0) {
2302 // C99 6.9p2: The storage-class specifiers auto and register shall not
2303 // appear in the declaration specifiers in an external declaration.
2304 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
2305
2306 // If this is a register variable with an asm label specified, then this
2307 // is a GNU extension.
2308 if (SC == VarDecl::Register && D.getAsmLabel())
2309 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
2310 else
2311 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
2312 D.setInvalidType();
2313 }
2314 }
2315 if (DC->isRecord() && !CurContext->isRecord()) {
2316 // This is an out-of-line definition of a static data member.
2317 if (SC == VarDecl::Static) {
2318 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2319 diag::err_static_out_of_line)
2320 << CodeModificationHint::CreateRemoval(
2321 D.getDeclSpec().getStorageClassSpecLoc());
2322 } else if (SC == VarDecl::None)
2323 SC = VarDecl::Static;
2324 }
2325 if (SC == VarDecl::Static) {
2326 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
2327 if (RD->isLocalClass())
2328 Diag(D.getIdentifierLoc(),
2329 diag::err_static_data_member_not_allowed_in_local_class)
2330 << Name << RD->getDeclName();
2331 }
2332 }
2333
2334 // Match up the template parameter lists with the scope specifier, then
2335 // determine whether we have a template or a template specialization.
2336 bool isExplicitSpecialization = false;
2337 if (TemplateParameterList *TemplateParams
2338 = MatchTemplateParametersToScopeSpecifier(
2339 D.getDeclSpec().getSourceRange().getBegin(),
2340 D.getCXXScopeSpec(),
2341 (TemplateParameterList**)TemplateParamLists.get(),
2342 TemplateParamLists.size(),
2343 isExplicitSpecialization)) {
2344 if (TemplateParams->size() > 0) {
2345 // There is no such thing as a variable template.
2346 Diag(D.getIdentifierLoc(), diag::err_template_variable)
2347 << II
2348 << SourceRange(TemplateParams->getTemplateLoc(),
2349 TemplateParams->getRAngleLoc());
2350 return 0;
2351 } else {
2352 // There is an extraneous 'template<>' for this variable. Complain
2353 // about it, but allow the declaration of the variable.
2354 Diag(TemplateParams->getTemplateLoc(),
2355 diag::err_template_variable_noparams)
2356 << II
2357 << SourceRange(TemplateParams->getTemplateLoc(),
2358 TemplateParams->getRAngleLoc());
2359
2360 isExplicitSpecialization = true;
2361 }
2362 }
2363
2364 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
2365 II, R, TInfo, SC);
2366
2367 if (D.isInvalidType())
2368 NewVD->setInvalidDecl();
2369
2370 if (D.getDeclSpec().isThreadSpecified()) {
2371 if (NewVD->hasLocalStorage())
2372 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
2373 else if (!Context.Target.isTLSSupported())
2374 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
2375 else
2376 NewVD->setThreadSpecified(true);
2377 }
2378
2379 // Set the lexical context. If the declarator has a C++ scope specifier, the
2380 // lexical context will be different from the semantic context.
2381 NewVD->setLexicalDeclContext(CurContext);
2382
2383 // Handle attributes prior to checking for duplicates in MergeVarDecl
2384 ProcessDeclAttributes(S, NewVD, D);
2385
2386 // Handle GNU asm-label extension (encoded as an attribute).
2387 if (Expr *E = (Expr*) D.getAsmLabel()) {
2388 // The parser guarantees this is a string.
2389 StringLiteral *SE = cast<StringLiteral>(E);
2390 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getString()));
2391 }
2392
2393 // Don't consider existing declarations that are in a different
2394 // scope and are out-of-semantic-context declarations (if the new
2395 // declaration has linkage).
2396 FilterLookupForScope(*this, Previous, DC, S, NewVD->hasLinkage());
2397
2398 // Merge the decl with the existing one if appropriate.
2399 if (!Previous.empty()) {
2400 if (Previous.isSingleResult() &&
2401 isa<FieldDecl>(Previous.getFoundDecl()) &&
2402 D.getCXXScopeSpec().isSet()) {
2403 // The user tried to define a non-static data member
2404 // out-of-line (C++ [dcl.meaning]p1).
2405 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
2406 << D.getCXXScopeSpec().getRange();
2407 Previous.clear();
2408 NewVD->setInvalidDecl();
2409 }
2410 } else if (D.getCXXScopeSpec().isSet()) {
2411 // No previous declaration in the qualifying scope.
2412 Diag(D.getIdentifierLoc(), diag::err_no_member)
2413 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
2414 << D.getCXXScopeSpec().getRange();
2415 NewVD->setInvalidDecl();
2416 }
2417
2418 CheckVariableDeclaration(NewVD, Previous, Redeclaration);
2419
2420 // This is an explicit specialization of a static data member. Check it.
2421 if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
2422 CheckMemberSpecialization(NewVD, Previous))
2423 NewVD->setInvalidDecl();
2424
2425 // attributes declared post-definition are currently ignored
2426 if (Previous.isSingleResult()) {
2427 VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl());
2428 if (Def && (Def = Def->getDefinition()) &&
2429 Def != NewVD && D.hasAttributes()) {
2430 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
2431 Diag(Def->getLocation(), diag::note_previous_definition);
2432 }
2433 }
2434
2435 // If this is a locally-scoped extern C variable, update the map of
2436 // such variables.
2437 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
2438 !NewVD->isInvalidDecl())
2439 RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
2440
2441 return NewVD;
2442}
2443
2444/// \brief Perform semantic checking on a newly-created variable
2445/// declaration.
2446///
2447/// This routine performs all of the type-checking required for a
2448/// variable declaration once it has been built. It is used both to
2449/// check variables after they have been parsed and their declarators
2450/// have been translated into a declaration, and to check variables
2451/// that have been instantiated from a template.
2452///
2453/// Sets NewVD->isInvalidDecl() if an error was encountered.
2454void Sema::CheckVariableDeclaration(VarDecl *NewVD,
2455 LookupResult &Previous,
2456 bool &Redeclaration) {
2457 // If the decl is already known invalid, don't check it.
2458 if (NewVD->isInvalidDecl())
2459 return;
2460
2461 QualType T = NewVD->getType();
2462
2463 if (T->isObjCInterfaceType()) {
2464 Diag(NewVD->getLocation(), diag::err_statically_allocated_object);
2465 return NewVD->setInvalidDecl();
2466 }
2467
2468 // Emit an error if an address space was applied to decl with local storage.
2469 // This includes arrays of objects with address space qualifiers, but not
2470 // automatic variables that point to other address spaces.
2471 // ISO/IEC TR 18037 S5.1.2
2472 if (NewVD->hasLocalStorage() && (T.getAddressSpace() != 0)) {
2473 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
2474 return NewVD->setInvalidDecl();
2475 }
2476
2477 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
2478 && !NewVD->hasAttr<BlocksAttr>())
2479 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
2480
2481 bool isVM = T->isVariablyModifiedType();
2482 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
2483 NewVD->hasAttr<BlocksAttr>())
2484 CurFunctionNeedsScopeChecking = true;
2485
2486 if ((isVM && NewVD->hasLinkage()) ||
2487 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
2488 bool SizeIsNegative;
2489 QualType FixedTy =
2490 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
2491
2492 if (FixedTy.isNull() && T->isVariableArrayType()) {
2493 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
2494 // FIXME: This won't give the correct result for
2495 // int a[10][n];
2496 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
2497
2498 if (NewVD->isFileVarDecl())
2499 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
2500 << SizeRange;
2501 else if (NewVD->getStorageClass() == VarDecl::Static)
2502 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
2503 << SizeRange;
2504 else
2505 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
2506 << SizeRange;
2507 return NewVD->setInvalidDecl();
2508 }
2509
2510 if (FixedTy.isNull()) {
2511 if (NewVD->isFileVarDecl())
2512 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
2513 else
2514 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
2515 return NewVD->setInvalidDecl();
2516 }
2517
2518 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
2519 NewVD->setType(FixedTy);
2520 }
2521
2522 if (Previous.empty() && NewVD->isExternC()) {
2523 // Since we did not find anything by this name and we're declaring
2524 // an extern "C" variable, look for a non-visible extern "C"
2525 // declaration with the same name.
2526 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
2527 = LocallyScopedExternalDecls.find(NewVD->getDeclName());
2528 if (Pos != LocallyScopedExternalDecls.end())
2529 Previous.addDecl(Pos->second);
2530 }
2531
2532 if (T->isVoidType() && !NewVD->hasExternalStorage()) {
2533 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
2534 << T;
2535 return NewVD->setInvalidDecl();
2536 }
2537
2538 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
2539 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
2540 return NewVD->setInvalidDecl();
2541 }
2542
2543 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
2544 Diag(NewVD->getLocation(), diag::err_block_on_vm);
2545 return NewVD->setInvalidDecl();
2546 }
2547
2548 if (!Previous.empty()) {
2549 Redeclaration = true;
2550 MergeVarDecl(NewVD, Previous);
2551 }
2552}
2553
2554/// \brief Data used with FindOverriddenMethod
2555struct FindOverriddenMethodData {
2556 Sema *S;
2557 CXXMethodDecl *Method;
2558};
2559
2560/// \brief Member lookup function that determines whether a given C++
2561/// method overrides a method in a base class, to be used with
2562/// CXXRecordDecl::lookupInBases().
2563static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
2564 CXXBasePath &Path,
2565 void *UserData) {
2566 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
2567
2568 FindOverriddenMethodData *Data
2569 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
2570
2571 DeclarationName Name = Data->Method->getDeclName();
2572
2573 // FIXME: Do we care about other names here too?
2574 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
2575 // We really want to find the base class constructor here.
2576 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
2577 CanQualType CT = Data->S->Context.getCanonicalType(T);
2578
2579 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
2580 }
2581
2582 for (Path.Decls = BaseRecord->lookup(Name);
2583 Path.Decls.first != Path.Decls.second;
2584 ++Path.Decls.first) {
2585 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*Path.Decls.first)) {
2586 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD))
2587 return true;
2588 }
2589 }
2590
2591 return false;
2592}
2593
2594/// AddOverriddenMethods - See if a method overrides any in the base classes,
2595/// and if so, check that it's a valid override and remember it.
2596void Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2597 // Look for virtual methods in base classes that this method might override.
2598 CXXBasePaths Paths;
2599 FindOverriddenMethodData Data;
2600 Data.Method = MD;
2601 Data.S = this;
2602 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
2603 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
2604 E = Paths.found_decls_end(); I != E; ++I) {
2605 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
2606 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
2607 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
2608 !CheckOverridingFunctionAttributes(MD, OldMD))
2609 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
2610 }
2611 }
2612 }
2613}
2614
2615NamedDecl*
2616Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2617 QualType R, TypeSourceInfo *TInfo,
2618 LookupResult &Previous,
2619 MultiTemplateParamsArg TemplateParamLists,
2620 bool IsFunctionDefinition, bool &Redeclaration) {
2621 assert(R.getTypePtr()->isFunctionType());
2622
2623 DeclarationName Name = GetNameForDeclarator(D);
2624 FunctionDecl::StorageClass SC = FunctionDecl::None;
2625 switch (D.getDeclSpec().getStorageClassSpec()) {
2626 default: assert(0 && "Unknown storage class!");
2627 case DeclSpec::SCS_auto:
2628 case DeclSpec::SCS_register:
2629 case DeclSpec::SCS_mutable:
2630 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2631 diag::err_typecheck_sclass_func);
2632 D.setInvalidType();
2633 break;
2634 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
2635 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
2636 case DeclSpec::SCS_static: {
2637 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
2638 // C99 6.7.1p5:
2639 // The declaration of an identifier for a function that has
2640 // block scope shall have no explicit storage-class specifier
2641 // other than extern
2642 // See also (C++ [dcl.stc]p4).
2643 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2644 diag::err_static_block_func);
2645 SC = FunctionDecl::None;
2646 } else
2647 SC = FunctionDecl::Static;
2648 break;
2649 }
2650 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
2651 }
2652
2653 if (D.getDeclSpec().isThreadSpecified())
2654 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2655
2656 bool isFriend = D.getDeclSpec().isFriendSpecified();
2657 bool isInline = D.getDeclSpec().isInlineSpecified();
2658 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
2659 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
2660
2661 // Check that the return type is not an abstract class type.
2662 // For record types, this is done by the AbstractClassUsageDiagnoser once
2663 // the class has been completely parsed.
2664 if (!DC->isRecord() &&
2665 RequireNonAbstractType(D.getIdentifierLoc(),
2666 R->getAs<FunctionType>()->getResultType(),
2667 diag::err_abstract_type_in_decl,
2668 AbstractReturnType))
2669 D.setInvalidType();
2670
2671 // Do not allow returning a objc interface by-value.
2672 if (R->getAs<FunctionType>()->getResultType()->isObjCInterfaceType()) {
2673 Diag(D.getIdentifierLoc(),
2674 diag::err_object_cannot_be_passed_returned_by_value) << 0
2675 << R->getAs<FunctionType>()->getResultType();
2676 D.setInvalidType();
2677 }
2678
2679 bool isVirtualOkay = false;
2680 FunctionDecl *NewFD;
2681
2682 if (isFriend) {
2683 // C++ [class.friend]p5
2684 // A function can be defined in a friend declaration of a
2685 // class . . . . Such a function is implicitly inline.
2686 isInline |= IsFunctionDefinition;
2687 }
2688
2689 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
2690 // This is a C++ constructor declaration.
2691 assert(DC->isRecord() &&
2692 "Constructors can only be declared in a member context");
2693
2694 R = CheckConstructorDeclarator(D, R, SC);
2695
2696 // Create the new declaration
2697 NewFD = CXXConstructorDecl::Create(Context,
2698 cast<CXXRecordDecl>(DC),
2699 D.getIdentifierLoc(), Name, R, TInfo,
2700 isExplicit, isInline,
2701 /*isImplicitlyDeclared=*/false);
2702 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
2703 // This is a C++ destructor declaration.
2704 if (DC->isRecord()) {
2705 R = CheckDestructorDeclarator(D, SC);
2706
2707 NewFD = CXXDestructorDecl::Create(Context,
2708 cast<CXXRecordDecl>(DC),
2709 D.getIdentifierLoc(), Name, R,
2710 isInline,
2711 /*isImplicitlyDeclared=*/false);
2712
2713 isVirtualOkay = true;
2714 } else {
2715 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
2716
2717 // Create a FunctionDecl to satisfy the function definition parsing
2718 // code path.
2719 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
2720 Name, R, TInfo, SC, isInline,
2721 /*hasPrototype=*/true);
2722 D.setInvalidType();
2723 }
2724 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2725 if (!DC->isRecord()) {
2726 Diag(D.getIdentifierLoc(),
2727 diag::err_conv_function_not_member);
2728 return 0;
2729 }
2730
2731 CheckConversionDeclarator(D, R, SC);
2732 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
2733 D.getIdentifierLoc(), Name, R, TInfo,
2734 isInline, isExplicit);
2735
2736 isVirtualOkay = true;
2737 } else if (DC->isRecord()) {
2738 // If the of the function is the same as the name of the record, then this
2739 // must be an invalid constructor that has a return type.
2740 // (The parser checks for a return type and makes the declarator a
2741 // constructor if it has no return type).
2742 // must have an invalid constructor that has a return type
2743 if (Name.getAsIdentifierInfo() &&
2744 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
2745 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
2746 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2747 << SourceRange(D.getIdentifierLoc());
2748 return 0;
2749 }
2750
2751 bool isStatic = SC == FunctionDecl::Static;
2752
2753 // [class.free]p1:
2754 // Any allocation function for a class T is a static member
2755 // (even if not explicitly declared static).
2756 if (Name.getCXXOverloadedOperator() == OO_New ||
2757 Name.getCXXOverloadedOperator() == OO_Array_New)
2758 isStatic = true;
2759
2760 // [class.free]p6 Any deallocation function for a class X is a static member
2761 // (even if not explicitly declared static).
2762 if (Name.getCXXOverloadedOperator() == OO_Delete ||
2763 Name.getCXXOverloadedOperator() == OO_Array_Delete)
2764 isStatic = true;
2765
2766 // This is a C++ method declaration.
2767 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
2768 D.getIdentifierLoc(), Name, R, TInfo,
2769 isStatic, isInline);
2770
2771 isVirtualOkay = !isStatic;
2772 } else {
2773 // Determine whether the function was written with a
2774 // prototype. This true when:
2775 // - we're in C++ (where every function has a prototype),
2776 // - there is a prototype in the declarator, or
2777 // - the type R of the function is some kind of typedef or other reference
2778 // to a type name (which eventually refers to a function type).
2779 bool HasPrototype =
2780 getLangOptions().CPlusPlus ||
2781 (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) ||
2782 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
2783
2784 NewFD = FunctionDecl::Create(Context, DC,
2785 D.getIdentifierLoc(),
2786 Name, R, TInfo, SC, isInline, HasPrototype);
2787 }
2788
2789 if (D.isInvalidType())
2790 NewFD->setInvalidDecl();
2791
2792 // Set the lexical context. If the declarator has a C++
2793 // scope specifier, or is the object of a friend declaration, the
2794 // lexical context will be different from the semantic context.
2795 NewFD->setLexicalDeclContext(CurContext);
2796
2797 // Match up the template parameter lists with the scope specifier, then
2798 // determine whether we have a template or a template specialization.
2799 FunctionTemplateDecl *FunctionTemplate = 0;
2800 bool isExplicitSpecialization = false;
2801 bool isFunctionTemplateSpecialization = false;
2802 if (TemplateParameterList *TemplateParams
2803 = MatchTemplateParametersToScopeSpecifier(
2804 D.getDeclSpec().getSourceRange().getBegin(),
2805 D.getCXXScopeSpec(),
2806 (TemplateParameterList**)TemplateParamLists.get(),
2807 TemplateParamLists.size(),
2808 isExplicitSpecialization)) {
2809 if (TemplateParams->size() > 0) {
2810 // This is a function template
2811
2812 // Check that we can declare a template here.
2813 if (CheckTemplateDeclScope(S, TemplateParams))
2814 return 0;
2815
2816 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
2817 NewFD->getLocation(),
2818 Name, TemplateParams,
2819 NewFD);
2820 FunctionTemplate->setLexicalDeclContext(CurContext);
2821 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
2822 } else {
2823 // This is a function template specialization.
2824 isFunctionTemplateSpecialization = true;
2825 }
2826
2827 // FIXME: Free this memory properly.
2828 TemplateParamLists.release();
2829 }
2830
2831 // C++ [dcl.fct.spec]p5:
2832 // The virtual specifier shall only be used in declarations of
2833 // nonstatic class member functions that appear within a
2834 // member-specification of a class declaration; see 10.3.
2835 //
2836 if (isVirtual && !NewFD->isInvalidDecl()) {
2837 if (!isVirtualOkay) {
2838 Diag(D.getDeclSpec().getVirtualSpecLoc(),
2839 diag::err_virtual_non_function);
2840 } else if (!CurContext->isRecord()) {
2841 // 'virtual' was specified outside of the class.
2842 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class)
2843 << CodeModificationHint::CreateRemoval(
2844 D.getDeclSpec().getVirtualSpecLoc());
2845 } else {
2846 // Okay: Add virtual to the method.
2847 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC);
2848 CurClass->setMethodAsVirtual(NewFD);
2849 }
2850 }
2851
2852 // C++ [dcl.fct.spec]p6:
2853 // The explicit specifier shall be used only in the declaration of a
2854 // constructor or conversion function within its class definition; see 12.3.1
2855 // and 12.3.2.
2856 if (isExplicit && !NewFD->isInvalidDecl()) {
2857 if (!CurContext->isRecord()) {
2858 // 'explicit' was specified outside of the class.
2859 Diag(D.getDeclSpec().getExplicitSpecLoc(),
2860 diag::err_explicit_out_of_class)
2861 << CodeModificationHint::CreateRemoval(
2862 D.getDeclSpec().getExplicitSpecLoc());
2863 } else if (!isa<CXXConstructorDecl>(NewFD) &&
2864 !isa<CXXConversionDecl>(NewFD)) {
2865 // 'explicit' was specified on a function that wasn't a constructor
2866 // or conversion function.
2867 Diag(D.getDeclSpec().getExplicitSpecLoc(),
2868 diag::err_explicit_non_ctor_or_conv_function)
2869 << CodeModificationHint::CreateRemoval(
2870 D.getDeclSpec().getExplicitSpecLoc());
2871 }
2872 }
2873
2874 // Filter out previous declarations that don't match the scope.
2875 FilterLookupForScope(*this, Previous, DC, S, NewFD->hasLinkage());
2876
2877 if (isFriend) {
2878 // DC is the namespace in which the function is being declared.
2879 assert((DC->isFileContext() || !Previous.empty()) &&
2880 "previously-undeclared friend function being created "
2881 "in a non-namespace context");
2882
2883 if (FunctionTemplate) {
2884 FunctionTemplate->setObjectOfFriendDecl(
2885 /* PreviouslyDeclared= */ !Previous.empty());
2886 FunctionTemplate->setAccess(AS_public);
2887 }
2888 else
2889 NewFD->setObjectOfFriendDecl(/* PreviouslyDeclared= */ !Previous.empty());
2890
2891 NewFD->setAccess(AS_public);
2892 }
2893
2894 if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) &&
2895 !CurContext->isRecord()) {
2896 // C++ [class.static]p1:
2897 // A data or function member of a class may be declared static
2898 // in a class definition, in which case it is a static member of
2899 // the class.
2900
2901 // Complain about the 'static' specifier if it's on an out-of-line
2902 // member function definition.
2903 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2904 diag::err_static_out_of_line)
2905 << CodeModificationHint::CreateRemoval(
2906 D.getDeclSpec().getStorageClassSpecLoc());
2907 }
2908
2909 // Handle GNU asm-label extension (encoded as an attribute).
2910 if (Expr *E = (Expr*) D.getAsmLabel()) {
2911 // The parser guarantees this is a string.
2912 StringLiteral *SE = cast<StringLiteral>(E);
2913 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getString()));
2914 }
2915
2916 // Copy the parameter declarations from the declarator D to the function
2917 // declaration NewFD, if they are available. First scavenge them into Params.
2918 llvm::SmallVector<ParmVarDecl*, 16> Params;
2919 if (D.getNumTypeObjects() > 0) {
2920 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2921
2922 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
2923 // function that takes no arguments, not a function that takes a
2924 // single void argument.
2925 // We let through "const void" here because Sema::GetTypeForDeclarator
2926 // already checks for that case.
2927 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2928 FTI.ArgInfo[0].Param &&
2929 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()) {
2930 // Empty arg list, don't push any params.
2931 ParmVarDecl *Param = FTI.ArgInfo[0].Param.getAs<ParmVarDecl>();
2932
2933 // In C++, the empty parameter-type-list must be spelled "void"; a
2934 // typedef of void is not permitted.
2935 if (getLangOptions().CPlusPlus &&
2936 Param->getType().getUnqualifiedType() != Context.VoidTy)
2937 Diag(Param->getLocation(), diag::err_param_typedef_of_void);
2938 // FIXME: Leaks decl?
2939 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
2940 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
2941 ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
2942 assert(Param->getDeclContext() != NewFD && "Was set before ?");
2943 Param->setDeclContext(NewFD);
2944 Params.push_back(Param);
2945 }
2946 }
2947
2948 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
2949 // When we're declaring a function with a typedef, typeof, etc as in the
2950 // following example, we'll need to synthesize (unnamed)
2951 // parameters for use in the declaration.
2952 //
2953 // @code
2954 // typedef void fn(int);
2955 // fn f;
2956 // @endcode
2957
2958 // Synthesize a parameter for each argument type.
2959 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
2960 AE = FT->arg_type_end(); AI != AE; ++AI) {
2961 ParmVarDecl *Param = ParmVarDecl::Create(Context, NewFD,
2962 SourceLocation(), 0,
2963 *AI, /*TInfo=*/0,
2964 VarDecl::None, 0);
2965 Param->setImplicit();
2966 Params.push_back(Param);
2967 }
2968 } else {
2969 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
2970 "Should not need args for typedef of non-prototype fn");
2971 }
2972 // Finally, we know we have the right number of parameters, install them.
2973 NewFD->setParams(Context, Params.data(), Params.size());
2974
2975 // If the declarator is a template-id, translate the parser's template
2976 // argument list into our AST format.
2977 bool HasExplicitTemplateArgs = false;
2978 TemplateArgumentListInfo TemplateArgs;
2979 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
2980 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
2981 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
2982 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
2983 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2984 TemplateId->getTemplateArgs(),
2985 TemplateId->NumArgs);
2986 translateTemplateArguments(TemplateArgsPtr,
2987 TemplateArgs);
2988 TemplateArgsPtr.release();
2989
2990 HasExplicitTemplateArgs = true;
2991
2992 if (FunctionTemplate) {
2993 // FIXME: Diagnose function template with explicit template
2994 // arguments.
2995 HasExplicitTemplateArgs = false;
2996 } else if (!isFunctionTemplateSpecialization &&
2997 !D.getDeclSpec().isFriendSpecified()) {
2998 // We have encountered something that the user meant to be a
2999 // specialization (because it has explicitly-specified template
3000 // arguments) but that was not introduced with a "template<>" (or had
3001 // too few of them).
3002 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
3003 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
3004 << CodeModificationHint::CreateInsertion(
3005 D.getDeclSpec().getSourceRange().getBegin(),
3006 "template<> ");
3007 isFunctionTemplateSpecialization = true;
3008 }
3009 }
3010
3011 if (isFunctionTemplateSpecialization) {
3012 if (CheckFunctionTemplateSpecialization(NewFD,
3013 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
3014 Previous))
3015 NewFD->setInvalidDecl();
3016 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD) &&
3017 CheckMemberSpecialization(NewFD, Previous))
3018 NewFD->setInvalidDecl();
3019
3020 // Perform semantic checking on the function declaration.
3021 bool OverloadableAttrRequired = false; // FIXME: HACK!
3022 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization,
3023 Redeclaration, /*FIXME:*/OverloadableAttrRequired);
3024
3025 assert((NewFD->isInvalidDecl() || !Redeclaration ||
3026 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
3027 "previous declaration set still overloaded");
3028
3029 // If we have a function template, check the template parameter
3030 // list. This will check and merge default template arguments.
3031 if (FunctionTemplate) {
3032 FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration();
3033 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
3034 PrevTemplate? PrevTemplate->getTemplateParameters() : 0,
3035 D.getDeclSpec().isFriendSpecified()? TPC_FriendFunctionTemplate
3036 : TPC_FunctionTemplate);
3037 }
3038
3039 if (D.getCXXScopeSpec().isSet() && !NewFD->isInvalidDecl()) {
3040 // Fake up an access specifier if it's supposed to be a class member.
3041 if (!Redeclaration && isa<CXXRecordDecl>(NewFD->getDeclContext()))
3042 NewFD->setAccess(AS_public);
3043
3044 // An out-of-line member function declaration must also be a
3045 // definition (C++ [dcl.meaning]p1).
3046 // Note that this is not the case for explicit specializations of
3047 // function templates or member functions of class templates, per
3048 // C++ [temp.expl.spec]p2.
3049 if (!IsFunctionDefinition && !isFriend &&
3050 !isFunctionTemplateSpecialization && !isExplicitSpecialization) {
3051 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
3052 << D.getCXXScopeSpec().getRange();
3053 NewFD->setInvalidDecl();
3054 } else if (!Redeclaration &&
3055 !(isFriend && CurContext->isDependentContext())) {
3056 // The user tried to provide an out-of-line definition for a
3057 // function that is a member of a class or namespace, but there
3058 // was no such member function declared (C++ [class.mfct]p2,
3059 // C++ [namespace.memdef]p2). For example:
3060 //
3061 // class X {
3062 // void f() const;
3063 // };
3064 //
3065 // void X::f() { } // ill-formed
3066 //
3067 // Complain about this problem, and attempt to suggest close
3068 // matches (e.g., those that differ only in cv-qualifiers and
3069 // whether the parameter types are references).
3070 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
3071 << Name << DC << D.getCXXScopeSpec().getRange();
3072 NewFD->setInvalidDecl();
3073
3074 LookupResult Prev(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
3075 ForRedeclaration);
3076 LookupQualifiedName(Prev, DC);
3077 assert(!Prev.isAmbiguous() &&
3078 "Cannot have an ambiguity in previous-declaration lookup");
3079 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
3080 Func != FuncEnd; ++Func) {
3081 if (isa<FunctionDecl>(*Func) &&
3082 isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
3083 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
3084 }
3085 }
3086 }
3087
3088 // Handle attributes. We need to have merged decls when handling attributes
3089 // (for example to check for conflicts, etc).
3090 // FIXME: This needs to happen before we merge declarations. Then,
3091 // let attribute merging cope with attribute conflicts.
3092 ProcessDeclAttributes(S, NewFD, D);
3093
3094 // attributes declared post-definition are currently ignored
3095 if (Redeclaration && Previous.isSingleResult()) {
3096 const FunctionDecl *Def;
3097 FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
3098 if (PrevFD && PrevFD->getBody(Def) && D.hasAttributes()) {
3099 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
3100 Diag(Def->getLocation(), diag::note_previous_definition);
3101 }
3102 }
3103
3104 AddKnownFunctionAttributes(NewFD);
3105
3106 if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) {
3107 // If a function name is overloadable in C, then every function
3108 // with that name must be marked "overloadable".
3109 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
3110 << Redeclaration << NewFD;
3111 if (!Previous.empty())
3112 Diag(Previous.getRepresentativeDecl()->getLocation(),
3113 diag::note_attribute_overloadable_prev_overload);
3114 NewFD->addAttr(::new (Context) OverloadableAttr());
3115 }
3116
3117 // If this is a locally-scoped extern C function, update the
3118 // map of such names.
3119 if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
3120 && !NewFD->isInvalidDecl())
3121 RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
3122
3123 // Set this FunctionDecl's range up to the right paren.
3124 NewFD->setLocEnd(D.getSourceRange().getEnd());
3125
3126 if (FunctionTemplate && NewFD->isInvalidDecl())
3127 FunctionTemplate->setInvalidDecl();
3128
3129 if (FunctionTemplate)
3130 return FunctionTemplate;
3131
3132 return NewFD;
3133}
3134
3135/// \brief Perform semantic checking of a new function declaration.
3136///
3137/// Performs semantic analysis of the new function declaration
3138/// NewFD. This routine performs all semantic checking that does not
3139/// require the actual declarator involved in the declaration, and is
3140/// used both for the declaration of functions as they are parsed
3141/// (called via ActOnDeclarator) and for the declaration of functions
3142/// that have been instantiated via C++ template instantiation (called
3143/// via InstantiateDecl).
3144///
3145/// \param IsExplicitSpecialiation whether this new function declaration is
3146/// an explicit specialization of the previous declaration.
3147///
3148/// This sets NewFD->isInvalidDecl() to true if there was an error.
3149void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
3150 LookupResult &Previous,
3151 bool IsExplicitSpecialization,
3152 bool &Redeclaration,
3153 bool &OverloadableAttrRequired) {
3154 // If NewFD is already known erroneous, don't do any of this checking.
3155 if (NewFD->isInvalidDecl())
3156 return;
3157
3158 if (NewFD->getResultType()->isVariablyModifiedType()) {
3159 // Functions returning a variably modified type violate C99 6.7.5.2p2
3160 // because all functions have linkage.
3161 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
3162 return NewFD->setInvalidDecl();
3163 }
3164
3165 if (NewFD->isMain())
3166 CheckMain(NewFD);
3167
3168 // Check for a previous declaration of this name.
3169 if (Previous.empty() && NewFD->isExternC()) {
3170 // Since we did not find anything by this name and we're declaring
3171 // an extern "C" function, look for a non-visible extern "C"
3172 // declaration with the same name.
3173 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3174 = LocallyScopedExternalDecls.find(NewFD->getDeclName());
3175 if (Pos != LocallyScopedExternalDecls.end())
3176 Previous.addDecl(Pos->second);
3177 }
3178
3179 // Merge or overload the declaration with an existing declaration of
3180 // the same name, if appropriate.
3181 if (!Previous.empty()) {
3182 // Determine whether NewFD is an overload of PrevDecl or
3183 // a declaration that requires merging. If it's an overload,
3184 // there's no more work to do here; we'll just add the new
3185 // function to the scope.
3186
3187 NamedDecl *OldDecl = 0;
3188 if (!AllowOverloadingOfFunction(Previous, Context)) {
3189 Redeclaration = true;
3190 OldDecl = Previous.getFoundDecl();
3191 } else {
3192 if (!getLangOptions().CPlusPlus) {
3193 OverloadableAttrRequired = true;
3194
3195 // Functions marked "overloadable" must have a prototype (that
3196 // we can't get through declaration merging).
3197 if (!NewFD->getType()->getAs<FunctionProtoType>()) {
3198 Diag(NewFD->getLocation(),
3199 diag::err_attribute_overloadable_no_prototype)
3200 << NewFD;
3201 Redeclaration = true;
3202
3203 // Turn this into a variadic function with no parameters.
3204 QualType R = Context.getFunctionType(
3205 NewFD->getType()->getAs<FunctionType>()->getResultType(),
3206 0, 0, true, 0);
3207 NewFD->setType(R);
3208 return NewFD->setInvalidDecl();
3209 }
3210 }
3211
3212 switch (CheckOverload(NewFD, Previous, OldDecl)) {
3213 case Ovl_Match:
3214 Redeclaration = true;
3215 if (isa<UsingShadowDecl>(OldDecl) && CurContext->isRecord()) {
3216 HideUsingShadowDecl(S, cast<UsingShadowDecl>(OldDecl));
3217 Redeclaration = false;
3218 }
3219 break;
3220
3221 case Ovl_NonFunction:
3222 Redeclaration = true;
3223 break;
3224
3225 case Ovl_Overload:
3226 Redeclaration = false;
3227 break;
3228 }
3229 }
3230
3231 if (Redeclaration) {
3232 // NewFD and OldDecl represent declarations that need to be
3233 // merged.
3234 if (MergeFunctionDecl(NewFD, OldDecl))
3235 return NewFD->setInvalidDecl();
3236
3237 Previous.clear();
3238 Previous.addDecl(OldDecl);
3239
3240 if (FunctionTemplateDecl *OldTemplateDecl
3241 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
3242 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
3243 FunctionTemplateDecl *NewTemplateDecl
3244 = NewFD->getDescribedFunctionTemplate();
3245 assert(NewTemplateDecl && "Template/non-template mismatch");
3246 if (CXXMethodDecl *Method
3247 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
3248 Method->setAccess(OldTemplateDecl->getAccess());
3249 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
3250 }
3251
3252 // If this is an explicit specialization of a member that is a function
3253 // template, mark it as a member specialization.
3254 if (IsExplicitSpecialization &&
3255 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
3256 NewTemplateDecl->setMemberSpecialization();
3257 assert(OldTemplateDecl->isMemberSpecialization());
3258 }
3259 } else {
3260 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
3261 NewFD->setAccess(OldDecl->getAccess());
3262 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
3263 }
3264 }
3265 }
3266
3267 // Semantic checking for this function declaration (in isolation).
3268 if (getLangOptions().CPlusPlus) {
3269 // C++-specific checks.
3270 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
3271 CheckConstructor(Constructor);
3272 } else if (CXXDestructorDecl *Destructor =
3273 dyn_cast<CXXDestructorDecl>(NewFD)) {
3274 CXXRecordDecl *Record = Destructor->getParent();
3275 QualType ClassType = Context.getTypeDeclType(Record);
3276
3277 // FIXME: Shouldn't we be able to perform thisc heck even when the class
3278 // type is dependent? Both gcc and edg can handle that.
3279 if (!ClassType->isDependentType()) {
3280 DeclarationName Name
3281 = Context.DeclarationNames.getCXXDestructorName(
3282 Context.getCanonicalType(ClassType));
3283 if (NewFD->getDeclName() != Name) {
3284 Diag(NewFD->getLocation(), diag::err_destructor_name);
3285 return NewFD->setInvalidDecl();
3286 }
3287 }
3288
3289 Record->setUserDeclaredDestructor(true);
3290 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
3291 // user-defined destructor.
3292 Record->setPOD(false);
3293
3294 // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly-
3295 // declared destructor.
3296 // FIXME: C++0x: don't do this for "= default" destructors
3297 Record->setHasTrivialDestructor(false);
3298 } else if (CXXConversionDecl *Conversion
3299 = dyn_cast<CXXConversionDecl>(NewFD)) {
3300 ActOnConversionDeclarator(Conversion);
3301 }
3302
3303 // Find any virtual functions that this function overrides.
3304 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
3305 if (!Method->isFunctionTemplateSpecialization() &&
3306 !Method->getDescribedFunctionTemplate())
3307 AddOverriddenMethods(Method->getParent(), Method);
3308 }
3309
3310 // Additional checks for the destructor; make sure we do this after we
3311 // figure out whether the destructor is virtual.
3312 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
3313 if (!Destructor->getParent()->isDependentType())
3314 CheckDestructor(Destructor);
3315
3316 // Extra checking for C++ overloaded operators (C++ [over.oper]).
3317 if (NewFD->isOverloadedOperator() &&
3318 CheckOverloadedOperatorDeclaration(NewFD))
3319 return NewFD->setInvalidDecl();
3320
3321 // Extra checking for C++0x literal operators (C++0x [over.literal]).
3322 if (NewFD->getLiteralIdentifier() &&
3323 CheckLiteralOperatorDeclaration(NewFD))
3324 return NewFD->setInvalidDecl();
3325
3326 // In C++, check default arguments now that we have merged decls. Unless
3327 // the lexical context is the class, because in this case this is done
3328 // during delayed parsing anyway.
3329 if (!CurContext->isRecord())
3330 CheckCXXDefaultArguments(NewFD);
3331 }
3332}
3333
3334void Sema::CheckMain(FunctionDecl* FD) {
3335 // C++ [basic.start.main]p3: A program that declares main to be inline
3336 // or static is ill-formed.
3337 // C99 6.7.4p4: In a hosted environment, the inline function specifier
3338 // shall not appear in a declaration of main.
3339 // static main is not an error under C99, but we should warn about it.
3340 bool isInline = FD->isInlineSpecified();
3341 bool isStatic = FD->getStorageClass() == FunctionDecl::Static;
3342 if (isInline || isStatic) {
3343 unsigned diagID = diag::warn_unusual_main_decl;
3344 if (isInline || getLangOptions().CPlusPlus)
3345 diagID = diag::err_unusual_main_decl;
3346
3347 int which = isStatic + (isInline << 1) - 1;
3348 Diag(FD->getLocation(), diagID) << which;
3349 }
3350
3351 QualType T = FD->getType();
3352 assert(T->isFunctionType() && "function decl is not of function type");
3353 const FunctionType* FT = T->getAs<FunctionType>();
3354
3355 if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
3356 // TODO: add a replacement fixit to turn the return type into 'int'.
3357 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
3358 FD->setInvalidDecl(true);
3359 }
3360
3361 // Treat protoless main() as nullary.
3362 if (isa<FunctionNoProtoType>(FT)) return;
3363
3364 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
3365 unsigned nparams = FTP->getNumArgs();
3366 assert(FD->getNumParams() == nparams);
3367
3368 bool HasExtraParameters = (nparams > 3);
3369
3370 // Darwin passes an undocumented fourth argument of type char**. If
3371 // other platforms start sprouting these, the logic below will start
3372 // getting shifty.
3373 if (nparams == 4 &&
3374 Context.Target.getTriple().getOS() == llvm::Triple::Darwin)
3375 HasExtraParameters = false;
3376
3377 if (HasExtraParameters) {
3378 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
3379 FD->setInvalidDecl(true);
3380 nparams = 3;
3381 }
3382
3383 // FIXME: a lot of the following diagnostics would be improved
3384 // if we had some location information about types.
3385
3386 QualType CharPP =
3387 Context.getPointerType(Context.getPointerType(Context.CharTy));
3388 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
3389
3390 for (unsigned i = 0; i < nparams; ++i) {
3391 QualType AT = FTP->getArgType(i);
3392
3393 bool mismatch = true;
3394
3395 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
3396 mismatch = false;
3397 else if (Expected[i] == CharPP) {
3398 // As an extension, the following forms are okay:
3399 // char const **
3400 // char const * const *
3401 // char * const *
3402
3403 QualifierCollector qs;
3404 const PointerType* PT;
3405 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
3406 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
3407 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
3408 qs.removeConst();
3409 mismatch = !qs.empty();
3410 }
3411 }
3412
3413 if (mismatch) {
3414 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
3415 // TODO: suggest replacing given type with expected type
3416 FD->setInvalidDecl(true);
3417 }
3418 }
3419
3420 if (nparams == 1 && !FD->isInvalidDecl()) {
3421 Diag(FD->getLocation(), diag::warn_main_one_arg);
3422 }
3423}
3424
3425bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
3426 // FIXME: Need strict checking. In C89, we need to check for
3427 // any assignment, increment, decrement, function-calls, or
3428 // commas outside of a sizeof. In C99, it's the same list,
3429 // except that the aforementioned are allowed in unevaluated
3430 // expressions. Everything else falls under the
3431 // "may accept other forms of constant expressions" exception.
3432 // (We never end up here for C++, so the constant expression
3433 // rules there don't matter.)
3434 if (Init->isConstantInitializer(Context))
3435 return false;
3436 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
3437 << Init->getSourceRange();
3438 return true;
3439}
3440
3441void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init) {
3442 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
3443}
3444
3445/// AddInitializerToDecl - Adds the initializer Init to the
3446/// declaration dcl. If DirectInit is true, this is C++ direct
3447/// initialization rather than copy initialization.
3448void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init, bool DirectInit) {
3449 Decl *RealDecl = dcl.getAs<Decl>();
3450 // If there is no declaration, there was an error parsing it. Just ignore
3451 // the initializer.
3452 if (RealDecl == 0)
3453 return;
3454
3455 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
3456 // With declarators parsed the way they are, the parser cannot
3457 // distinguish between a normal initializer and a pure-specifier.
3458 // Thus this grotesque test.
3459 IntegerLiteral *IL;
3460 Expr *Init = static_cast<Expr *>(init.get());
3461 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
3462 Context.getCanonicalType(IL->getType()) == Context.IntTy)
3463 CheckPureMethod(Method, Init->getSourceRange());
3464 else {
3465 Diag(Method->getLocation(), diag::err_member_function_initialization)
3466 << Method->getDeclName() << Init->getSourceRange();
3467 Method->setInvalidDecl();
3468 }
3469 return;
3470 }
3471
3472 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3473 if (!VDecl) {
3474 if (getLangOptions().CPlusPlus &&
3475 RealDecl->getLexicalDeclContext()->isRecord() &&
3476 isa<NamedDecl>(RealDecl))
3477 Diag(RealDecl->getLocation(), diag::err_member_initialization)
3478 << cast<NamedDecl>(RealDecl)->getDeclName();
3479 else
3480 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3481 RealDecl->setInvalidDecl();
3482 return;
3483 }
3484
3485 // A definition must end up with a complete type, which means it must be
3486 // complete with the restriction that an array type might be completed by the
3487 // initializer; note that later code assumes this restriction.
3488 QualType BaseDeclType = VDecl->getType();
3489 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
3490 BaseDeclType = Array->getElementType();
3491 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
3492 diag::err_typecheck_decl_incomplete_type)) {
3493 RealDecl->setInvalidDecl();
3494 return;
3495 }
3496
3497 // The variable can not have an abstract class type.
3498 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
3499 diag::err_abstract_type_in_decl,
3500 AbstractVariableType))
3501 VDecl->setInvalidDecl();
3502
3503 const VarDecl *Def;
3504 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
3505 Diag(VDecl->getLocation(), diag::err_redefinition)
3506 << VDecl->getDeclName();
3507 Diag(Def->getLocation(), diag::note_previous_definition);
3508 VDecl->setInvalidDecl();
3509 return;
3510 }
3511
3512 // Take ownership of the expression, now that we're sure we have somewhere
3513 // to put it.
3514 Expr *Init = init.takeAs<Expr>();
3515 assert(Init && "missing initializer");
3516
3517 // Capture the variable that is being initialized and the style of
3518 // initialization.
3519 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
3520
3521 // FIXME: Poor source location information.
3522 InitializationKind Kind
3523 = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(),
3524 Init->getLocStart(),
3525 Init->getLocEnd())
3526 : InitializationKind::CreateCopy(VDecl->getLocation(),
3527 Init->getLocStart());
3528
3529 // Get the decls type and save a reference for later, since
3530 // CheckInitializerTypes may change it.
3531 QualType DclT = VDecl->getType(), SavT = DclT;
3532 if (VDecl->isBlockVarDecl()) {
3533 if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
3534 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
3535 VDecl->setInvalidDecl();
3536 } else if (!VDecl->isInvalidDecl()) {
3537 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
3538 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3539 MultiExprArg(*this, (void**)&Init, 1),
3540 &DclT);
3541 if (Result.isInvalid()) {
3542 VDecl->setInvalidDecl();
3543 return;
3544 }
3545
3546 Init = Result.takeAs<Expr>();
3547
3548 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
3549 // Don't check invalid declarations to avoid emitting useless diagnostics.
3550 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
3551 if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4.
3552 CheckForConstantInitializer(Init, DclT);
3553 }
3554 }
3555 } else if (VDecl->isStaticDataMember() &&
3556 VDecl->getLexicalDeclContext()->isRecord()) {
3557 // This is an in-class initialization for a static data member, e.g.,
3558 //
3559 // struct S {
3560 // static const int value = 17;
3561 // };
3562
3563 // Attach the initializer
3564 VDecl->setInit(Context, Init);
3565
3566 // C++ [class.mem]p4:
3567 // A member-declarator can contain a constant-initializer only
3568 // if it declares a static member (9.4) of const integral or
3569 // const enumeration type, see 9.4.2.
3570 QualType T = VDecl->getType();
3571 if (!T->isDependentType() &&
3572 (!Context.getCanonicalType(T).isConstQualified() ||
3573 !T->isIntegralType())) {
3574 Diag(VDecl->getLocation(), diag::err_member_initialization)
3575 << VDecl->getDeclName() << Init->getSourceRange();
3576 VDecl->setInvalidDecl();
3577 } else {
3578 // C++ [class.static.data]p4:
3579 // If a static data member is of const integral or const
3580 // enumeration type, its declaration in the class definition
3581 // can specify a constant-initializer which shall be an
3582 // integral constant expression (5.19).
3583 if (!Init->isTypeDependent() &&
3584 !Init->getType()->isIntegralType()) {
3585 // We have a non-dependent, non-integral or enumeration type.
3586 Diag(Init->getSourceRange().getBegin(),
3587 diag::err_in_class_initializer_non_integral_type)
3588 << Init->getType() << Init->getSourceRange();
3589 VDecl->setInvalidDecl();
3590 } else if (!Init->isTypeDependent() && !Init->isValueDependent()) {
3591 // Check whether the expression is a constant expression.
3592 llvm::APSInt Value;
3593 SourceLocation Loc;
3594 if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) {
3595 Diag(Loc, diag::err_in_class_initializer_non_constant)
3596 << Init->getSourceRange();
3597 VDecl->setInvalidDecl();
3598 } else if (!VDecl->getType()->isDependentType())
3599 ImpCastExprToType(Init, VDecl->getType(), CastExpr::CK_IntegralCast);
3600 }
3601 }
3602 } else if (VDecl->isFileVarDecl()) {
3603 if (VDecl->getStorageClass() == VarDecl::Extern)
3604 Diag(VDecl->getLocation(), diag::warn_extern_init);
3605 if (!VDecl->isInvalidDecl()) {
3606 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
3607 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3608 MultiExprArg(*this, (void**)&Init, 1),
3609 &DclT);
3610 if (Result.isInvalid()) {
3611 VDecl->setInvalidDecl();
3612 return;
3613 }
3614
3615 Init = Result.takeAs<Expr>();
3616 }
3617
3618 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
3619 // Don't check invalid declarations to avoid emitting useless diagnostics.
3620 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
3621 // C99 6.7.8p4. All file scoped initializers need to be constant.
3622 CheckForConstantInitializer(Init, DclT);
3623 }
3624 }
3625 // If the type changed, it means we had an incomplete type that was
3626 // completed by the initializer. For example:
3627 // int ary[] = { 1, 3, 5 };
3628 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
3629 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
3630 VDecl->setType(DclT);
3631 Init->setType(DclT);
3632 }
3633
3634 Init = MaybeCreateCXXExprWithTemporaries(Init);
3635 // Attach the initializer to the decl.
3636 VDecl->setInit(Context, Init);
3637
3638 if (getLangOptions().CPlusPlus) {
3639 // Make sure we mark the destructor as used if necessary.
3640 QualType InitType = VDecl->getType();
3641 while (const ArrayType *Array = Context.getAsArrayType(InitType))
3642 InitType = Context.getBaseElementType(Array);
3643 if (const RecordType *Record = InitType->getAs<RecordType>())
3644 FinalizeVarWithDestructor(VDecl, Record);
3645 }
3646
3647 return;
3648}
3649
3650void Sema::ActOnUninitializedDecl(DeclPtrTy dcl,
3651 bool TypeContainsUndeducedAuto) {
3652 Decl *RealDecl = dcl.getAs<Decl>();
3653
3654 // If there is no declaration, there was an error parsing it. Just ignore it.
3655 if (RealDecl == 0)
3656 return;
3657
3658 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
3659 QualType Type = Var->getType();
3660
3661 // C++0x [dcl.spec.auto]p3
3662 if (TypeContainsUndeducedAuto) {
3663 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
3664 << Var->getDeclName() << Type;
3665 Var->setInvalidDecl();
3666 return;
3667 }
3668
3669 switch (Var->isThisDeclarationADefinition()) {
3670 case VarDecl::Definition:
3671 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
3672 break;
3673
3674 // We have an out-of-line definition of a static data member
3675 // that has an in-class initializer, so we type-check this like
3676 // a declaration.
3677 //
3678 // Fall through
3679
3680 case VarDecl::DeclarationOnly:
3681 // It's only a declaration.
3682
3683 // Block scope. C99 6.7p7: If an identifier for an object is
3684 // declared with no linkage (C99 6.2.2p6), the type for the
3685 // object shall be complete.
3686 if (!Type->isDependentType() && Var->isBlockVarDecl() &&
3687 !Var->getLinkage() && !Var->isInvalidDecl() &&
3688 RequireCompleteType(Var->getLocation(), Type,
3689 diag::err_typecheck_decl_incomplete_type))
3690 Var->setInvalidDecl();
3691
3692 // Make sure that the type is not abstract.
3693 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
3694 RequireNonAbstractType(Var->getLocation(), Type,
3695 diag::err_abstract_type_in_decl,
3696 AbstractVariableType))
3697 Var->setInvalidDecl();
3698 return;
3699
3700 case VarDecl::TentativeDefinition:
3701 // File scope. C99 6.9.2p2: A declaration of an identifier for an
3702 // object that has file scope without an initializer, and without a
3703 // storage-class specifier or with the storage-class specifier "static",
3704 // constitutes a tentative definition. Note: A tentative definition with
3705 // external linkage is valid (C99 6.2.2p5).
3706 if (!Var->isInvalidDecl()) {
3707 if (const IncompleteArrayType *ArrayT
3708 = Context.getAsIncompleteArrayType(Type)) {
3709 if (RequireCompleteType(Var->getLocation(),
3710 ArrayT->getElementType(),
3711 diag::err_illegal_decl_array_incomplete_type))
3712 Var->setInvalidDecl();
3713 } else if (Var->getStorageClass() == VarDecl::Static) {
3714 // C99 6.9.2p3: If the declaration of an identifier for an object is
3715 // a tentative definition and has internal linkage (C99 6.2.2p3), the
3716 // declared type shall not be an incomplete type.
3717 // NOTE: code such as the following
3718 // static struct s;
3719 // struct s { int a; };
3720 // is accepted by gcc. Hence here we issue a warning instead of
3721 // an error and we do not invalidate the static declaration.
3722 // NOTE: to avoid multiple warnings, only check the first declaration.
3723 if (Var->getPreviousDeclaration() == 0)
3724 RequireCompleteType(Var->getLocation(), Type,
3725 diag::ext_typecheck_decl_incomplete_type);
3726 }
3727 }
3728
3729 // Record the tentative definition; we're done.
3730 if (!Var->isInvalidDecl())
3731 TentativeDefinitions.push_back(Var);
3732 return;
3733 }
3734
3735 // Provide a specific diagnostic for uninitialized variable
3736 // definitions with incomplete array type.
3737 if (Type->isIncompleteArrayType()) {
3738 Diag(Var->getLocation(),
3739 diag::err_typecheck_incomplete_array_needs_initializer);
3740 Var->setInvalidDecl();
3741 return;
3742 }
3743
3744 // Provide a specific diagnostic for uninitialized variable
3745 // definitions with reference type.
3746 if (Type->isReferenceType()) {
3747 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
3748 << Var->getDeclName()
3749 << SourceRange(Var->getLocation(), Var->getLocation());
3750 Var->setInvalidDecl();
3751 return;
3752 }
3753
3754 // Do not attempt to type-check the default initializer for a
3755 // variable with dependent type.
3756 if (Type->isDependentType())
3757 return;
3758
3759 if (Var->isInvalidDecl())
3760 return;
3761
3762 if (RequireCompleteType(Var->getLocation(),
3763 Context.getBaseElementType(Type),
3764 diag::err_typecheck_decl_incomplete_type)) {
3765 Var->setInvalidDecl();
3766 return;
3767 }
3768
3769 // The variable can not have an abstract class type.
3770 if (RequireNonAbstractType(Var->getLocation(), Type,
3771 diag::err_abstract_type_in_decl,
3772 AbstractVariableType)) {
3773 Var->setInvalidDecl();
3774 return;
3775 }
3776
3777 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
3778 InitializationKind Kind
3779 = InitializationKind::CreateDefault(Var->getLocation());
3780
3781 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
3782 OwningExprResult Init = InitSeq.Perform(*this, Entity, Kind,
3783 MultiExprArg(*this, 0, 0));
3784 if (Init.isInvalid())
3785 Var->setInvalidDecl();
3786 else {
3787 if (Init.get())
3788 Var->setInit(Context,
3789 MaybeCreateCXXExprWithTemporaries(Init.takeAs<Expr>()));
3790
3791 if (getLangOptions().CPlusPlus)
3792 if (const RecordType *Record
3793 = Context.getBaseElementType(Type)->getAs<RecordType>())
3794 FinalizeVarWithDestructor(Var, Record);
3795 }
3796 }
3797}
3798
3799Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
3800 DeclPtrTy *Group,
3801 unsigned NumDecls) {
3802 llvm::SmallVector<Decl*, 8> Decls;
3803
3804 if (DS.isTypeSpecOwned())
3805 Decls.push_back((Decl*)DS.getTypeRep());
3806
3807 for (unsigned i = 0; i != NumDecls; ++i)
3808 if (Decl *D = Group[i].getAs<Decl>())
3809 Decls.push_back(D);
3810
3811 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context,
3812 Decls.data(), Decls.size()));
3813}
3814
3815
3816/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
3817/// to introduce parameters into function prototype scope.
3818Sema::DeclPtrTy
3819Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
3820 const DeclSpec &DS = D.getDeclSpec();
3821
3822 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
3823 VarDecl::StorageClass StorageClass = VarDecl::None;
3824 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
3825 StorageClass = VarDecl::Register;
3826 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
3827 Diag(DS.getStorageClassSpecLoc(),
3828 diag::err_invalid_storage_class_in_func_decl);
3829 D.getMutableDeclSpec().ClearStorageClassSpecs();
3830 }
3831
3832 if (D.getDeclSpec().isThreadSpecified())
3833 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
3834
3835 DiagnoseFunctionSpecifiers(D);
3836
3837 // Check that there are no default arguments inside the type of this
3838 // parameter (C++ only).
3839 if (getLangOptions().CPlusPlus)
3840 CheckExtraCXXDefaultArguments(D);
3841
3842 TypeSourceInfo *TInfo = 0;
3843 TagDecl *OwnedDecl = 0;
3844 QualType parmDeclType = GetTypeForDeclarator(D, S, &TInfo, &OwnedDecl);
3845
3846 if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) {
3847 // C++ [dcl.fct]p6:
3848 // Types shall not be defined in return or parameter types.
3849 Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
3850 << Context.getTypeDeclType(OwnedDecl);
3851 }
3852
3853 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
3854 // Can this happen for params? We already checked that they don't conflict
3855 // among each other. Here they can only shadow globals, which is ok.
3856 IdentifierInfo *II = D.getIdentifier();
3857 if (II) {
3858 if (NamedDecl *PrevDecl = LookupSingleName(S, II, LookupOrdinaryName)) {
3859 if (PrevDecl->isTemplateParameter()) {
3860 // Maybe we will complain about the shadowed template parameter.
3861 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
3862 // Just pretend that we didn't see the previous declaration.
3863 PrevDecl = 0;
3864 } else if (S->isDeclScope(DeclPtrTy::make(PrevDecl))) {
3865 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
3866
3867 // Recover by removing the name
3868 II = 0;
3869 D.SetIdentifier(0, D.getIdentifierLoc());
3870 }
3871 }
3872 }
3873
3874 // Parameters can not be abstract class types.
3875 // For record types, this is done by the AbstractClassUsageDiagnoser once
3876 // the class has been completely parsed.
3877 if (!CurContext->isRecord() &&
3878 RequireNonAbstractType(D.getIdentifierLoc(), parmDeclType,
3879 diag::err_abstract_type_in_decl,
3880 AbstractParamType))
3881 D.setInvalidType(true);
3882
3883 QualType T = adjustParameterType(parmDeclType);
3884
3885 // Temporarily put parameter variables in the translation unit, not
3886 // the enclosing context. This prevents them from accidentally
3887 // looking like class members in C++.
3888 DeclContext *DC = Context.getTranslationUnitDecl();
3889
3890 ParmVarDecl *New
3891 = ParmVarDecl::Create(Context, DC, D.getIdentifierLoc(), II,
3892 T, TInfo, StorageClass, 0);
3893
3894 if (D.isInvalidType())
3895 New->setInvalidDecl();
3896
3897 // Parameter declarators cannot be interface types. All ObjC objects are
3898 // passed by reference.
3899 if (T->isObjCInterfaceType()) {
3900 Diag(D.getIdentifierLoc(),
3901 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
3902 New->setInvalidDecl();
3903 }
3904
3905 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
3906 if (D.getCXXScopeSpec().isSet()) {
3907 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
3908 << D.getCXXScopeSpec().getRange();
3909 New->setInvalidDecl();
3910 }
3911
3912 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
3913 // duration shall not be qualified by an address-space qualifier."
3914 // Since all parameters have automatic store duration, they can not have
3915 // an address space.
3916 if (T.getAddressSpace() != 0) {
3917 Diag(D.getIdentifierLoc(),
3918 diag::err_arg_with_address_space);
3919 New->setInvalidDecl();
3920 }
3921
3922
3923 // Add the parameter declaration into this scope.
3924 S->AddDecl(DeclPtrTy::make(New));
3925 if (II)
3926 IdResolver.AddDecl(New);
3927
3928 ProcessDeclAttributes(S, New, D);
3929
3930 if (New->hasAttr<BlocksAttr>()) {
3931 Diag(New->getLocation(), diag::err_block_on_nonlocal);
3932 }
3933 return DeclPtrTy::make(New);
3934}
3935
3936void Sema::ActOnObjCCatchParam(DeclPtrTy D) {
3937 ParmVarDecl *Param = cast<ParmVarDecl>(D.getAs<Decl>());
3938 Param->setDeclContext(CurContext);
3939}
3940
3941void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
3942 SourceLocation LocAfterDecls) {
3943 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3944 "Not a function declarator!");
3945 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3946
3947 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
3948 // for a K&R function.
3949 if (!FTI.hasPrototype) {
3950 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
3951 --i;
3952 if (FTI.ArgInfo[i].Param == 0) {
3953 llvm::SmallString<256> Code;
3954 llvm::raw_svector_ostream(Code) << " int "
3955 << FTI.ArgInfo[i].Ident->getName()
3956 << ";\n";
3957 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
3958 << FTI.ArgInfo[i].Ident
3959 << CodeModificationHint::CreateInsertion(LocAfterDecls, Code.str());
3960
3961 // Implicitly declare the argument as type 'int' for lack of a better
3962 // type.
3963 DeclSpec DS;
3964 const char* PrevSpec; // unused
3965 unsigned DiagID; // unused
3966 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
3967 PrevSpec, DiagID);
3968 Declarator ParamD(DS, Declarator::KNRTypeListContext);
3969 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
3970 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
3971 }
3972 }
3973 }
3974}
3975
3976Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
3977 Declarator &D) {
3978 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
3979 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3980 "Not a function declarator!");
3981 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3982
3983 if (FTI.hasPrototype) {
3984 // FIXME: Diagnose arguments without names in C.
3985 }
3986
3987 Scope *ParentScope = FnBodyScope->getParent();
3988
3989 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
3990 MultiTemplateParamsArg(*this),
3991 /*IsFunctionDefinition=*/true);
3992 return ActOnStartOfFunctionDef(FnBodyScope, DP);
3993}
3994
3995static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
3996 // Don't warn about invalid declarations.
3997 if (FD->isInvalidDecl())
3998 return false;
3999
4000 // Or declarations that aren't global.
4001 if (!FD->isGlobal())
4002 return false;
4003
4004 // Don't warn about C++ member functions.
4005 if (isa<CXXMethodDecl>(FD))
4006 return false;
4007
4008 // Don't warn about 'main'.
4009 if (FD->isMain())
4010 return false;
4011
4012 // Don't warn about inline functions.
4013 if (FD->isInlineSpecified())
4014 return false;
4015
4016 // Don't warn about function templates.
4017 if (FD->getDescribedFunctionTemplate())
4018 return false;
4019
4020 // Don't warn about function template specializations.
4021 if (FD->isFunctionTemplateSpecialization())
4022 return false;
4023
4024 bool MissingPrototype = true;
4025 for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
4026 Prev; Prev = Prev->getPreviousDeclaration()) {
4027 // Ignore any declarations that occur in function or method
4028 // scope, because they aren't visible from the header.
4029 if (Prev->getDeclContext()->isFunctionOrMethod())
4030 continue;
4031
4032 MissingPrototype = !Prev->getType()->isFunctionProtoType();
4033 break;
4034 }
4035
4036 return MissingPrototype;
4037}
4038
4039Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) {
4040 // Clear the last template instantiation error context.
4041 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
4042
4043 if (!D)
4044 return D;
4045 FunctionDecl *FD = 0;
4046
4047 if (FunctionTemplateDecl *FunTmpl
4048 = dyn_cast<FunctionTemplateDecl>(D.getAs<Decl>()))
4049 FD = FunTmpl->getTemplatedDecl();
4050 else
4051 FD = cast<FunctionDecl>(D.getAs<Decl>());
4052
4053 CurFunctionNeedsScopeChecking = false;
4054
4055 // See if this is a redefinition.
4056 const FunctionDecl *Definition;
4057 if (FD->getBody(Definition)) {
4058 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
4059 Diag(Definition->getLocation(), diag::note_previous_definition);
4060 }
4061
4062 // Builtin functions cannot be defined.
4063 if (unsigned BuiltinID = FD->getBuiltinID()) {
4064 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4065 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
4066 FD->setInvalidDecl();
4067 }
4068 }
4069
4070 // The return type of a function definition must be complete
4071 // (C99 6.9.1p3, C++ [dcl.fct]p6).
4072 QualType ResultType = FD->getResultType();
4073 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
4074 !FD->isInvalidDecl() &&
4075 RequireCompleteType(FD->getLocation(), ResultType,
4076 diag::err_func_def_incomplete_result))
4077 FD->setInvalidDecl();
4078
4079 // GNU warning -Wmissing-prototypes:
4080 // Warn if a global function is defined without a previous
4081 // prototype declaration. This warning is issued even if the
4082 // definition itself provides a prototype. The aim is to detect
4083 // global functions that fail to be declared in header files.
4084 if (ShouldWarnAboutMissingPrototype(FD))
4085 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
4086
4087 if (FnBodyScope)
4088 PushDeclContext(FnBodyScope, FD);
4089
4090 // Check the validity of our function parameters
4091 CheckParmsForFunctionDef(FD);
4092
4093 // Introduce our parameters into the function scope
4094 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
4095 ParmVarDecl *Param = FD->getParamDecl(p);
4096 Param->setOwningFunction(FD);
4097
4098 // If this has an identifier, add it to the scope stack.
4099 if (Param->getIdentifier() && FnBodyScope)
4100 PushOnScopeChains(Param, FnBodyScope);
4101 }
4102
4103 // Checking attributes of current function definition
4104 // dllimport attribute.
4105 if (FD->getAttr<DLLImportAttr>() &&
4106 (!FD->getAttr<DLLExportAttr>())) {
4107 // dllimport attribute cannot be applied to definition.
4108 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
4109 Diag(FD->getLocation(),
4110 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
4111 << "dllimport";
4112 FD->setInvalidDecl();
4113 return DeclPtrTy::make(FD);
4114 } else {
4115 // If a symbol previously declared dllimport is later defined, the
4116 // attribute is ignored in subsequent references, and a warning is
4117 // emitted.
4118 Diag(FD->getLocation(),
4119 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
4120 << FD->getNameAsCString() << "dllimport";
4121 }
4122 }
4123 return DeclPtrTy::make(FD);
4124}
4125
4126Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) {
4127 return ActOnFinishFunctionBody(D, move(BodyArg), false);
4128}
4129
4130Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg,
4131 bool IsInstantiation) {
4132 Decl *dcl = D.getAs<Decl>();
4133 Stmt *Body = BodyArg.takeAs<Stmt>();
4134
4135 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
4136 // explosion for destrutors that can result and the compile time hit.
4137 AnalysisContext AC(dcl, false);
4138 FunctionDecl *FD = 0;
4139 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
4140 if (FunTmpl)
4141 FD = FunTmpl->getTemplatedDecl();
4142 else
4143 FD = dyn_cast_or_null<FunctionDecl>(dcl);
4144
4145 if (FD) {
4146 FD->setBody(Body);
4147 if (FD->isMain())
4148 // C and C++ allow for main to automagically return 0.
4149 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
4150 FD->setHasImplicitReturnZero(true);
4151 else
4152 CheckFallThroughForFunctionDef(FD, Body, AC);
4153
4154 if (!FD->isInvalidDecl())
4155 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
4156
4157 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
4158 MaybeMarkVirtualMembersReferenced(Method->getLocation(), Method);
4159
4160 assert(FD == getCurFunctionDecl() && "Function parsing confused");
4161 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
4162 assert(MD == getCurMethodDecl() && "Method parsing confused");
4163 MD->setBody(Body);
4164 CheckFallThroughForFunctionDef(MD, Body, AC);
4165 MD->setEndLoc(Body->getLocEnd());
4166
4167 if (!MD->isInvalidDecl())
4168 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
4169 } else {
4170 Body->Destroy(Context);
4171 return DeclPtrTy();
4172 }
4173 if (!IsInstantiation)
4174 PopDeclContext();
4175
4176 // Verify and clean out per-function state.
4177
4178 assert(&getLabelMap() == &FunctionLabelMap && "Didn't pop block right?");
4179
4180 // Check goto/label use.
4181 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
4182 I = FunctionLabelMap.begin(), E = FunctionLabelMap.end(); I != E; ++I) {
4183 LabelStmt *L = I->second;
4184
4185 // Verify that we have no forward references left. If so, there was a goto
4186 // or address of a label taken, but no definition of it. Label fwd
4187 // definitions are indicated with a null substmt.
4188 if (L->getSubStmt() != 0)
4189 continue;
4190
4191 // Emit error.
4192 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
4193
4194 // At this point, we have gotos that use the bogus label. Stitch it into
4195 // the function body so that they aren't leaked and that the AST is well
4196 // formed.
4197 if (Body == 0) {
4198 // The whole function wasn't parsed correctly, just delete this.
4199 L->Destroy(Context);
4200 continue;
4201 }
4202
4203 // Otherwise, the body is valid: we want to stitch the label decl into the
4204 // function somewhere so that it is properly owned and so that the goto
4205 // has a valid target. Do this by creating a new compound stmt with the
4206 // label in it.
4207
4208 // Give the label a sub-statement.
4209 L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
4210
4211 CompoundStmt *Compound = isa<CXXTryStmt>(Body) ?
4212 cast<CXXTryStmt>(Body)->getTryBlock() :
4213 cast<CompoundStmt>(Body);
4214 std::vector<Stmt*> Elements(Compound->body_begin(), Compound->body_end());
4215 Elements.push_back(L);
4216 Compound->setStmts(Context, &Elements[0], Elements.size());
4217 }
4218 FunctionLabelMap.clear();
4219
4220 if (!Body) return D;
4221
4222 CheckUnreachable(AC);
4223
4224 // Verify that that gotos and switch cases don't jump into scopes illegally.
4225 if (CurFunctionNeedsScopeChecking)
4226 DiagnoseInvalidJumps(Body);
4227
4228 // C++ constructors that have function-try-blocks can't have return
4229 // statements in the handlers of that block. (C++ [except.handle]p14)
4230 // Verify this.
4231 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
4232 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
4233
4234 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl))
4235 MarkBaseAndMemberDestructorsReferenced(Destructor);
4236
4237 // If any errors have occurred, clear out any temporaries that may have
4238 // been leftover. This ensures that these temporaries won't be picked up for
4239 // deletion in some later function.
4240 if (PP.getDiagnostics().hasErrorOccurred())
4241 ExprTemporaries.clear();
4242
4243 assert(ExprTemporaries.empty() && "Leftover temporaries in function");
4244 return D;
4245}
4246
4247/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4248/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4249NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
4250 IdentifierInfo &II, Scope *S) {
4251 // Before we produce a declaration for an implicitly defined
4252 // function, see whether there was a locally-scoped declaration of
4253 // this name as a function or variable. If so, use that
4254 // (non-visible) declaration, and complain about it.
4255 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4256 = LocallyScopedExternalDecls.find(&II);
4257 if (Pos != LocallyScopedExternalDecls.end()) {
4258 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
4259 Diag(Pos->second->getLocation(), diag::note_previous_declaration);
4260 return Pos->second;
4261 }
4262
4263 // Extension in C99. Legal in C90, but warn about it.
4264 if (II.getName().startswith("__builtin_"))
4265 Diag(Loc, diag::warn_builtin_unknown) << &II;
4266 else if (getLangOptions().C99)
4267 Diag(Loc, diag::ext_implicit_function_decl) << &II;
4268 else
4269 Diag(Loc, diag::warn_implicit_function_decl) << &II;
4270
4271 // Set a Declarator for the implicit definition: int foo();
4272 const char *Dummy;
4273 DeclSpec DS;
4274 unsigned DiagID;
4275 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
4276 Error = Error; // Silence warning.
4277 assert(!Error && "Error setting up implicit decl!");
4278 Declarator D(DS, Declarator::BlockContext);
4279 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
4280 0, 0, false, SourceLocation(),
4281 false, 0,0,0, Loc, Loc, D),
4282 SourceLocation());
4283 D.SetIdentifier(&II, Loc);
4284
4285 // Insert this function into translation-unit scope.
4286
4287 DeclContext *PrevDC = CurContext;
4288 CurContext = Context.getTranslationUnitDecl();
4289
4290 FunctionDecl *FD =
4291 dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D).getAs<Decl>());
4292 FD->setImplicit();
4293
4294 CurContext = PrevDC;
4295
4296 AddKnownFunctionAttributes(FD);
4297
4298 return FD;
4299}
4300
4301/// \brief Adds any function attributes that we know a priori based on
4302/// the declaration of this function.
4303///
4304/// These attributes can apply both to implicitly-declared builtins
4305/// (like __builtin___printf_chk) or to library-declared functions
4306/// like NSLog or printf.
4307void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
4308 if (FD->isInvalidDecl())
4309 return;
4310
4311 // If this is a built-in function, map its builtin attributes to
4312 // actual attributes.
4313 if (unsigned BuiltinID = FD->getBuiltinID()) {
4314 // Handle printf-formatting attributes.
4315 unsigned FormatIdx;
4316 bool HasVAListArg;
4317 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
4318 if (!FD->getAttr<FormatAttr>())
4319 FD->addAttr(::new (Context) FormatAttr("printf", FormatIdx + 1,
4320 HasVAListArg ? 0 : FormatIdx + 2));
4321 }
4322
4323 // Mark const if we don't care about errno and that is the only
4324 // thing preventing the function from being const. This allows
4325 // IRgen to use LLVM intrinsics for such functions.
4326 if (!getLangOptions().MathErrno &&
4327 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
4328 if (!FD->getAttr<ConstAttr>())
4329 FD->addAttr(::new (Context) ConstAttr());
4330 }
4331
4332 if (Context.BuiltinInfo.isNoReturn(BuiltinID))
4333 FD->setType(Context.getNoReturnType(FD->getType()));
4334 if (Context.BuiltinInfo.isNoThrow(BuiltinID))
4335 FD->addAttr(::new (Context) NoThrowAttr());
4336 if (Context.BuiltinInfo.isConst(BuiltinID))
4337 FD->addAttr(::new (Context) ConstAttr());
4338 }
4339
4340 IdentifierInfo *Name = FD->getIdentifier();
4341 if (!Name)
4342 return;
4343 if ((!getLangOptions().CPlusPlus &&
4344 FD->getDeclContext()->isTranslationUnit()) ||
4345 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
4346 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
4347 LinkageSpecDecl::lang_c)) {
4348 // Okay: this could be a libc/libm/Objective-C function we know
4349 // about.
4350 } else
4351 return;
4352
4353 if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
4354 // FIXME: NSLog and NSLogv should be target specific
4355 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
4356 // FIXME: We known better than our headers.
4357 const_cast<FormatAttr *>(Format)->setType("printf");
4358 } else
4359 FD->addAttr(::new (Context) FormatAttr("printf", 1,
4360 Name->isStr("NSLogv") ? 0 : 2));
4361 } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
4362 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
4363 // target-specific builtins, perhaps?
4364 if (!FD->getAttr<FormatAttr>())
4365 FD->addAttr(::new (Context) FormatAttr("printf", 2,
4366 Name->isStr("vasprintf") ? 0 : 3));
4367 }
4368}
4369
4370TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
4371 TypeSourceInfo *TInfo) {
4372 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
4373 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
4374
4375 if (!TInfo) {
4376 assert(D.isInvalidType() && "no declarator info for valid type");
4377 TInfo = Context.getTrivialTypeSourceInfo(T);
4378 }
4379
4380 // Scope manipulation handled by caller.
4381 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
4382 D.getIdentifierLoc(),
4383 D.getIdentifier(),
4384 TInfo);
4385
4386 if (const TagType *TT = T->getAs<TagType>()) {
4387 TagDecl *TD = TT->getDecl();
4388
4389 // If the TagDecl that the TypedefDecl points to is an anonymous decl
4390 // keep track of the TypedefDecl.
4391 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
4392 TD->setTypedefForAnonDecl(NewTD);
4393 }
4394
4395 if (D.isInvalidType())
4396 NewTD->setInvalidDecl();
4397 return NewTD;
4398}
4399
4400
4401/// \brief Determine whether a tag with a given kind is acceptable
4402/// as a redeclaration of the given tag declaration.
4403///
4404/// \returns true if the new tag kind is acceptable, false otherwise.
4405bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
4406 TagDecl::TagKind NewTag,
4407 SourceLocation NewTagLoc,
4408 const IdentifierInfo &Name) {
4409 // C++ [dcl.type.elab]p3:
4410 // The class-key or enum keyword present in the
4411 // elaborated-type-specifier shall agree in kind with the
4412 // declaration to which the name in theelaborated-type-specifier
4413 // refers. This rule also applies to the form of
4414 // elaborated-type-specifier that declares a class-name or
4415 // friend class since it can be construed as referring to the
4416 // definition of the class. Thus, in any
4417 // elaborated-type-specifier, the enum keyword shall be used to
4418 // refer to an enumeration (7.2), the union class-keyshall be
4419 // used to refer to a union (clause 9), and either the class or
4420 // struct class-key shall be used to refer to a class (clause 9)
4421 // declared using the class or struct class-key.
4422 TagDecl::TagKind OldTag = Previous->getTagKind();
4423 if (OldTag == NewTag)
4424 return true;
4425
4426 if ((OldTag == TagDecl::TK_struct || OldTag == TagDecl::TK_class) &&
4427 (NewTag == TagDecl::TK_struct || NewTag == TagDecl::TK_class)) {
4428 // Warn about the struct/class tag mismatch.
4429 bool isTemplate = false;
4430 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
4431 isTemplate = Record->getDescribedClassTemplate();
4432
4433 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
4434 << (NewTag == TagDecl::TK_class)
4435 << isTemplate << &Name
4436 << CodeModificationHint::CreateReplacement(SourceRange(NewTagLoc),
4437 OldTag == TagDecl::TK_class? "class" : "struct");
4438 Diag(Previous->getLocation(), diag::note_previous_use);
4439 return true;
4440 }
4441 return false;
4442}
4443
4444/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
4445/// former case, Name will be non-null. In the later case, Name will be null.
4446/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
4447/// reference/declaration/definition of a tag.
4448Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4449 SourceLocation KWLoc, const CXXScopeSpec &SS,
4450 IdentifierInfo *Name, SourceLocation NameLoc,
4451 AttributeList *Attr, AccessSpecifier AS,
4452 MultiTemplateParamsArg TemplateParameterLists,
4453 bool &OwnedDecl, bool &IsDependent) {
4454 // If this is not a definition, it must have a name.
4455 assert((Name != 0 || TUK == TUK_Definition) &&
4456 "Nameless record must be a definition!");
4457
4458 OwnedDecl = false;
4459 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
4460
4461 // FIXME: Check explicit specializations more carefully.
4462 bool isExplicitSpecialization = false;
4463 if (TUK != TUK_Reference) {
4464 if (TemplateParameterList *TemplateParams
4465 = MatchTemplateParametersToScopeSpecifier(KWLoc, SS,
4466 (TemplateParameterList**)TemplateParameterLists.get(),
4467 TemplateParameterLists.size(),
4468 isExplicitSpecialization)) {
4469 if (TemplateParams->size() > 0) {
4470 // This is a declaration or definition of a class template (which may
4471 // be a member of another template).
4472 OwnedDecl = false;
4473 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
4474 SS, Name, NameLoc, Attr,
4475 TemplateParams,
4476 AS);
4477 TemplateParameterLists.release();
4478 return Result.get();
4479 } else {
4480 // The "template<>" header is extraneous.
4481 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
4482 << ElaboratedType::getNameForTagKind(Kind) << Name;
4483 isExplicitSpecialization = true;
4484 }
4485 }
4486
4487 TemplateParameterLists.release();
4488 }
4489
4490 DeclContext *SearchDC = CurContext;
4491 DeclContext *DC = CurContext;
4492 bool isStdBadAlloc = false;
4493 bool Invalid = false;
4494
4495 RedeclarationKind Redecl = (TUK != TUK_Reference ? ForRedeclaration
4496 : NotForRedeclaration);
4497
4498 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
4499
4500 if (Name && SS.isNotEmpty()) {
4501 // We have a nested-name tag ('struct foo::bar').
4502
4503 // Check for invalid 'foo::'.
4504 if (SS.isInvalid()) {
4505 Name = 0;
4506 goto CreateNewDecl;
4507 }
4508
4509 // If this is a friend or a reference to a class in a dependent
4510 // context, don't try to make a decl for it.
4511 if (TUK == TUK_Friend || TUK == TUK_Reference) {
4512 DC = computeDeclContext(SS, false);
4513 if (!DC) {
4514 IsDependent = true;
4515 return DeclPtrTy();
4516 }
4517 }
4518
4519 if (RequireCompleteDeclContext(SS))
4520 return DeclPtrTy::make((Decl *)0);
4521
4522 DC = computeDeclContext(SS, true);
4523 SearchDC = DC;
4524 // Look-up name inside 'foo::'.
4525 LookupQualifiedName(Previous, DC);
4526
4527 if (Previous.isAmbiguous())
4528 return DeclPtrTy();
4529
4530 if (Previous.empty()) {
4531 // Name lookup did not find anything. However, if the
4532 // nested-name-specifier refers to the current instantiation,
4533 // and that current instantiation has any dependent base
4534 // classes, we might find something at instantiation time: treat
4535 // this as a dependent elaborated-type-specifier.
4536 if (Previous.wasNotFoundInCurrentInstantiation()) {
4537 IsDependent = true;
4538 return DeclPtrTy();
4539 }
4540
4541 // A tag 'foo::bar' must already exist.
4542 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
4543 Name = 0;
4544 Invalid = true;
4545 goto CreateNewDecl;
4546 }
4547 } else if (Name) {
4548 // If this is a named struct, check to see if there was a previous forward
4549 // declaration or definition.
4550 // FIXME: We're looking into outer scopes here, even when we
4551 // shouldn't be. Doing so can result in ambiguities that we
4552 // shouldn't be diagnosing.
4553 LookupName(Previous, S);
4554
4555 // Note: there used to be some attempt at recovery here.
4556 if (Previous.isAmbiguous())
4557 return DeclPtrTy();
4558
4559 if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
4560 // FIXME: This makes sure that we ignore the contexts associated
4561 // with C structs, unions, and enums when looking for a matching
4562 // tag declaration or definition. See the similar lookup tweak
4563 // in Sema::LookupName; is there a better way to deal with this?
4564 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
4565 SearchDC = SearchDC->getParent();
4566 }
4567 }
4568
4569 if (Previous.isSingleResult() &&
4570 Previous.getFoundDecl()->isTemplateParameter()) {
4571 // Maybe we will complain about the shadowed template parameter.
4572 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
4573 // Just pretend that we didn't see the previous declaration.
4574 Previous.clear();
4575 }
4576
4577 if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
4578 DC->Equals(StdNamespace) && Name->isStr("bad_alloc")) {
4579 // This is a declaration of or a reference to "std::bad_alloc".
4580 isStdBadAlloc = true;
4581
4582 if (Previous.empty() && StdBadAlloc) {
4583 // std::bad_alloc has been implicitly declared (but made invisible to
4584 // name lookup). Fill in this implicit declaration as the previous
4585 // declaration, so that the declarations get chained appropriately.
4586 Previous.addDecl(StdBadAlloc);
4587 }
4588 }
4589
4590 if (!Previous.empty()) {
4591 assert(Previous.isSingleResult());
4592 NamedDecl *PrevDecl = Previous.getFoundDecl();
4593 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
4594 // If this is a use of a previous tag, or if the tag is already declared
4595 // in the same scope (so that the definition/declaration completes or
4596 // rementions the tag), reuse the decl.
4597 if (TUK == TUK_Reference || TUK == TUK_Friend ||
4598 isDeclInScope(PrevDecl, SearchDC, S)) {
4599 // Make sure that this wasn't declared as an enum and now used as a
4600 // struct or something similar.
4601 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) {
4602 bool SafeToContinue
4603 = (PrevTagDecl->getTagKind() != TagDecl::TK_enum &&
4604 Kind != TagDecl::TK_enum);
4605 if (SafeToContinue)
4606 Diag(KWLoc, diag::err_use_with_wrong_tag)
4607 << Name
4608 << CodeModificationHint::CreateReplacement(SourceRange(KWLoc),
4609 PrevTagDecl->getKindName());
4610 else
4611 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
4612 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
4613
4614 if (SafeToContinue)
4615 Kind = PrevTagDecl->getTagKind();
4616 else {
4617 // Recover by making this an anonymous redefinition.
4618 Name = 0;
4619 Previous.clear();
4620 Invalid = true;
4621 }
4622 }
4623
4624 if (!Invalid) {
4625 // If this is a use, just return the declaration we found.
4626
4627 // FIXME: In the future, return a variant or some other clue
4628 // for the consumer of this Decl to know it doesn't own it.
4629 // For our current ASTs this shouldn't be a problem, but will
4630 // need to be changed with DeclGroups.
4631 if (TUK == TUK_Reference || TUK == TUK_Friend)
4632 return DeclPtrTy::make(PrevTagDecl);
4633
4634 // Diagnose attempts to redefine a tag.
4635 if (TUK == TUK_Definition) {
4636 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
4637 // If we're defining a specialization and the previous definition
4638 // is from an implicit instantiation, don't emit an error
4639 // here; we'll catch this in the general case below.
4640 if (!isExplicitSpecialization ||
4641 !isa<CXXRecordDecl>(Def) ||
4642 cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
4643 == TSK_ExplicitSpecialization) {
4644 Diag(NameLoc, diag::err_redefinition) << Name;
4645 Diag(Def->getLocation(), diag::note_previous_definition);
4646 // If this is a redefinition, recover by making this
4647 // struct be anonymous, which will make any later
4648 // references get the previous definition.
4649 Name = 0;
4650 Previous.clear();
4651 Invalid = true;
4652 }
4653 } else {
4654 // If the type is currently being defined, complain
4655 // about a nested redefinition.
4656 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
4657 if (Tag->isBeingDefined()) {
4658 Diag(NameLoc, diag::err_nested_redefinition) << Name;
4659 Diag(PrevTagDecl->getLocation(),
4660 diag::note_previous_definition);
4661 Name = 0;
4662 Previous.clear();
4663 Invalid = true;
4664 }
4665 }
4666
4667 // Okay, this is definition of a previously declared or referenced
4668 // tag PrevDecl. We're going to create a new Decl for it.
4669 }
4670 }
4671 // If we get here we have (another) forward declaration or we
4672 // have a definition. Just create a new decl.
4673
4674 } else {
4675 // If we get here, this is a definition of a new tag type in a nested
4676 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
4677 // new decl/type. We set PrevDecl to NULL so that the entities
4678 // have distinct types.
4679 Previous.clear();
4680 }
4681 // If we get here, we're going to create a new Decl. If PrevDecl
4682 // is non-NULL, it's a definition of the tag declared by
4683 // PrevDecl. If it's NULL, we have a new definition.
4684 } else {
4685 // PrevDecl is a namespace, template, or anything else
4686 // that lives in the IDNS_Tag identifier namespace.
4687 if (isDeclInScope(PrevDecl, SearchDC, S)) {
4688 // The tag name clashes with a namespace name, issue an error and
4689 // recover by making this tag be anonymous.
4690 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
4691 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4692 Name = 0;
4693 Previous.clear();
4694 Invalid = true;
4695 } else {
4696 // The existing declaration isn't relevant to us; we're in a
4697 // new scope, so clear out the previous declaration.
4698 Previous.clear();
4699 }
4700 }
4701 } else if (TUK == TUK_Reference && SS.isEmpty() && Name) {
4702 // C++ [basic.scope.pdecl]p5:
4703 // -- for an elaborated-type-specifier of the form
4704 //
4705 // class-key identifier
4706 //
4707 // if the elaborated-type-specifier is used in the
4708 // decl-specifier-seq or parameter-declaration-clause of a
4709 // function defined in namespace scope, the identifier is
4710 // declared as a class-name in the namespace that contains
4711 // the declaration; otherwise, except as a friend
4712 // declaration, the identifier is declared in the smallest
4713 // non-class, non-function-prototype scope that contains the
4714 // declaration.
4715 //
4716 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
4717 // C structs and unions.
4718 //
4719 // It is an error in C++ to declare (rather than define) an enum
4720 // type, including via an elaborated type specifier. We'll
4721 // diagnose that later; for now, declare the enum in the same
4722 // scope as we would have picked for any other tag type.
4723 //
4724 // GNU C also supports this behavior as part of its incomplete
4725 // enum types extension, while GNU C++ does not.
4726 //
4727 // Find the context where we'll be declaring the tag.
4728 // FIXME: We would like to maintain the current DeclContext as the
4729 // lexical context,
4730 while (SearchDC->isRecord())
4731 SearchDC = SearchDC->getParent();
4732
4733 // Find the scope where we'll be declaring the tag.
4734 while (S->isClassScope() ||
4735 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
4736 ((S->getFlags() & Scope::DeclScope) == 0) ||
4737 (S->getEntity() &&
4738 ((DeclContext *)S->getEntity())->isTransparentContext()))
4739 S = S->getParent();
4740
4741 } else if (TUK == TUK_Friend && SS.isEmpty() && Name) {
4742 // C++ [namespace.memdef]p3:
4743 // If a friend declaration in a non-local class first declares a
4744 // class or function, the friend class or function is a member of
4745 // the innermost enclosing namespace.
4746 while (!SearchDC->isFileContext())
4747 SearchDC = SearchDC->getParent();
4748
4749 // The entity of a decl scope is a DeclContext; see PushDeclContext.
4750 while (S->getEntity() != SearchDC)
4751 S = S->getParent();
4752 }
4753
4754CreateNewDecl:
4755
4756 TagDecl *PrevDecl = 0;
4757 if (Previous.isSingleResult())
4758 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
4759
4760 // If there is an identifier, use the location of the identifier as the
4761 // location of the decl, otherwise use the location of the struct/union
4762 // keyword.
4763 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
4764
4765 // Otherwise, create a new declaration. If there is a previous
4766 // declaration of the same entity, the two will be linked via
4767 // PrevDecl.
4768 TagDecl *New;
4769
4770 if (Kind == TagDecl::TK_enum) {
4771 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
4772 // enum X { A, B, C } D; D should chain to X.
4773 New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc,
4774 cast_or_null<EnumDecl>(PrevDecl));
4775 // If this is an undefined enum, warn.
4776 if (TUK != TUK_Definition && !Invalid) {
4777 unsigned DK = getLangOptions().CPlusPlus? diag::err_forward_ref_enum
4778 : diag::ext_forward_ref_enum;
4779 Diag(Loc, DK);
4780 }
4781 } else {
4782 // struct/union/class
4783
4784 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
4785 // struct X { int A; } D; D should chain to X.
4786 if (getLangOptions().CPlusPlus) {
4787 // FIXME: Look for a way to use RecordDecl for simple structs.
4788 New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
4789 cast_or_null<CXXRecordDecl>(PrevDecl));
4790
4791 if (isStdBadAlloc && (!StdBadAlloc || StdBadAlloc->isImplicit()))
4792 StdBadAlloc = cast<CXXRecordDecl>(New);
4793 } else
4794 New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
4795 cast_or_null<RecordDecl>(PrevDecl));
4796 }
4797
4798 if (Kind != TagDecl::TK_enum) {
4799 // Handle #pragma pack: if the #pragma pack stack has non-default
4800 // alignment, make up a packed attribute for this decl. These
4801 // attributes are checked when the ASTContext lays out the
4802 // structure.
4803 //
4804 // It is important for implementing the correct semantics that this
4805 // happen here (in act on tag decl). The #pragma pack stack is
4806 // maintained as a result of parser callbacks which can occur at
4807 // many points during the parsing of a struct declaration (because
4808 // the #pragma tokens are effectively skipped over during the
4809 // parsing of the struct).
4810 if (unsigned Alignment = getPragmaPackAlignment())
4811 New->addAttr(::new (Context) PragmaPackAttr(Alignment * 8));
4812 }
4813
4814 if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
4815 // C++ [dcl.typedef]p3:
4816 // [...] Similarly, in a given scope, a class or enumeration
4817 // shall not be declared with the same name as a typedef-name
4818 // that is declared in that scope and refers to a type other
4819 // than the class or enumeration itself.
4820 LookupResult Lookup(*this, Name, NameLoc, LookupOrdinaryName,
4821 ForRedeclaration);
4822 LookupName(Lookup, S);
4823 TypedefDecl *PrevTypedef = Lookup.getAsSingle<TypedefDecl>();
4824 NamedDecl *PrevTypedefNamed = PrevTypedef;
4825 if (PrevTypedef && isDeclInScope(PrevTypedefNamed, SearchDC, S) &&
4826 Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
4827 Context.getCanonicalType(Context.getTypeDeclType(New))) {
4828 Diag(Loc, diag::err_tag_definition_of_typedef)
4829 << Context.getTypeDeclType(New)
4830 << PrevTypedef->getUnderlyingType();
4831 Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
4832 Invalid = true;
4833 }
4834 }
4835
4836 // If this is a specialization of a member class (of a class template),
4837 // check the specialization.
4838 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
4839 Invalid = true;
4840
4841 if (Invalid)
4842 New->setInvalidDecl();
4843
4844 if (Attr)
4845 ProcessDeclAttributeList(S, New, Attr);
4846
4847 // If we're declaring or defining a tag in function prototype scope
4848 // in C, note that this type can only be used within the function.
4849 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
4850 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
4851
4852 // Set the lexical context. If the tag has a C++ scope specifier, the
4853 // lexical context will be different from the semantic context.
4854 New->setLexicalDeclContext(CurContext);
4855
4856 // Mark this as a friend decl if applicable.
4857 if (TUK == TUK_Friend)
4858 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty());
4859
4860 // Set the access specifier.
4861 if (!Invalid && TUK != TUK_Friend)
4862 SetMemberAccessSpecifier(New, PrevDecl, AS);
4863
4864 if (TUK == TUK_Definition)
4865 New->startDefinition();
4866
4867 // If this has an identifier, add it to the scope stack.
4868 if (TUK == TUK_Friend) {
4869 // We might be replacing an existing declaration in the lookup tables;
4870 // if so, borrow its access specifier.
4871 if (PrevDecl)
4872 New->setAccess(PrevDecl->getAccess());
4873
4874 // Friend tag decls are visible in fairly strange ways.
4875 if (!CurContext->isDependentContext()) {
4876 DeclContext *DC = New->getDeclContext()->getLookupContext();
4877 DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
4878 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
4879 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
4880 }
4881 } else if (Name) {
4882 S = getNonFieldDeclScope(S);
4883 PushOnScopeChains(New, S);
4884 } else {
4885 CurContext->addDecl(New);
4886 }
4887
4888 // If this is the C FILE type, notify the AST context.
4889 if (IdentifierInfo *II = New->getIdentifier())
4890 if (!New->isInvalidDecl() &&
4891 New->getDeclContext()->getLookupContext()->isTranslationUnit() &&
4892 II->isStr("FILE"))
4893 Context.setFILEDecl(New);
4894
4895 OwnedDecl = true;
4896 return DeclPtrTy::make(New);
4897}
4898
4899void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) {
4900 AdjustDeclIfTemplate(TagD);
4901 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4902
4903 // Enter the tag context.
4904 PushDeclContext(S, Tag);
4905}
4906
4907void Sema::ActOnStartCXXMemberDeclarations(Scope *S, DeclPtrTy TagD,
4908 SourceLocation LBraceLoc) {
4909 AdjustDeclIfTemplate(TagD);
4910 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD.getAs<Decl>());
4911
4912 FieldCollector->StartClass();
4913
4914 if (!Record->getIdentifier())
4915 return;
4916
4917 // C++ [class]p2:
4918 // [...] The class-name is also inserted into the scope of the
4919 // class itself; this is known as the injected-class-name. For
4920 // purposes of access checking, the injected-class-name is treated
4921 // as if it were a public member name.
4922 CXXRecordDecl *InjectedClassName
4923 = CXXRecordDecl::Create(Context, Record->getTagKind(),
4924 CurContext, Record->getLocation(),
4925 Record->getIdentifier(),
4926 Record->getTagKeywordLoc(),
4927 Record);
4928 InjectedClassName->setImplicit();
4929 InjectedClassName->setAccess(AS_public);
4930 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
4931 InjectedClassName->setDescribedClassTemplate(Template);
4932 PushOnScopeChains(InjectedClassName, S);
4933 assert(InjectedClassName->isInjectedClassName() &&
4934 "Broken injected-class-name");
4935}
4936
4937// Traverses the class and any nested classes, making a note of any
4938// dynamic classes that have no key function so that we can mark all of
4939// their virtual member functions as "used" at the end of the translation
4940// unit. This ensures that all functions needed by the vtable will get
4941// instantiated/synthesized.
4942static void
4943RecordDynamicClassesWithNoKeyFunction(Sema &S, CXXRecordDecl *Record,
4944 SourceLocation Loc) {
4945 // We don't look at dependent or undefined classes.
4946 if (Record->isDependentContext() || !Record->isDefinition())
4947 return;
4948
4949 if (Record->isDynamicClass()) {
4950 const CXXMethodDecl *KeyFunction = S.Context.getKeyFunction(Record);
4951
4952 if (!KeyFunction)
4953 S.ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(Record,
4954 Loc));
4955
4956 if ((!KeyFunction || (KeyFunction->getBody() && KeyFunction->isInlined()))
4957 && Record->getLinkage() == ExternalLinkage)
4958 S.Diag(Record->getLocation(), diag::warn_weak_vtable) << Record;
4959 }
4960 for (DeclContext::decl_iterator D = Record->decls_begin(),
4961 DEnd = Record->decls_end();
4962 D != DEnd; ++D) {
4963 if (CXXRecordDecl *Nested = dyn_cast<CXXRecordDecl>(*D))
4964 RecordDynamicClassesWithNoKeyFunction(S, Nested, Loc);
4965 }
4966}
4967
4968void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD,
4969 SourceLocation RBraceLoc) {
4970 AdjustDeclIfTemplate(TagD);
4971 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4972 Tag->setRBraceLoc(RBraceLoc);
4973
4974 if (isa<CXXRecordDecl>(Tag))
4975 FieldCollector->FinishClass();
4976
4977 // Exit this scope of this tag's definition.
4978 PopDeclContext();
4979
4980 if (isa<CXXRecordDecl>(Tag) && !Tag->getDeclContext()->isRecord())
4981 RecordDynamicClassesWithNoKeyFunction(*this, cast<CXXRecordDecl>(Tag),
4982 RBraceLoc);
4983
4984 // Notify the consumer that we've defined a tag.
4985 Consumer.HandleTagDeclDefinition(Tag);
4986}
4987
4988// Note that FieldName may be null for anonymous bitfields.
4989bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
4990 QualType FieldTy, const Expr *BitWidth,
4991 bool *ZeroWidth) {
4992 // Default to true; that shouldn't confuse checks for emptiness
4993 if (ZeroWidth)
4994 *ZeroWidth = true;
4995
4996 // C99 6.7.2.1p4 - verify the field type.
4997 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
4998 if (!FieldTy->isDependentType() && !FieldTy->isIntegralType()) {
4999 // Handle incomplete types with specific error.
5000 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
5001 return true;
5002 if (FieldName)
5003 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
5004 << FieldName << FieldTy << BitWidth->getSourceRange();
5005 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
5006 << FieldTy << BitWidth->getSourceRange();
5007 }
5008
5009 // If the bit-width is type- or value-dependent, don't try to check
5010 // it now.
5011 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
5012 return false;
5013
5014 llvm::APSInt Value;
5015 if (VerifyIntegerConstantExpression(BitWidth, &Value))
5016 return true;
5017
5018 if (Value != 0 && ZeroWidth)
5019 *ZeroWidth = false;
5020
5021 // Zero-width bitfield is ok for anonymous field.
5022 if (Value == 0 && FieldName)
5023 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
5024
5025 if (Value.isSigned() && Value.isNegative()) {
5026 if (FieldName)
5027 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
5028 << FieldName << Value.toString(10);
5029 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
5030 << Value.toString(10);
5031 }
5032
5033 if (!FieldTy->isDependentType()) {
5034 uint64_t TypeSize = Context.getTypeSize(FieldTy);
5035 if (Value.getZExtValue() > TypeSize) {
5036 if (FieldName)
5037 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
5038 << FieldName << (unsigned)TypeSize;
5039 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
5040 << (unsigned)TypeSize;
5041 }
5042 }
5043
5044 return false;
5045}
5046
5047/// ActOnField - Each field of a struct/union/class is passed into this in order
5048/// to create a FieldDecl object for it.
5049Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD,
5050 SourceLocation DeclStart,
5051 Declarator &D, ExprTy *BitfieldWidth) {
5052 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()),
5053 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
5054 AS_public);
5055 return DeclPtrTy::make(Res);
5056}
5057
5058/// HandleField - Analyze a field of a C struct or a C++ data member.
5059///
5060FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
5061 SourceLocation DeclStart,
5062 Declarator &D, Expr *BitWidth,
5063 AccessSpecifier AS) {
5064 IdentifierInfo *II = D.getIdentifier();
5065 SourceLocation Loc = DeclStart;
5066 if (II) Loc = D.getIdentifierLoc();
5067
5068 TypeSourceInfo *TInfo = 0;
5069 QualType T = GetTypeForDeclarator(D, S, &TInfo);
5070 if (getLangOptions().CPlusPlus)
5071 CheckExtraCXXDefaultArguments(D);
5072
5073 DiagnoseFunctionSpecifiers(D);
5074
5075 if (D.getDeclSpec().isThreadSpecified())
5076 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
5077
5078 NamedDecl *PrevDecl = LookupSingleName(S, II, LookupMemberName,
5079 ForRedeclaration);
5080
5081 if (PrevDecl && PrevDecl->isTemplateParameter()) {
5082 // Maybe we will complain about the shadowed template parameter.
5083 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5084 // Just pretend that we didn't see the previous declaration.
5085 PrevDecl = 0;
5086 }
5087
5088 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
5089 PrevDecl = 0;
5090
5091 bool Mutable
5092 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
5093 SourceLocation TSSL = D.getSourceRange().getBegin();
5094 FieldDecl *NewFD
5095 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, TSSL,
5096 AS, PrevDecl, &D);
5097 if (NewFD->isInvalidDecl() && PrevDecl) {
5098 // Don't introduce NewFD into scope; there's already something
5099 // with the same name in the same scope.
5100 } else if (II) {
5101 PushOnScopeChains(NewFD, S);
5102 } else
5103 Record->addDecl(NewFD);
5104
5105 return NewFD;
5106}
5107
5108/// \brief Build a new FieldDecl and check its well-formedness.
5109///
5110/// This routine builds a new FieldDecl given the fields name, type,
5111/// record, etc. \p PrevDecl should refer to any previous declaration
5112/// with the same name and in the same scope as the field to be
5113/// created.
5114///
5115/// \returns a new FieldDecl.
5116///
5117/// \todo The Declarator argument is a hack. It will be removed once
5118FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
5119 TypeSourceInfo *TInfo,
5120 RecordDecl *Record, SourceLocation Loc,
5121 bool Mutable, Expr *BitWidth,
5122 SourceLocation TSSL,
5123 AccessSpecifier AS, NamedDecl *PrevDecl,
5124 Declarator *D) {
5125 IdentifierInfo *II = Name.getAsIdentifierInfo();
5126 bool InvalidDecl = false;
5127 if (D) InvalidDecl = D->isInvalidType();
5128
5129 // If we receive a broken type, recover by assuming 'int' and
5130 // marking this declaration as invalid.
5131 if (T.isNull()) {
5132 InvalidDecl = true;
5133 T = Context.IntTy;
5134 }
5135
5136 QualType EltTy = Context.getBaseElementType(T);
5137 if (!EltTy->isDependentType() &&
5138 RequireCompleteType(Loc, EltTy, diag::err_field_incomplete))
5139 InvalidDecl = true;
5140
5141 // C99 6.7.2.1p8: A member of a structure or union may have any type other
5142 // than a variably modified type.
5143 if (!InvalidDecl && T->isVariablyModifiedType()) {
5144 bool SizeIsNegative;
5145 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
5146 SizeIsNegative);
5147 if (!FixedTy.isNull()) {
5148 Diag(Loc, diag::warn_illegal_constant_array_size);
5149 T = FixedTy;
5150 } else {
5151 if (SizeIsNegative)
5152 Diag(Loc, diag::err_typecheck_negative_array_size);
5153 else
5154 Diag(Loc, diag::err_typecheck_field_variable_size);
5155 InvalidDecl = true;
5156 }
5157 }
5158
5159 // Fields can not have abstract class types
5160 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
5161 diag::err_abstract_type_in_decl,
5162 AbstractFieldType))
5163 InvalidDecl = true;
5164
5165 bool ZeroWidth = false;
5166 // If this is declared as a bit-field, check the bit-field.
5167 if (!InvalidDecl && BitWidth &&
5168 VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
5169 InvalidDecl = true;
5170 DeleteExpr(BitWidth);
5171 BitWidth = 0;
5172 ZeroWidth = false;
5173 }
5174
5175 FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, TInfo,
5176 BitWidth, Mutable);
5177 if (InvalidDecl)
5178 NewFD->setInvalidDecl();
5179
5180 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
5181 Diag(Loc, diag::err_duplicate_member) << II;
5182 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5183 NewFD->setInvalidDecl();
5184 }
5185
5186 if (!InvalidDecl && getLangOptions().CPlusPlus) {
5187 CXXRecordDecl* CXXRecord = cast<CXXRecordDecl>(Record);
5188
5189 if (!T->isPODType())
5190 CXXRecord->setPOD(false);
5191 if (!ZeroWidth)
5192 CXXRecord->setEmpty(false);
5193
5194 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
5195 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
5196
5197 if (!RDecl->hasTrivialConstructor())
5198 CXXRecord->setHasTrivialConstructor(false);
5199 if (!RDecl->hasTrivialCopyConstructor())
5200 CXXRecord->setHasTrivialCopyConstructor(false);
5201 if (!RDecl->hasTrivialCopyAssignment())
5202 CXXRecord->setHasTrivialCopyAssignment(false);
5203 if (!RDecl->hasTrivialDestructor())
5204 CXXRecord->setHasTrivialDestructor(false);
5205
5206 // C++ 9.5p1: An object of a class with a non-trivial
5207 // constructor, a non-trivial copy constructor, a non-trivial
5208 // destructor, or a non-trivial copy assignment operator
5209 // cannot be a member of a union, nor can an array of such
5210 // objects.
5211 // TODO: C++0x alters this restriction significantly.
5212 if (Record->isUnion()) {
5213 // We check for copy constructors before constructors
5214 // because otherwise we'll never get complaints about
5215 // copy constructors.
5216
5217 const CXXSpecialMember invalid = (CXXSpecialMember) -1;
5218
5219 CXXSpecialMember member;
5220 if (!RDecl->hasTrivialCopyConstructor())
5221 member = CXXCopyConstructor;
5222 else if (!RDecl->hasTrivialConstructor())
5223 member = CXXDefaultConstructor;
5224 else if (!RDecl->hasTrivialCopyAssignment())
5225 member = CXXCopyAssignment;
5226 else if (!RDecl->hasTrivialDestructor())
5227 member = CXXDestructor;
5228 else
5229 member = invalid;
5230
5231 if (member != invalid) {
5232 Diag(Loc, diag::err_illegal_union_member) << Name << member;
5233 DiagnoseNontrivial(RT, member);
5234 NewFD->setInvalidDecl();
5235 }
5236 }
5237 }
5238 }
5239
5240 // FIXME: We need to pass in the attributes given an AST
5241 // representation, not a parser representation.
5242 if (D)
5243 // FIXME: What to pass instead of TUScope?
5244 ProcessDeclAttributes(TUScope, NewFD, *D);
5245
5246 if (T.isObjCGCWeak())
5247 Diag(Loc, diag::warn_attribute_weak_on_field);
5248
5249 NewFD->setAccess(AS);
5250
5251 // C++ [dcl.init.aggr]p1:
5252 // An aggregate is an array or a class (clause 9) with [...] no
5253 // private or protected non-static data members (clause 11).
5254 // A POD must be an aggregate.
5255 if (getLangOptions().CPlusPlus &&
5256 (AS == AS_private || AS == AS_protected)) {
5257 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
5258 CXXRecord->setAggregate(false);
5259 CXXRecord->setPOD(false);
5260 }
5261
5262 return NewFD;
5263}
5264
5265/// DiagnoseNontrivial - Given that a class has a non-trivial
5266/// special member, figure out why.
5267void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
5268 QualType QT(T, 0U);
5269 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
5270
5271 // Check whether the member was user-declared.
5272 switch (member) {
5273 case CXXDefaultConstructor:
5274 if (RD->hasUserDeclaredConstructor()) {
5275 typedef CXXRecordDecl::ctor_iterator ctor_iter;
5276 for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
5277 const FunctionDecl *body = 0;
5278 ci->getBody(body);
5279 if (!body ||
5280 !cast<CXXConstructorDecl>(body)->isImplicitlyDefined(Context)) {
5281 SourceLocation CtorLoc = ci->getLocation();
5282 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5283 return;
5284 }
5285 }
5286
5287 assert(0 && "found no user-declared constructors");
5288 return;
5289 }
5290 break;
5291
5292 case CXXCopyConstructor:
5293 if (RD->hasUserDeclaredCopyConstructor()) {
5294 SourceLocation CtorLoc =
5295 RD->getCopyConstructor(Context, 0)->getLocation();
5296 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5297 return;
5298 }
5299 break;
5300
5301 case CXXCopyAssignment:
5302 if (RD->hasUserDeclaredCopyAssignment()) {
5303 // FIXME: this should use the location of the copy
5304 // assignment, not the type.
5305 SourceLocation TyLoc = RD->getSourceRange().getBegin();
5306 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
5307 return;
5308 }
5309 break;
5310
5311 case CXXDestructor:
5312 if (RD->hasUserDeclaredDestructor()) {
5313 SourceLocation DtorLoc = RD->getDestructor(Context)->getLocation();
5314 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5315 return;
5316 }
5317 break;
5318 }
5319
5320 typedef CXXRecordDecl::base_class_iterator base_iter;
5321
5322 // Virtual bases and members inhibit trivial copying/construction,
5323 // but not trivial destruction.
5324 if (member != CXXDestructor) {
5325 // Check for virtual bases. vbases includes indirect virtual bases,
5326 // so we just iterate through the direct bases.
5327 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
5328 if (bi->isVirtual()) {
5329 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5330 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
5331 return;
5332 }
5333
5334 // Check for virtual methods.
5335 typedef CXXRecordDecl::method_iterator meth_iter;
5336 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
5337 ++mi) {
5338 if (mi->isVirtual()) {
5339 SourceLocation MLoc = mi->getSourceRange().getBegin();
5340 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
5341 return;
5342 }
5343 }
5344 }
5345
5346 bool (CXXRecordDecl::*hasTrivial)() const;
5347 switch (member) {
5348 case CXXDefaultConstructor:
5349 hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break;
5350 case CXXCopyConstructor:
5351 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
5352 case CXXCopyAssignment:
5353 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
5354 case CXXDestructor:
5355 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
5356 default:
5357 assert(0 && "unexpected special member"); return;
5358 }
5359
5360 // Check for nontrivial bases (and recurse).
5361 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
5362 const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
5363 assert(BaseRT && "Don't know how to handle dependent bases");
5364 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
5365 if (!(BaseRecTy->*hasTrivial)()) {
5366 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5367 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
5368 DiagnoseNontrivial(BaseRT, member);
5369 return;
5370 }
5371 }
5372
5373 // Check for nontrivial members (and recurse).
5374 typedef RecordDecl::field_iterator field_iter;
5375 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
5376 ++fi) {
5377 QualType EltTy = Context.getBaseElementType((*fi)->getType());
5378 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
5379 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
5380
5381 if (!(EltRD->*hasTrivial)()) {
5382 SourceLocation FLoc = (*fi)->getLocation();
5383 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
5384 DiagnoseNontrivial(EltRT, member);
5385 return;
5386 }
5387 }
5388 }
5389
5390 assert(0 && "found no explanation for non-trivial member");
5391}
5392
5393/// TranslateIvarVisibility - Translate visibility from a token ID to an
5394/// AST enum value.
5395static ObjCIvarDecl::AccessControl
5396TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
5397 switch (ivarVisibility) {
5398 default: assert(0 && "Unknown visitibility kind");
5399 case tok::objc_private: return ObjCIvarDecl::Private;
5400 case tok::objc_public: return ObjCIvarDecl::Public;
5401 case tok::objc_protected: return ObjCIvarDecl::Protected;
5402 case tok::objc_package: return ObjCIvarDecl::Package;
5403 }
5404}
5405
5406/// ActOnIvar - Each ivar field of an objective-c class is passed into this
5407/// in order to create an IvarDecl object for it.
5408Sema::DeclPtrTy Sema::ActOnIvar(Scope *S,
5409 SourceLocation DeclStart,
5410 DeclPtrTy IntfDecl,
5411 Declarator &D, ExprTy *BitfieldWidth,
5412 tok::ObjCKeywordKind Visibility) {
5413
5414 IdentifierInfo *II = D.getIdentifier();
5415 Expr *BitWidth = (Expr*)BitfieldWidth;
5416 SourceLocation Loc = DeclStart;
5417 if (II) Loc = D.getIdentifierLoc();
5418
5419 // FIXME: Unnamed fields can be handled in various different ways, for
5420 // example, unnamed unions inject all members into the struct namespace!
5421
5422 TypeSourceInfo *TInfo = 0;
5423 QualType T = GetTypeForDeclarator(D, S, &TInfo);
5424
5425 if (BitWidth) {
5426 // 6.7.2.1p3, 6.7.2.1p4
5427 if (VerifyBitField(Loc, II, T, BitWidth)) {
5428 D.setInvalidType();
5429 DeleteExpr(BitWidth);
5430 BitWidth = 0;
5431 }
5432 } else {
5433 // Not a bitfield.
5434
5435 // validate II.
5436
5437 }
5438
5439 // C99 6.7.2.1p8: A member of a structure or union may have any type other
5440 // than a variably modified type.
5441 if (T->isVariablyModifiedType()) {
5442 Diag(Loc, diag::err_typecheck_ivar_variable_size);
5443 D.setInvalidType();
5444 }
5445
5446 // Get the visibility (access control) for this ivar.
5447 ObjCIvarDecl::AccessControl ac =
5448 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
5449 : ObjCIvarDecl::None;
5450 // Must set ivar's DeclContext to its enclosing interface.
5451 Decl *EnclosingDecl = IntfDecl.getAs<Decl>();
5452 DeclContext *EnclosingContext;
5453 if (ObjCImplementationDecl *IMPDecl =
5454 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
5455 // Case of ivar declared in an implementation. Context is that of its class.
5456 ObjCInterfaceDecl* IDecl = IMPDecl->getClassInterface();
5457 assert(IDecl && "No class- ActOnIvar");
5458 EnclosingContext = cast_or_null<DeclContext>(IDecl);
5459 } else
5460 EnclosingContext = dyn_cast<DeclContext>(EnclosingDecl);
5461 assert(EnclosingContext && "null DeclContext for ivar - ActOnIvar");
5462
5463 // Construct the decl.
5464 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context,
5465 EnclosingContext, Loc, II, T,
5466 TInfo, ac, (Expr *)BitfieldWidth);
5467
5468 if (II) {
5469 NamedDecl *PrevDecl = LookupSingleName(S, II, LookupMemberName,
5470 ForRedeclaration);
5471 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
5472 && !isa<TagDecl>(PrevDecl)) {
5473 Diag(Loc, diag::err_duplicate_member) << II;
5474 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5475 NewID->setInvalidDecl();
5476 }
5477 }
5478
5479 // Process attributes attached to the ivar.
5480 ProcessDeclAttributes(S, NewID, D);
5481
5482 if (D.isInvalidType())
5483 NewID->setInvalidDecl();
5484
5485 if (II) {
5486 // FIXME: When interfaces are DeclContexts, we'll need to add
5487 // these to the interface.
5488 S->AddDecl(DeclPtrTy::make(NewID));
5489 IdResolver.AddDecl(NewID);
5490 }
5491
5492 return DeclPtrTy::make(NewID);
5493}
5494
5495void Sema::ActOnFields(Scope* S,
5496 SourceLocation RecLoc, DeclPtrTy RecDecl,
5497 DeclPtrTy *Fields, unsigned NumFields,
5498 SourceLocation LBrac, SourceLocation RBrac,
5499 AttributeList *Attr) {
5500 Decl *EnclosingDecl = RecDecl.getAs<Decl>();
5501 assert(EnclosingDecl && "missing record or interface decl");
5502
5503 // If the decl this is being inserted into is invalid, then it may be a
5504 // redeclaration or some other bogus case. Don't try to add fields to it.
5505 if (EnclosingDecl->isInvalidDecl()) {
5506 // FIXME: Deallocate fields?
5507 return;
5508 }
5509
5510
5511 // Verify that all the fields are okay.
5512 unsigned NumNamedMembers = 0;
5513 llvm::SmallVector<FieldDecl*, 32> RecFields;
5514
5515 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
5516 for (unsigned i = 0; i != NumFields; ++i) {
5517 FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>());
5518
5519 // Get the type for the field.
5520 Type *FDTy = FD->getType().getTypePtr();
5521
5522 if (!FD->isAnonymousStructOrUnion()) {
5523 // Remember all fields written by the user.
5524 RecFields.push_back(FD);
5525 }
5526
5527 // If the field is already invalid for some reason, don't emit more
5528 // diagnostics about it.
5529 if (FD->isInvalidDecl()) {
5530 EnclosingDecl->setInvalidDecl();
5531 continue;
5532 }
5533
5534 // C99 6.7.2.1p2:
5535 // A structure or union shall not contain a member with
5536 // incomplete or function type (hence, a structure shall not
5537 // contain an instance of itself, but may contain a pointer to
5538 // an instance of itself), except that the last member of a
5539 // structure with more than one named member may have incomplete
5540 // array type; such a structure (and any union containing,
5541 // possibly recursively, a member that is such a structure)
5542 // shall not be a member of a structure or an element of an
5543 // array.
5544 if (FDTy->isFunctionType()) {
5545 // Field declared as a function.
5546 Diag(FD->getLocation(), diag::err_field_declared_as_function)
5547 << FD->getDeclName();
5548 FD->setInvalidDecl();
5549 EnclosingDecl->setInvalidDecl();
5550 continue;
5551 } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 &&
5552 Record && Record->isStruct()) {
5553 // Flexible array member.
5554 if (NumNamedMembers < 1) {
5555 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
5556 << FD->getDeclName();
5557 FD->setInvalidDecl();
5558 EnclosingDecl->setInvalidDecl();
5559 continue;
5560 }
5561 // Okay, we have a legal flexible array member at the end of the struct.
5562 if (Record)
5563 Record->setHasFlexibleArrayMember(true);
5564 } else if (!FDTy->isDependentType() &&
5565 RequireCompleteType(FD->getLocation(), FD->getType(),
5566 diag::err_field_incomplete)) {
5567 // Incomplete type
5568 FD->setInvalidDecl();
5569 EnclosingDecl->setInvalidDecl();
5570 continue;
5571 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
5572 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
5573 // If this is a member of a union, then entire union becomes "flexible".
5574 if (Record && Record->isUnion()) {
5575 Record->setHasFlexibleArrayMember(true);
5576 } else {
5577 // If this is a struct/class and this is not the last element, reject
5578 // it. Note that GCC supports variable sized arrays in the middle of
5579 // structures.
5580 if (i != NumFields-1)
5581 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
5582 << FD->getDeclName() << FD->getType();
5583 else {
5584 // We support flexible arrays at the end of structs in
5585 // other structs as an extension.
5586 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
5587 << FD->getDeclName();
5588 if (Record)
5589 Record->setHasFlexibleArrayMember(true);
5590 }
5591 }
5592 }
5593 if (Record && FDTTy->getDecl()->hasObjectMember())
5594 Record->setHasObjectMember(true);
5595 } else if (FDTy->isObjCInterfaceType()) {
5596 /// A field cannot be an Objective-c object
5597 Diag(FD->getLocation(), diag::err_statically_allocated_object);
5598 FD->setInvalidDecl();
5599 EnclosingDecl->setInvalidDecl();
5600 continue;
5601 } else if (getLangOptions().ObjC1 &&
5602 getLangOptions().getGCMode() != LangOptions::NonGC &&
5603 Record &&
5604 (FD->getType()->isObjCObjectPointerType() ||
5605 FD->getType().isObjCGCStrong()))
5606 Record->setHasObjectMember(true);
5607 // Keep track of the number of named members.
5608 if (FD->getIdentifier())
5609 ++NumNamedMembers;
5610 }
5611
5612 // Okay, we successfully defined 'Record'.
5613 if (Record) {
5614 Record->completeDefinition(Context);
5615 } else {
5616 ObjCIvarDecl **ClsFields =
5617 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
5618 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
5619 ID->setIVarList(ClsFields, RecFields.size(), Context);
5620 ID->setLocEnd(RBrac);
5621 // Add ivar's to class's DeclContext.
5622 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
5623 ClsFields[i]->setLexicalDeclContext(ID);
5624 ID->addDecl(ClsFields[i]);
5625 }
5626 // Must enforce the rule that ivars in the base classes may not be
5627 // duplicates.
5628 if (ID->getSuperClass()) {
5629 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
5630 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
5631 ObjCIvarDecl* Ivar = (*IVI);
5632
5633 if (IdentifierInfo *II = Ivar->getIdentifier()) {
5634 ObjCIvarDecl* prevIvar =
5635 ID->getSuperClass()->lookupInstanceVariable(II);
5636 if (prevIvar) {
5637 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
5638 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
5639 }
5640 }
5641 }
5642 }
5643 } else if (ObjCImplementationDecl *IMPDecl =
5644 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
5645 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
5646 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
5647 // Ivar declared in @implementation never belongs to the implementation.
5648 // Only it is in implementation's lexical context.
5649 ClsFields[I]->setLexicalDeclContext(IMPDecl);
5650 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
5651 }
5652 }
5653
5654 if (Attr)
5655 ProcessDeclAttributeList(S, Record, Attr);
5656}
5657
5658/// \brief Determine whether the given integral value is representable within
5659/// the given type T.
5660static bool isRepresentableIntegerValue(ASTContext &Context,
5661 llvm::APSInt &Value,
5662 QualType T) {
5663 assert(T->isIntegralType() && "Integral type required!");
5664 unsigned BitWidth = Context.getTypeSize(T);
5665
5666 if (Value.isUnsigned() || Value.isNonNegative())
5667 return Value.getActiveBits() < BitWidth;
5668
5669 return Value.getMinSignedBits() <= BitWidth;
5670}
5671
5672// \brief Given an integral type, return the next larger integral type
5673// (or a NULL type of no such type exists).
5674static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
5675 // FIXME: Int128/UInt128 support, which also needs to be introduced into
5676 // enum checking below.
5677 assert(T->isIntegralType() && "Integral type required!");
5678 const unsigned NumTypes = 4;
5679 QualType SignedIntegralTypes[NumTypes] = {
5680 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
5681 };
5682 QualType UnsignedIntegralTypes[NumTypes] = {
5683 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
5684 Context.UnsignedLongLongTy
5685 };
5686
5687 unsigned BitWidth = Context.getTypeSize(T);
5688 QualType *Types = T->isSignedIntegerType()? SignedIntegralTypes
5689 : UnsignedIntegralTypes;
5690 for (unsigned I = 0; I != NumTypes; ++I)
5691 if (Context.getTypeSize(Types[I]) > BitWidth)
5692 return Types[I];
5693
5694 return QualType();
5695}
5696
5697EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
5698 EnumConstantDecl *LastEnumConst,
5699 SourceLocation IdLoc,
5700 IdentifierInfo *Id,
5701 ExprArg val) {
5702 Expr *Val = (Expr *)val.get();
5703
5704 unsigned IntWidth = Context.Target.getIntWidth();
5705 llvm::APSInt EnumVal(IntWidth);
5706 QualType EltTy;
5707 if (Val) {
5708 if (Enum->isDependentType())
5709 EltTy = Context.DependentTy;
5710 else {
5711 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
5712 SourceLocation ExpLoc;
5713 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
5714 Val = 0;
5715 } else {
5716 if (!getLangOptions().CPlusPlus) {
5717 // C99 6.7.2.2p2:
5718 // The expression that defines the value of an enumeration constant
5719 // shall be an integer constant expression that has a value
5720 // representable as an int.
5721
5722 // Complain if the value is not representable in an int.
5723 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
5724 Diag(IdLoc, diag::ext_enum_value_not_int)
5725 << EnumVal.toString(10) << Val->getSourceRange()
5726 << EnumVal.isNonNegative();
5727 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
5728 // Force the type of the expression to 'int'.
5729 ImpCastExprToType(Val, Context.IntTy, CastExpr::CK_IntegralCast);
5730
5731 if (Val != val.get()) {
5732 val.release();
5733 val = Val;
5734 }
5735 }
5736 }
5737
5738 // C++0x [dcl.enum]p5:
5739 // If the underlying type is not fixed, the type of each enumerator
5740 // is the type of its initializing value:
5741 // - If an initializer is specified for an enumerator, the
5742 // initializing value has the same type as the expression.
5743 EltTy = Val->getType();
5744 }
5745 }
5746 }
5747
5748 if (!Val) {
5749 if (Enum->isDependentType())
5750 EltTy = Context.DependentTy;
5751 else if (!LastEnumConst) {
5752 // C++0x [dcl.enum]p5:
5753 // If the underlying type is not fixed, the type of each enumerator
5754 // is the type of its initializing value:
5755 // - If no initializer is specified for the first enumerator, the
5756 // initializing value has an unspecified integral type.
5757 //
5758 // GCC uses 'int' for its unspecified integral type, as does
5759 // C99 6.7.2.2p3.
5760 EltTy = Context.IntTy;
5761 } else {
5762 // Assign the last value + 1.
5763 EnumVal = LastEnumConst->getInitVal();
5764 ++EnumVal;
5765 EltTy = LastEnumConst->getType();
5766
5767 // Check for overflow on increment.
5768 if (EnumVal < LastEnumConst->getInitVal()) {
5769 // C++0x [dcl.enum]p5:
5770 // If the underlying type is not fixed, the type of each enumerator
5771 // is the type of its initializing value:
5772 //
5773 // - Otherwise the type of the initializing value is the same as
5774 // the type of the initializing value of the preceding enumerator
5775 // unless the incremented value is not representable in that type,
5776 // in which case the type is an unspecified integral type
5777 // sufficient to contain the incremented value. If no such type
5778 // exists, the program is ill-formed.
5779 QualType T = getNextLargerIntegralType(Context, EltTy);
5780 if (T.isNull()) {
5781 // There is no integral type larger enough to represent this
5782 // value. Complain, then allow the value to wrap around.
5783 EnumVal = LastEnumConst->getInitVal();
5784 EnumVal.zext(EnumVal.getBitWidth() * 2);
5785 Diag(IdLoc, diag::warn_enumerator_too_large)
5786 << EnumVal.toString(10);
5787 } else {
5788 EltTy = T;
5789 }
5790
5791 // Retrieve the last enumerator's value, extent that type to the
5792 // type that is supposed to be large enough to represent the incremented
5793 // value, then increment.
5794 EnumVal = LastEnumConst->getInitVal();
5795 EnumVal.setIsSigned(EltTy->isSignedIntegerType());
5796 EnumVal.zextOrTrunc(Context.getTypeSize(EltTy));
5797 ++EnumVal;
5798
5799 // If we're not in C++, diagnose the overflow of enumerator values,
5800 // which in C99 means that the enumerator value is not representable in
5801 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
5802 // permits enumerator values that are representable in some larger
5803 // integral type.
5804 if (!getLangOptions().CPlusPlus && !T.isNull())
5805 Diag(IdLoc, diag::warn_enum_value_overflow);
5806 } else if (!getLangOptions().CPlusPlus &&
5807 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
5808 // Enforce C99 6.7.2.2p2 even when we compute the next value.
5809 Diag(IdLoc, diag::ext_enum_value_not_int)
5810 << EnumVal.toString(10) << 1;
5811 }
5812 }
5813 }
5814
5815 if (!Enum->isDependentType()) {
5816 // Make the enumerator value match the signedness and size of the
5817 // enumerator's type.
5818 EnumVal.zextOrTrunc(Context.getTypeSize(EltTy));
5819 EnumVal.setIsSigned(EltTy->isSignedIntegerType());
5820 }
5821
5822 val.release();
5823 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
5824 Val, EnumVal);
5825}
5826
5827
5828Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl,
5829 DeclPtrTy lastEnumConst,
5830 SourceLocation IdLoc,
5831 IdentifierInfo *Id,
5832 SourceLocation EqualLoc, ExprTy *val) {
5833 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>());
5834 EnumConstantDecl *LastEnumConst =
5835 cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>());
5836 Expr *Val = static_cast<Expr*>(val);
5837
5838 // The scope passed in may not be a decl scope. Zip up the scope tree until
5839 // we find one that is.
5840 S = getNonFieldDeclScope(S);
5841
5842 // Verify that there isn't already something declared with this name in this
5843 // scope.
5844 NamedDecl *PrevDecl = LookupSingleName(S, Id, LookupOrdinaryName,
5845 ForRedeclaration);
5846 if (PrevDecl && PrevDecl->isTemplateParameter()) {
5847 // Maybe we will complain about the shadowed template parameter.
5848 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
5849 // Just pretend that we didn't see the previous declaration.
5850 PrevDecl = 0;
5851 }
5852
5853 if (PrevDecl) {
5854 // When in C++, we may get a TagDecl with the same name; in this case the
5855 // enum constant will 'hide' the tag.
5856 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
5857 "Received TagDecl when not in C++!");
5858 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
5859 if (isa<EnumConstantDecl>(PrevDecl))
5860 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
5861 else
5862 Diag(IdLoc, diag::err_redefinition) << Id;
5863 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5864 if (Val) Val->Destroy(Context);
5865 return DeclPtrTy();
5866 }
5867 }
5868
5869 EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst,
5870 IdLoc, Id, Owned(Val));
5871
5872 // Register this decl in the current scope stack.
5873 if (New) {
5874 New->setAccess(TheEnumDecl->getAccess());
5875 PushOnScopeChains(New, S);
5876 }
5877
5878 return DeclPtrTy::make(New);
5879}
5880
5881void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
5882 SourceLocation RBraceLoc, DeclPtrTy EnumDeclX,
5883 DeclPtrTy *Elements, unsigned NumElements,
5884 Scope *S, AttributeList *Attr) {
5885 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>());
5886 QualType EnumType = Context.getTypeDeclType(Enum);
5887
5888 if (Attr)
5889 ProcessDeclAttributeList(S, Enum, Attr);
5890
5891 if (Enum->isDependentType()) {
5892 for (unsigned i = 0; i != NumElements; ++i) {
5893 EnumConstantDecl *ECD =
5894 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
5895 if (!ECD) continue;
5896
5897 ECD->setType(EnumType);
5898 }
5899
5900 Enum->completeDefinition(Context, Context.DependentTy, Context.DependentTy);
5901 return;
5902 }
5903
5904 // TODO: If the result value doesn't fit in an int, it must be a long or long
5905 // long value. ISO C does not support this, but GCC does as an extension,
5906 // emit a warning.
5907 unsigned IntWidth = Context.Target.getIntWidth();
5908 unsigned CharWidth = Context.Target.getCharWidth();
5909 unsigned ShortWidth = Context.Target.getShortWidth();
5910
5911 // Verify that all the values are okay, compute the size of the values, and
5912 // reverse the list.
5913 unsigned NumNegativeBits = 0;
5914 unsigned NumPositiveBits = 0;
5915
5916 // Keep track of whether all elements have type int.
5917 bool AllElementsInt = true;
5918
5919 for (unsigned i = 0; i != NumElements; ++i) {
5920 EnumConstantDecl *ECD =
5921 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
5922 if (!ECD) continue; // Already issued a diagnostic.
5923
5924 const llvm::APSInt &InitVal = ECD->getInitVal();
5925
5926 // Keep track of the size of positive and negative values.
5927 if (InitVal.isUnsigned() || InitVal.isNonNegative())
5928 NumPositiveBits = std::max(NumPositiveBits,
5929 (unsigned)InitVal.getActiveBits());
5930 else
5931 NumNegativeBits = std::max(NumNegativeBits,
5932 (unsigned)InitVal.getMinSignedBits());
5933
5934 // Keep track of whether every enum element has type int (very commmon).
5935 if (AllElementsInt)
5936 AllElementsInt = ECD->getType() == Context.IntTy;
5937 }
5938
5939 // Figure out the type that should be used for this enum.
5940 // FIXME: Support -fshort-enums.
5941 QualType BestType;
5942 unsigned BestWidth;
5943
5944 // C++0x N3000 [conv.prom]p3:
5945 // An rvalue of an unscoped enumeration type whose underlying
5946 // type is not fixed can be converted to an rvalue of the first
5947 // of the following types that can represent all the values of
5948 // the enumeration: int, unsigned int, long int, unsigned long
5949 // int, long long int, or unsigned long long int.
5950 // C99 6.4.4.3p2:
5951 // An identifier declared as an enumeration constant has type int.
5952 // The C99 rule is modified by a gcc extension
5953 QualType BestPromotionType;
5954
5955 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
5956
5957 if (NumNegativeBits) {
5958 // If there is a negative value, figure out the smallest integer type (of
5959 // int/long/longlong) that fits.
5960 // If it's packed, check also if it fits a char or a short.
5961 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
5962 BestType = Context.SignedCharTy;
5963 BestWidth = CharWidth;
5964 } else if (Packed && NumNegativeBits <= ShortWidth &&
5965 NumPositiveBits < ShortWidth) {
5966 BestType = Context.ShortTy;
5967 BestWidth = ShortWidth;
5968 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5969 BestType = Context.IntTy;
5970 BestWidth = IntWidth;
5971 } else {
5972 BestWidth = Context.Target.getLongWidth();
5973
5974 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5975 BestType = Context.LongTy;
5976 } else {
5977 BestWidth = Context.Target.getLongLongWidth();
5978
5979 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5980 Diag(Enum->getLocation(), diag::warn_enum_too_large);
5981 BestType = Context.LongLongTy;
5982 }
5983 }
5984 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
5985 } else {
5986 // If there is no negative value, figure out the smallest type that fits
5987 // all of the enumerator values.
5988 // If it's packed, check also if it fits a char or a short.
5989 if (Packed && NumPositiveBits <= CharWidth) {
5990 BestType = Context.UnsignedCharTy;
5991 BestPromotionType = Context.IntTy;
5992 BestWidth = CharWidth;
5993 } else if (Packed && NumPositiveBits <= ShortWidth) {
5994 BestType = Context.UnsignedShortTy;
5995 BestPromotionType = Context.IntTy;
5996 BestWidth = ShortWidth;
5997 } else if (NumPositiveBits <= IntWidth) {
5998 BestType = Context.UnsignedIntTy;
5999 BestWidth = IntWidth;
6000 BestPromotionType
6001 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6002 ? Context.UnsignedIntTy : Context.IntTy;
6003 } else if (NumPositiveBits <=
6004 (BestWidth = Context.Target.getLongWidth())) {
6005 BestType = Context.UnsignedLongTy;
6006 BestPromotionType
6007 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6008 ? Context.UnsignedLongTy : Context.LongTy;
6009 } else {
6010 BestWidth = Context.Target.getLongLongWidth();
6011 assert(NumPositiveBits <= BestWidth &&
6012 "How could an initializer get larger than ULL?");
6013 BestType = Context.UnsignedLongLongTy;
6014 BestPromotionType
6015 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6016 ? Context.UnsignedLongLongTy : Context.LongLongTy;
6017 }
6018 }
6019
6020 // Loop over all of the enumerator constants, changing their types to match
6021 // the type of the enum if needed.
6022 for (unsigned i = 0; i != NumElements; ++i) {
6023 EnumConstantDecl *ECD =
6024 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
6025 if (!ECD) continue; // Already issued a diagnostic.
6026
6027 // Standard C says the enumerators have int type, but we allow, as an
6028 // extension, the enumerators to be larger than int size. If each
6029 // enumerator value fits in an int, type it as an int, otherwise type it the
6030 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
6031 // that X has type 'int', not 'unsigned'.
6032
6033 // Determine whether the value fits into an int.
6034 llvm::APSInt InitVal = ECD->getInitVal();
6035
6036 // If it fits into an integer type, force it. Otherwise force it to match
6037 // the enum decl type.
6038 QualType NewTy;
6039 unsigned NewWidth;
6040 bool NewSign;
6041 if (!getLangOptions().CPlusPlus &&
6042 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
6043 NewTy = Context.IntTy;
6044 NewWidth = IntWidth;
6045 NewSign = true;
6046 } else if (ECD->getType() == BestType) {
6047 // Already the right type!
6048 if (getLangOptions().CPlusPlus)
6049 // C++ [dcl.enum]p4: Following the closing brace of an
6050 // enum-specifier, each enumerator has the type of its
6051 // enumeration.
6052 ECD->setType(EnumType);
6053 continue;
6054 } else {
6055 NewTy = BestType;
6056 NewWidth = BestWidth;
6057 NewSign = BestType->isSignedIntegerType();
6058 }
6059
6060 // Adjust the APSInt value.
6061 InitVal.extOrTrunc(NewWidth);
6062 InitVal.setIsSigned(NewSign);
6063 ECD->setInitVal(InitVal);
6064
6065 // Adjust the Expr initializer and type.
6066 if (ECD->getInitExpr())
6067 ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy,
6068 CastExpr::CK_IntegralCast,
6069 ECD->getInitExpr(),
6070 /*isLvalue=*/false));
6071 if (getLangOptions().CPlusPlus)
6072 // C++ [dcl.enum]p4: Following the closing brace of an
6073 // enum-specifier, each enumerator has the type of its
6074 // enumeration.
6075 ECD->setType(EnumType);
6076 else
6077 ECD->setType(NewTy);
6078 }
6079
6080 Enum->completeDefinition(Context, BestType, BestPromotionType);
6081}
6082
6083Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
6084 ExprArg expr) {
6085 StringLiteral *AsmString = cast<StringLiteral>(expr.takeAs<Expr>());
6086
6087 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
6088 Loc, AsmString);
6089 CurContext->addDecl(New);
6090 return DeclPtrTy::make(New);
6091}
6092
6093void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
6094 SourceLocation PragmaLoc,
6095 SourceLocation NameLoc) {
6096 Decl *PrevDecl = LookupSingleName(TUScope, Name, LookupOrdinaryName);
6097
6098 if (PrevDecl) {
6099 PrevDecl->addAttr(::new (Context) WeakAttr());
6100 } else {
6101 (void)WeakUndeclaredIdentifiers.insert(
6102 std::pair<IdentifierInfo*,WeakInfo>
6103 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
6104 }
6105}
6106
6107void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
6108 IdentifierInfo* AliasName,
6109 SourceLocation PragmaLoc,
6110 SourceLocation NameLoc,
6111 SourceLocation AliasNameLoc) {
6112 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, LookupOrdinaryName);
6113 WeakInfo W = WeakInfo(Name, NameLoc);
6114
6115 if (PrevDecl) {
6116 if (!PrevDecl->hasAttr<AliasAttr>())
6117 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
6118 DeclApplyPragmaWeak(TUScope, ND, W);
6119 } else {
6120 (void)WeakUndeclaredIdentifiers.insert(
6121 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
6122 }
6123}