blob: 2807e759b56d4bffb0b8245308a1247bfe34f121 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
John McCall5f1e0942010-08-24 08:50:51 +000017#include "clang/Sema/CXXFieldCollector.h"
18#include "clang/Sema/Scope.h"
John McCall781472f2010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000020#include "clang/AST/APValue.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000021#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
John McCall384aff82010-08-25 07:42:41 +000024#include "clang/AST/DeclCXX.h"
John McCall7cd088e2010-08-24 07:21:54 +000025#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000026#include "clang/AST/DeclTemplate.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000027#include "clang/AST/ExprCXX.h"
Sebastian Redld3a413d2009-04-26 20:35:05 +000028#include "clang/AST/StmtCXX.h"
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +000029#include "clang/AST/CharUnits.h"
John McCall19510852010-08-20 18:27:03 +000030#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/ParsedTemplate.h"
Douglas Gregora786fdb2009-10-13 23:27:22 +000032#include "clang/Parse/ParseDiagnostic.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000033#include "clang/Basic/PartialDiagnostic.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000034#include "clang/Basic/SourceManager.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000035#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000036// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000037#include "clang/Lex/Preprocessor.h"
Mike Stump1eb44332009-09-09 15:08:12 +000038#include "clang/Lex/HeaderSearch.h"
John McCall66755862009-12-24 09:58:38 +000039#include "llvm/ADT/Triple.h"
Douglas Gregor6ed40e32008-12-23 21:05:05 +000040#include <algorithm>
Douglas Gregor9a8c9a22009-09-28 21:14:19 +000041#include <cstring>
Douglas Gregor6ed40e32008-12-23 21:05:05 +000042#include <functional>
Reid Spencer5f016e22007-07-11 17:01:13 +000043using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000044using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000045
John McCalld226f652010-08-21 09:40:31 +000046Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr) {
47 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
Chris Lattner682bf922009-03-29 16:50:03 +000048}
49
Douglas Gregord6efafa2009-02-04 19:16:12 +000050/// \brief If the identifier refers to a type name within this scope,
51/// return the declaration of that type.
52///
53/// This routine performs ordinary name lookup of the identifier II
54/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor1a51b4a2009-02-09 15:09:02 +000055/// determine whether the name refers to a type. If so, returns an
56/// opaque pointer (actually a QualType) corresponding to that
57/// type. Otherwise, returns NULL.
Douglas Gregord6efafa2009-02-04 19:16:12 +000058///
59/// If name lookup results in an ambiguity, this routine will complain
60/// and then return NULL.
John McCallb3d87482010-08-24 05:47:05 +000061ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
62 Scope *S, CXXScopeSpec *SS,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +000063 bool isClassName, bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +000064 ParsedType ObjectTypePtr) {
Douglas Gregorf6e6fc82009-11-20 22:03:38 +000065 // Determine where we will perform name lookup.
66 DeclContext *LookupCtx = 0;
67 if (ObjectTypePtr) {
John McCallb3d87482010-08-24 05:47:05 +000068 QualType ObjectType = ObjectTypePtr.get();
Douglas Gregorf6e6fc82009-11-20 22:03:38 +000069 if (ObjectType->isRecordType())
70 LookupCtx = computeDeclContext(ObjectType);
Jeffrey Yasskinedc28772010-04-07 23:29:58 +000071 } else if (SS && SS->isNotEmpty()) {
Douglas Gregorf6e6fc82009-11-20 22:03:38 +000072 LookupCtx = computeDeclContext(*SS, false);
73
74 if (!LookupCtx) {
75 if (isDependentScopeSpecifier(*SS)) {
76 // C++ [temp.res]p3:
77 // A qualified-id that refers to a type and in which the
78 // nested-name-specifier depends on a template-parameter (14.6.2)
79 // shall be prefixed by the keyword typename to indicate that the
80 // qualified-id denotes a type, forming an
81 // elaborated-type-specifier (7.1.5.3).
82 //
83 // We therefore do not perform any name lookup if the result would
84 // refer to a member of an unknown specialization.
85 if (!isClassName)
John McCallb3d87482010-08-24 05:47:05 +000086 return ParsedType();
Douglas Gregorf6e6fc82009-11-20 22:03:38 +000087
John McCall33500952010-06-11 00:33:02 +000088 // We know from the grammar that this name refers to a type,
89 // so build a dependent node to describe the type.
John McCallb3d87482010-08-24 05:47:05 +000090 QualType T =
91 CheckTypenameType(ETK_None, SS->getScopeRep(), II,
92 SourceLocation(), SS->getRange(), NameLoc);
93 return ParsedType::make(T);
Douglas Gregorf6e6fc82009-11-20 22:03:38 +000094 }
95
John McCallb3d87482010-08-24 05:47:05 +000096 return ParsedType();
Douglas Gregorf6e6fc82009-11-20 22:03:38 +000097 }
98
John McCall77bb1aa2010-05-01 00:40:08 +000099 if (!LookupCtx->isDependentContext() &&
100 RequireCompleteDeclContext(*SS, LookupCtx))
John McCallb3d87482010-08-24 05:47:05 +0000101 return ParsedType();
Douglas Gregor42c39f32009-08-26 18:27:52 +0000102 }
Eli Friedman0f0615b2009-12-21 01:42:38 +0000103
104 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
105 // lookup for class-names.
106 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
107 LookupOrdinaryName;
108 LookupResult Result(*this, &II, NameLoc, Kind);
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000109 if (LookupCtx) {
110 // Perform "qualified" name lookup into the declaration context we
111 // computed, which is either the type of the base of a member access
112 // expression or the declaration context associated with a prior
113 // nested-name-specifier.
114 LookupQualifiedName(Result, LookupCtx);
Douglas Gregor42af25f2009-05-11 19:58:34 +0000115
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000116 if (ObjectTypePtr && Result.empty()) {
117 // C++ [basic.lookup.classref]p3:
118 // If the unqualified-id is ~type-name, the type-name is looked up
119 // in the context of the entire postfix-expression. If the type T of
120 // the object expression is of a class type C, the type-name is also
121 // looked up in the scope of class C. At least one of the lookups shall
122 // find a name that refers to (possibly cv-qualified) T.
123 LookupName(Result, S);
124 }
125 } else {
126 // Perform unqualified name lookup.
127 LookupName(Result, S);
128 }
129
Chris Lattner22bd9052009-02-16 22:07:16 +0000130 NamedDecl *IIDecl = 0;
John McCalla24dc2e2009-11-17 02:14:36 +0000131 switch (Result.getResultKind()) {
Chris Lattner22bd9052009-02-16 22:07:16 +0000132 case LookupResult::NotFound:
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000133 case LookupResult::NotFoundInCurrentInstantiation:
Chris Lattner22bd9052009-02-16 22:07:16 +0000134 case LookupResult::FoundOverloaded:
John McCall7ba107a2009-11-18 02:36:19 +0000135 case LookupResult::FoundUnresolvedValue:
John McCallc373d482010-01-27 01:50:18 +0000136 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000137 return ParsedType();
Douglas Gregorb696ea32009-02-04 17:00:24 +0000138
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000139 case LookupResult::Ambiguous:
John McCall6e247262009-10-10 05:48:19 +0000140 // Recover from type-hiding ambiguities by hiding the type. We'll
141 // do the lookup again when looking for an object, and we can
142 // diagnose the error then. If we don't do this, then the error
143 // about hiding the type will be immediately followed by an error
144 // that only makes sense if the identifier was treated like a type.
John McCalla24dc2e2009-11-17 02:14:36 +0000145 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
146 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000147 return ParsedType();
John McCalla24dc2e2009-11-17 02:14:36 +0000148 }
John McCall6e247262009-10-10 05:48:19 +0000149
Douglas Gregor31a19b62009-04-01 21:51:26 +0000150 // Look to see if we have a type anywhere in the list of results.
151 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
152 Res != ResEnd; ++Res) {
153 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000154 if (!IIDecl ||
155 (*Res)->getLocation().getRawEncoding() <
Douglas Gregor841b53c2009-04-13 15:14:38 +0000156 IIDecl->getLocation().getRawEncoding())
157 IIDecl = *Res;
Douglas Gregor31a19b62009-04-01 21:51:26 +0000158 }
159 }
160
161 if (!IIDecl) {
162 // None of the entities we found is a type, so there is no way
163 // to even assume that the result is a type. In this case, don't
164 // complain about the ambiguity. The parser will either try to
165 // perform this lookup again (e.g., as an object name), which
166 // will produce the ambiguity, or will complain that it expected
167 // a type name.
John McCalla24dc2e2009-11-17 02:14:36 +0000168 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000169 return ParsedType();
Douglas Gregor31a19b62009-04-01 21:51:26 +0000170 }
171
172 // We found a type within the ambiguous lookup; diagnose the
173 // ambiguity and then return that type. This might be the right
174 // answer, or it might not be, but it suppresses any attempt to
175 // perform the name lookup again.
Douglas Gregor31a19b62009-04-01 21:51:26 +0000176 break;
Douglas Gregorb696ea32009-02-04 17:00:24 +0000177
Chris Lattner22bd9052009-02-16 22:07:16 +0000178 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +0000179 IIDecl = Result.getFoundDecl();
Chris Lattner22bd9052009-02-16 22:07:16 +0000180 break;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000181 }
182
Chris Lattner10ca3372009-10-25 17:16:46 +0000183 assert(IIDecl && "Didn't find decl");
John McCall54abf7d2009-11-04 02:18:39 +0000184
Chris Lattner10ca3372009-10-25 17:16:46 +0000185 QualType T;
186 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
John McCall54abf7d2009-11-04 02:18:39 +0000187 DiagnoseUseOfDecl(IIDecl, NameLoc);
John McCalla24dc2e2009-11-17 02:14:36 +0000188
Chris Lattner10ca3372009-10-25 17:16:46 +0000189 if (T.isNull())
190 T = Context.getTypeDeclType(TD);
191
Douglas Gregore6258932009-03-19 00:39:20 +0000192 if (SS)
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000193 T = getElaboratedType(ETK_None, *SS, T);
Chris Lattner10ca3372009-10-25 17:16:46 +0000194
195 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +0000196 if (!HasTrailingDot)
197 T = Context.getObjCInterfaceType(IDecl);
198 }
199
200 if (T.isNull()) {
John McCalla24dc2e2009-11-17 02:14:36 +0000201 // If it's not plausibly a type, suppress diagnostics.
202 Result.suppressDiagnostics();
John McCallb3d87482010-08-24 05:47:05 +0000203 return ParsedType();
John McCalla24dc2e2009-11-17 02:14:36 +0000204 }
John McCallb3d87482010-08-24 05:47:05 +0000205 return ParsedType::make(T);
Reid Spencer5f016e22007-07-11 17:01:13 +0000206}
207
Chris Lattner4c97d762009-04-12 21:49:30 +0000208/// isTagName() - This method is called *for error recovery purposes only*
209/// to determine if the specified name is a valid tag name ("struct foo"). If
210/// so, this returns the TST for the tag corresponding to it (TST_enum,
211/// TST_union, TST_struct, TST_class). This is used to diagnose cases in C
212/// where the user forgot to specify the tag.
213DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
214 // Do a tag name lookup in this scope.
John McCalla24dc2e2009-11-17 02:14:36 +0000215 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
216 LookupName(R, S, false);
217 R.suppressDiagnostics();
218 if (R.getResultKind() == LookupResult::Found)
John McCall1bcee0a2009-12-02 08:25:40 +0000219 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
Chris Lattner4c97d762009-04-12 21:49:30 +0000220 switch (TD->getTagKind()) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000221 default: return DeclSpec::TST_unspecified;
222 case TTK_Struct: return DeclSpec::TST_struct;
223 case TTK_Union: return DeclSpec::TST_union;
224 case TTK_Class: return DeclSpec::TST_class;
225 case TTK_Enum: return DeclSpec::TST_enum;
Chris Lattner4c97d762009-04-12 21:49:30 +0000226 }
227 }
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Chris Lattner4c97d762009-04-12 21:49:30 +0000229 return DeclSpec::TST_unspecified;
230}
231
Douglas Gregora786fdb2009-10-13 23:27:22 +0000232bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
233 SourceLocation IILoc,
234 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000235 CXXScopeSpec *SS,
John McCallb3d87482010-08-24 05:47:05 +0000236 ParsedType &SuggestedType) {
Douglas Gregora786fdb2009-10-13 23:27:22 +0000237 // We don't have anything to suggest (yet).
John McCallb3d87482010-08-24 05:47:05 +0000238 SuggestedType = ParsedType();
Douglas Gregora786fdb2009-10-13 23:27:22 +0000239
Douglas Gregor546be3c2009-12-30 17:04:44 +0000240 // There may have been a typo in the name of the type. Look up typo
241 // results, in case we have something that we can suggest.
242 LookupResult Lookup(*this, &II, IILoc, LookupOrdinaryName,
243 NotForRedeclaration);
244
Douglas Gregoraaf87162010-04-14 20:04:41 +0000245 if (DeclarationName Corrected = CorrectTypo(Lookup, S, SS, 0, 0, CTC_Type)) {
246 if (NamedDecl *Result = Lookup.getAsSingle<NamedDecl>()) {
247 if ((isa<TypeDecl>(Result) || isa<ObjCInterfaceDecl>(Result)) &&
248 !Result->isInvalidDecl()) {
249 // We found a similarly-named type or interface; suggest that.
250 if (!SS || !SS->isSet())
251 Diag(IILoc, diag::err_unknown_typename_suggest)
252 << &II << Lookup.getLookupName()
253 << FixItHint::CreateReplacement(SourceRange(IILoc),
254 Result->getNameAsString());
255 else if (DeclContext *DC = computeDeclContext(*SS, false))
256 Diag(IILoc, diag::err_unknown_nested_typename_suggest)
257 << &II << DC << Lookup.getLookupName() << SS->getRange()
258 << FixItHint::CreateReplacement(SourceRange(IILoc),
259 Result->getNameAsString());
260 else
261 llvm_unreachable("could not have corrected a typo here");
Douglas Gregor546be3c2009-12-30 17:04:44 +0000262
Douglas Gregoraaf87162010-04-14 20:04:41 +0000263 Diag(Result->getLocation(), diag::note_previous_decl)
264 << Result->getDeclName();
265
266 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS);
267 return true;
268 }
269 } else if (Lookup.empty()) {
270 // We corrected to a keyword.
271 // FIXME: Actually recover with the keyword we suggest, and emit a fix-it.
272 Diag(IILoc, diag::err_unknown_typename_suggest)
273 << &II << Corrected;
274 return true;
Douglas Gregor546be3c2009-12-30 17:04:44 +0000275 }
276 }
277
Jeffrey Yasskinc173be22010-04-08 21:04:54 +0000278 if (getLangOptions().CPlusPlus) {
279 // See if II is a class template that the user forgot to pass arguments to.
280 UnqualifiedId Name;
281 Name.setIdentifier(&II, IILoc);
282 CXXScopeSpec EmptySS;
283 TemplateTy TemplateResult;
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000284 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +0000285 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
John McCallb3d87482010-08-24 05:47:05 +0000286 Name, ParsedType(), true, TemplateResult,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000287 MemberOfUnknownSpecialization) == TNK_Type_template) {
Jeffrey Yasskinc173be22010-04-08 21:04:54 +0000288 TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
289 Diag(IILoc, diag::err_template_missing_args) << TplName;
290 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
291 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
292 << TplDecl->getTemplateParameters()->getSourceRange();
293 }
294 return true;
295 }
296 }
297
Douglas Gregora786fdb2009-10-13 23:27:22 +0000298 // FIXME: Should we move the logic that tries to recover from a missing tag
299 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
300
Douglas Gregor546be3c2009-12-30 17:04:44 +0000301 if (!SS || (!SS->isSet() && !SS->isInvalid()))
Douglas Gregora786fdb2009-10-13 23:27:22 +0000302 Diag(IILoc, diag::err_unknown_typename) << &II;
303 else if (DeclContext *DC = computeDeclContext(*SS, false))
304 Diag(IILoc, diag::err_typename_nested_not_found)
305 << &II << DC << SS->getRange();
306 else if (isDependentScopeSpecifier(*SS)) {
307 Diag(SS->getRange().getBegin(), diag::err_typename_missing)
Daniel Dunbar01eb9b92009-10-18 21:17:35 +0000308 << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
Douglas Gregora786fdb2009-10-13 23:27:22 +0000309 << SourceRange(SS->getRange().getBegin(), IILoc)
Douglas Gregor849b2432010-03-31 17:46:05 +0000310 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
Douglas Gregor1a15dae2010-06-16 22:31:08 +0000311 SuggestedType = ActOnTypenameType(S, SourceLocation(), *SS, II, IILoc).get();
Douglas Gregora786fdb2009-10-13 23:27:22 +0000312 } else {
313 assert(SS && SS->isInvalid() &&
314 "Invalid scope specifier has already been diagnosed");
315 }
316
317 return true;
318}
Chris Lattner4c97d762009-04-12 21:49:30 +0000319
John McCall88232aa2009-08-18 00:00:49 +0000320// Determines the context to return to after temporarily entering a
321// context. This depends in an unnecessarily complicated way on the
322// exact ordering of callbacks from the parser.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000323DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000324
John McCall88232aa2009-08-18 00:00:49 +0000325 // Functions defined inline within classes aren't parsed until we've
326 // finished parsing the top-level class, so the top-level class is
327 // the context we'll need to return to.
328 if (isa<FunctionDecl>(DC)) {
329 DC = DC->getLexicalParent();
330
331 // A function not defined within a class will always return to its
332 // lexical context.
333 if (!isa<CXXRecordDecl>(DC))
334 return DC;
335
336 // A C++ inline method/friend is parsed *after* the topmost class
337 // it was declared in is fully parsed ("complete"); the topmost
338 // class is the context we need to return to.
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +0000339 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000340 DC = RD;
341
342 // Return the declaration context of the topmost class the inline method is
343 // declared in.
344 return DC;
345 }
346
John McCall9983d2d2010-08-06 00:46:05 +0000347 // ObjCMethodDecls are parsed (for some reason) outside the context
348 // of the class.
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +0000349 if (isa<ObjCMethodDecl>(DC))
John McCall9983d2d2010-08-06 00:46:05 +0000350 return DC->getLexicalParent()->getLexicalParent();
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +0000351
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +0000352 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000353}
354
Douglas Gregor44b43212008-12-11 16:49:14 +0000355void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000356 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xue50897a2008-12-08 07:14:51 +0000357 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +0000358 CurContext = DC;
Douglas Gregor44b43212008-12-11 16:49:14 +0000359 S->setEntity(DC);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000360}
361
Chris Lattnerb048c982008-04-06 04:47:34 +0000362void Sema::PopDeclContext() {
363 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor44b43212008-12-11 16:49:14 +0000364
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000365 CurContext = getContainingDC(CurContext);
John McCallacb70392010-07-23 22:45:07 +0000366 assert(CurContext && "Popped translation unit!");
Chris Lattner0ed844b2008-04-04 06:12:32 +0000367}
368
Argyrios Kyrtzidis179fe1a2009-06-17 23:19:02 +0000369/// EnterDeclaratorContext - Used when we must lookup names in the context
370/// of a declarator's nested name specifier.
John McCall7a1dc562009-12-19 10:49:29 +0000371///
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000372void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall7a1dc562009-12-19 10:49:29 +0000373 // C++0x [basic.lookup.unqual]p13:
374 // A name used in the definition of a static data member of class
375 // X (after the qualified-id of the static member) is looked up as
376 // if the name was used in a member function of X.
377 // C++0x [basic.lookup.unqual]p14:
378 // If a variable member of a namespace is defined outside of the
379 // scope of its namespace then any name used in the definition of
380 // the variable member (after the declarator-id) is looked up as
381 // if the definition of the variable member occurred in its
382 // namespace.
383 // Both of these imply that we should push a scope whose context
384 // is the semantic context of the declaration. We can't use
385 // PushDeclContext here because that context is not necessarily
386 // lexically contained in the current context. Fortunately,
387 // the containing scope should have the appropriate information.
388
389 assert(!S->getEntity() && "scope already has entity");
390
391#ifndef NDEBUG
392 Scope *Ancestor = S->getParent();
393 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
394 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
395#endif
396
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000397 CurContext = DC;
John McCall7a1dc562009-12-19 10:49:29 +0000398 S->setEntity(DC);
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000399}
400
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000401void Sema::ExitDeclaratorContext(Scope *S) {
John McCall7a1dc562009-12-19 10:49:29 +0000402 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000403
John McCall7a1dc562009-12-19 10:49:29 +0000404 // Switch back to the lexical context. The safety of this is
405 // enforced by an assert in EnterDeclaratorContext.
406 Scope *Ancestor = S->getParent();
407 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
408 CurContext = (DeclContext*) Ancestor->getEntity();
409
410 // We don't need to do anything with the scope, which is going to
411 // disappear.
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +0000412}
413
Douglas Gregorf9201e02009-02-11 23:02:49 +0000414/// \brief Determine whether we allow overloading of the function
415/// PrevDecl with another declaration.
416///
417/// This routine determines whether overloading is possible, not
418/// whether some new function is actually an overload. It will return
419/// true in C++ (where we can always provide overloads) or, as an
420/// extension, in C when the previous function is already an
421/// overloaded function declaration or has the "overloadable"
422/// attribute.
John McCall68263142009-11-18 22:49:29 +0000423static bool AllowOverloadingOfFunction(LookupResult &Previous,
424 ASTContext &Context) {
Douglas Gregorf9201e02009-02-11 23:02:49 +0000425 if (Context.getLangOptions().CPlusPlus)
426 return true;
427
John McCall68263142009-11-18 22:49:29 +0000428 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000429 return true;
430
John McCall68263142009-11-18 22:49:29 +0000431 return (Previous.getResultKind() == LookupResult::Found
432 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregorf9201e02009-02-11 23:02:49 +0000433}
434
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000435/// Add this decl to the scope shadowed decl chains.
John McCallab88d972009-08-31 22:39:49 +0000436void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor074149e2009-01-05 19:45:36 +0000437 // Move up the scope chain until we find the nearest enclosing
438 // non-transparent context. The declaration will be introduced into this
439 // scope.
Mike Stump1eb44332009-09-09 15:08:12 +0000440 while (S->getEntity() &&
Douglas Gregor074149e2009-01-05 19:45:36 +0000441 ((DeclContext *)S->getEntity())->isTransparentContext())
442 S = S->getParent();
443
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000444 // Add scoped declarations into their context, so that they can be
445 // found later. Declarations without a context won't be inserted
446 // into any context.
John McCallab88d972009-08-31 22:39:49 +0000447 if (AddToContext)
448 CurContext->addDecl(D);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000449
Chandler Carruth8761d682010-02-21 07:08:09 +0000450 // Out-of-line definitions shouldn't be pushed into scope in C++.
451 // Out-of-line variable and function definitions shouldn't even in C.
452 if ((getLangOptions().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
453 D->isOutOfLine())
454 return;
455
456 // Template instantiations should also not be pushed into scope.
457 if (isa<FunctionDecl>(D) &&
458 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregord04b1be2009-09-28 18:41:37 +0000459 return;
460
John McCallf36e02d2009-10-09 21:13:30 +0000461 // If this replaces anything in the current scope,
462 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
463 IEnd = IdResolver.end();
464 for (; I != IEnd; ++I) {
John McCalld226f652010-08-21 09:40:31 +0000465 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
466 S->RemoveDecl(*I);
John McCallf36e02d2009-10-09 21:13:30 +0000467 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000468
John McCallf36e02d2009-10-09 21:13:30 +0000469 // Should only need to replace one decl.
470 break;
Douglas Gregor516ff432009-04-24 02:57:34 +0000471 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000472 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000473
John McCalld226f652010-08-21 09:40:31 +0000474 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000475 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000476}
477
Douglas Gregor2531c2d2009-09-28 00:47:05 +0000478bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S) {
Douglas Gregor2531c2d2009-09-28 00:47:05 +0000479 return IdResolver.isDeclInScope(D, Ctx, Context, S);
480}
481
John McCall5f1e0942010-08-24 08:50:51 +0000482Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
483 DeclContext *TargetDC = DC->getPrimaryContext();
484 do {
485 if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
486 if (ScopeDC->getPrimaryContext() == TargetDC)
487 return S;
488 } while ((S = S->getParent()));
489
490 return 0;
491}
492
John McCall68263142009-11-18 22:49:29 +0000493static bool isOutOfScopePreviousDeclaration(NamedDecl *,
494 DeclContext*,
495 ASTContext&);
496
497/// Filters out lookup results that don't fall within the given scope
498/// as determined by isDeclInScope.
499static void FilterLookupForScope(Sema &SemaRef, LookupResult &R,
500 DeclContext *Ctx, Scope *S,
501 bool ConsiderLinkage) {
502 LookupResult::Filter F = R.makeFilter();
503 while (F.hasNext()) {
504 NamedDecl *D = F.next();
505
506 if (SemaRef.isDeclInScope(D, Ctx, S))
507 continue;
508
509 if (ConsiderLinkage &&
510 isOutOfScopePreviousDeclaration(D, Ctx, SemaRef.Context))
511 continue;
512
513 F.erase();
514 }
515
516 F.done();
517}
518
519static bool isUsingDecl(NamedDecl *D) {
520 return isa<UsingShadowDecl>(D) ||
521 isa<UnresolvedUsingTypenameDecl>(D) ||
522 isa<UnresolvedUsingValueDecl>(D);
523}
524
525/// Removes using shadow declarations from the lookup results.
526static void RemoveUsingDecls(LookupResult &R) {
527 LookupResult::Filter F = R.makeFilter();
528 while (F.hasNext())
529 if (isUsingDecl(F.next()))
530 F.erase();
531
532 F.done();
533}
534
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +0000535/// \brief Check for this common pattern:
536/// @code
537/// class S {
538/// S(const S&); // DO NOT IMPLEMENT
539/// void operator=(const S&); // DO NOT IMPLEMENT
540/// };
541/// @endcode
542static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
543 // FIXME: Should check for private access too but access is set after we get
544 // the decl here.
545 if (D->isThisDeclarationADefinition())
546 return false;
547
548 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
549 return CD->isCopyConstructor();
Douglas Gregor27c08ab2010-09-27 22:06:20 +0000550 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
551 return Method->isCopyAssignmentOperator();
552 return false;
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +0000553}
554
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000555bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
556 assert(D);
Argyrios Kyrtzidisf6d1d432010-08-13 18:42:29 +0000557
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000558 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
559 return false;
560
561 // Ignore class templates.
Chandler Carruthef9d09c2011-01-03 19:27:19 +0000562 if (D->getDeclContext()->isDependentContext() ||
563 D->getLexicalDeclContext()->isDependentContext())
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000564 return false;
565
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000566 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +0000567 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
568 return false;
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000569
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +0000570 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
571 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
572 return false;
573 } else {
574 // 'static inline' functions are used in headers; don't warn.
John McCalld931b082010-08-26 03:08:43 +0000575 if (FD->getStorageClass() == SC_Static &&
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +0000576 FD->isInlineSpecified())
577 return false;
578 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000579
John McCall82b96592010-10-27 01:41:35 +0000580 if (FD->isThisDeclarationADefinition() &&
581 Context.DeclMustBeEmitted(FD))
582 return false;
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000583
John McCall82b96592010-10-27 01:41:35 +0000584 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
585 if (!VD->isFileVarDecl() ||
586 VD->getType().isConstant(Context) ||
587 Context.DeclMustBeEmitted(VD))
588 return false;
589
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000590 if (VD->isStaticDataMember() &&
591 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
592 return false;
593
John McCall82b96592010-10-27 01:41:35 +0000594 } else {
595 return false;
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000596 }
597
John McCall82b96592010-10-27 01:41:35 +0000598 // Only warn for unused decls internal to the translation unit.
599 if (D->getLinkage() == ExternalLinkage)
600 return false;
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000601
John McCall82b96592010-10-27 01:41:35 +0000602 return true;
603}
604
605void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000606 if (!D)
607 return;
608
609 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
610 const FunctionDecl *First = FD->getFirstDeclaration();
611 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
612 return; // First should already be in the vector.
613 }
614
615 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
616 const VarDecl *First = VD->getFirstDeclaration();
617 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
618 return; // First should already be in the vector.
619 }
620
621 if (ShouldWarnIfUnusedFileScopedDecl(D))
622 UnusedFileScopedDecls.push_back(D);
623 }
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +0000624
Anders Carlsson99a000e2009-11-07 07:18:14 +0000625static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall86ff3082010-02-04 22:26:26 +0000626 if (D->isInvalidDecl())
627 return false;
628
Anders Carlssonf7613d52009-11-07 07:26:56 +0000629 if (D->isUsed() || D->hasAttr<UnusedAttr>())
630 return false;
John McCall86ff3082010-02-04 22:26:26 +0000631
632 // White-list anything that isn't a local variable.
633 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
634 !D->getDeclContext()->isFunctionOrMethod())
635 return false;
636
637 // Types of valid local variables should be complete, so this should succeed.
Anders Carlssonf7613d52009-11-07 07:26:56 +0000638 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
John McCallaec58602010-03-31 02:47:45 +0000639
640 // White-list anything with an __attribute__((unused)) type.
641 QualType Ty = VD->getType();
642
643 // Only look at the outermost level of typedef.
644 if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) {
645 if (TT->getDecl()->hasAttr<UnusedAttr>())
646 return false;
647 }
648
Douglas Gregor5764f612010-05-08 23:05:03 +0000649 // If we failed to complete the type for some reason, or if the type is
650 // dependent, don't diagnose the variable.
651 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregora6a292b2010-04-27 16:20:13 +0000652 return false;
653
John McCallaec58602010-03-31 02:47:45 +0000654 if (const TagType *TT = Ty->getAs<TagType>()) {
655 const TagDecl *Tag = TT->getDecl();
656 if (Tag->hasAttr<UnusedAttr>())
657 return false;
658
659 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Douglas Gregor5764f612010-05-08 23:05:03 +0000660 // FIXME: Checking for the presence of a user-declared constructor
661 // isn't completely accurate; we'd prefer to check that the initializer
662 // has no side effects.
663 if (RD->hasUserDeclaredConstructor() || !RD->hasTrivialDestructor())
Anders Carlssonf7613d52009-11-07 07:26:56 +0000664 return false;
665 }
666 }
John McCallaec58602010-03-31 02:47:45 +0000667
668 // TODO: __attribute__((unused)) templates?
Anders Carlssonf7613d52009-11-07 07:26:56 +0000669 }
670
John McCall86ff3082010-02-04 22:26:26 +0000671 return true;
Anders Carlsson99a000e2009-11-07 07:18:14 +0000672}
673
Douglas Gregor5764f612010-05-08 23:05:03 +0000674void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
675 if (!ShouldDiagnoseUnusedDecl(D))
676 return;
677
678 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
679 Diag(D->getLocation(), diag::warn_unused_exception_param)
680 << D->getDeclName();
681 else
682 Diag(D->getLocation(), diag::warn_unused_variable)
683 << D->getDeclName();
684}
685
Steve Naroffb216c882007-10-09 22:01:59 +0000686void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000687 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000688 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump1eb44332009-09-09 15:08:12 +0000689 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000690
Reid Spencer5f016e22007-07-11 17:01:13 +0000691 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
692 I != E; ++I) {
John McCalld226f652010-08-21 09:40:31 +0000693 Decl *TmpD = (*I);
Steve Naroffc752d042007-09-13 18:10:37 +0000694 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000695
Douglas Gregor44b43212008-12-11 16:49:14 +0000696 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
697 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000698
Douglas Gregor44b43212008-12-11 16:49:14 +0000699 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000700
Douglas Gregorb5352cf2009-10-08 21:35:42 +0000701 // Diagnose unused variables in this scope.
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +0000702 if (!S->hasErrorOccurred())
Douglas Gregor5764f612010-05-08 23:05:03 +0000703 DiagnoseUnusedDecl(D);
704
Douglas Gregor44b43212008-12-11 16:49:14 +0000705 // Remove this name from our lexical scope.
706 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000707 }
708}
709
Douglas Gregordeacbdc2010-08-11 12:19:30 +0000710/// \brief Look for an Objective-C class in the translation unit.
711///
712/// \param Id The name of the Objective-C class we're looking for. If
713/// typo-correction fixes this name, the Id will be updated
714/// to the fixed name.
715///
716/// \param IdLoc The location of the name in the translation unit.
717///
718/// \param TypoCorrection If true, this routine will attempt typo correction
719/// if there is no class with the given name.
720///
721/// \returns The declaration of the named Objective-C class, or NULL if the
722/// class could not be found.
723ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
724 SourceLocation IdLoc,
725 bool TypoCorrection) {
726 // The third "scope" argument is 0 since we aren't enabling lazy built-in
727 // creation from this context.
728 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
729
730 if (!IDecl && TypoCorrection) {
731 // Perform typo correction at the given location, but only if we
732 // find an Objective-C class name.
733 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName);
734 if (CorrectTypo(R, TUScope, 0, 0, false, CTC_NoKeywords) &&
735 (IDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
736 Diag(IdLoc, diag::err_undef_interface_suggest)
737 << Id << IDecl->getDeclName()
738 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
739 Diag(IDecl->getLocation(), diag::note_previous_decl)
740 << IDecl->getDeclName();
741
742 Id = IDecl->getIdentifier();
743 }
744 }
745
746 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
747}
748
Douglas Gregor1a0d31a2009-01-12 18:45:55 +0000749/// getNonFieldDeclScope - Retrieves the innermost scope, starting
750/// from S, where a non-field would be declared. This routine copes
751/// with the difference between C and C++ scoping rules in structs and
752/// unions. For example, the following code is well-formed in C but
753/// ill-formed in C++:
754/// @code
755/// struct S6 {
756/// enum { BAR } e;
757/// };
Mike Stump1eb44332009-09-09 15:08:12 +0000758///
Douglas Gregor1a0d31a2009-01-12 18:45:55 +0000759/// void test_S6() {
760/// struct S6 a;
761/// a.e = BAR;
762/// }
763/// @endcode
764/// For the declaration of BAR, this routine will return a different
765/// scope. The scope S will be the scope of the unnamed enumeration
766/// within S6. In C++, this routine will return the scope associated
767/// with S6, because the enumeration's scope is a transparent
768/// context but structures can contain non-field names. In C, this
769/// routine will return the translation unit scope, since the
770/// enumeration's scope is a transparent context and structures cannot
771/// contain non-field names.
772Scope *Sema::getNonFieldDeclScope(Scope *S) {
773 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000774 (S->getEntity() &&
Douglas Gregor1a0d31a2009-01-12 18:45:55 +0000775 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
776 (S->isClassScope() && !getLangOptions().CPlusPlus))
777 S = S->getParent();
778 return S;
779}
780
Douglas Gregor3e41d602009-02-13 23:20:09 +0000781/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
782/// file scope. lazily create a decl for it. ForRedeclaration is true
783/// if we're creating this built-in in anticipation of redeclaring the
784/// built-in.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000785NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregor3e41d602009-02-13 23:20:09 +0000786 Scope *S, bool ForRedeclaration,
787 SourceLocation Loc) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000788 Builtin::ID BID = (Builtin::ID)bid;
789
Chris Lattner86df27b2009-06-14 00:45:47 +0000790 ASTContext::GetBuiltinTypeError Error;
Mike Stump1eb44332009-09-09 15:08:12 +0000791 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor370ab3f2009-02-14 01:52:53 +0000792 switch (Error) {
Chris Lattner86df27b2009-06-14 00:45:47 +0000793 case ASTContext::GE_None:
Douglas Gregor370ab3f2009-02-14 01:52:53 +0000794 // Okay
795 break;
796
Mike Stumpf711c412009-07-28 23:57:15 +0000797 case ASTContext::GE_Missing_stdio:
Douglas Gregor370ab3f2009-02-14 01:52:53 +0000798 if (ForRedeclaration)
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000799 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
Douglas Gregor370ab3f2009-02-14 01:52:53 +0000800 << Context.BuiltinInfo.GetName(BID);
801 return 0;
Mike Stump782fa302009-07-28 02:25:19 +0000802
Mike Stumpf711c412009-07-28 23:57:15 +0000803 case ASTContext::GE_Missing_setjmp:
Mike Stump782fa302009-07-28 02:25:19 +0000804 if (ForRedeclaration)
Douglas Gregor6b9109e2011-01-03 09:37:44 +0000805 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
Mike Stump782fa302009-07-28 02:25:19 +0000806 << Context.BuiltinInfo.GetName(BID);
807 return 0;
Douglas Gregor370ab3f2009-02-14 01:52:53 +0000808 }
Douglas Gregor3e41d602009-02-13 23:20:09 +0000809
810 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
811 Diag(Loc, diag::ext_implicit_lib_function_decl)
812 << Context.BuiltinInfo.GetName(BID)
813 << R;
Douglas Gregorb1152d82009-02-16 21:58:21 +0000814 if (Context.BuiltinInfo.getHeaderName(BID) &&
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000815 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
Chris Lattner6a7334d2009-04-16 03:59:32 +0000816 != Diagnostic::Ignored)
Douglas Gregor3e41d602009-02-13 23:20:09 +0000817 Diag(Loc, diag::note_please_include_header)
818 << Context.BuiltinInfo.getHeaderName(BID)
819 << Context.BuiltinInfo.GetName(BID);
820 }
821
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000822 FunctionDecl *New = FunctionDecl::Create(Context,
823 Context.getTranslationUnitDecl(),
John McCalla93c9342009-12-07 02:54:59 +0000824 Loc, II, R, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +0000825 SC_Extern,
826 SC_None, false,
Douglas Gregor2224f842009-02-25 16:33:18 +0000827 /*hasPrototype=*/true);
Douglas Gregor3e41d602009-02-13 23:20:09 +0000828 New->setImplicit();
829
Chris Lattner95e2c712008-05-05 22:18:14 +0000830 // Create Decl objects for each parameter, adding them to the
831 // FunctionDecl.
John McCallf4c73712011-01-19 06:33:43 +0000832 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner95e2c712008-05-05 22:18:14 +0000833 llvm::SmallVector<ParmVarDecl*, 16> Params;
834 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
835 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +0000836 FT->getArgType(i), /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +0000837 SC_None, SC_None, 0));
Douglas Gregor838db382010-02-11 01:19:42 +0000838 New->setParams(Params.data(), Params.size());
Chris Lattner95e2c712008-05-05 22:18:14 +0000839 }
Mike Stump1eb44332009-09-09 15:08:12 +0000840
841 AddKnownFunctionAttributes(New);
842
Chris Lattner7f925cc2008-04-11 07:00:53 +0000843 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000844 // FIXME: This is hideous. We need to teach PushOnScopeChains to
845 // relate Scopes to DeclContexts, and probably eliminate CurContext
846 // entirely, but we're not there yet.
847 DeclContext *SavedContext = CurContext;
848 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000849 PushOnScopeChains(New, TUScope);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000850 CurContext = SavedContext;
Reid Spencer5f016e22007-07-11 17:01:13 +0000851 return New;
852}
853
Douglas Gregorcda9c672009-02-16 17:45:42 +0000854/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
855/// same name and scope as a previous declaration 'Old'. Figure out
856/// how to resolve this situation, merging decls or emitting
Chris Lattnereaaebc72009-04-25 08:06:05 +0000857/// diagnostics as appropriate. If there was an error, set New to be invalid.
Reid Spencer5f016e22007-07-11 17:01:13 +0000858///
John McCall68263142009-11-18 22:49:29 +0000859void Sema::MergeTypeDefDecl(TypedefDecl *New, LookupResult &OldDecls) {
860 // If the new decl is known invalid already, don't bother doing any
861 // merging checks.
862 if (New->isInvalidDecl()) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000863
Steve Naroff2b255c42008-09-09 14:32:20 +0000864 // Allow multiple definitions for ObjC built-in typedefs.
865 // FIXME: Verify the underlying types are equivalent!
866 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000867 const IdentifierInfo *TypeID = New->getIdentifier();
868 switch (TypeID->getLength()) {
869 default: break;
Mike Stump1eb44332009-09-09 15:08:12 +0000870 case 2:
Chris Lattner2bac0f62008-11-20 05:41:43 +0000871 if (!TypeID->isStr("id"))
872 break;
David Chisnall0f436562009-08-17 16:35:33 +0000873 Context.ObjCIdRedefinitionType = New->getUnderlyingType();
Steve Naroff14108da2009-07-10 23:34:53 +0000874 // Install the built-in type for 'id', ignoring the current definition.
875 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
876 return;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000877 case 5:
878 if (!TypeID->isStr("Class"))
879 break;
David Chisnall0f436562009-08-17 16:35:33 +0000880 Context.ObjCClassRedefinitionType = New->getUnderlyingType();
Steve Naroff14108da2009-07-10 23:34:53 +0000881 // Install the built-in type for 'Class', ignoring the current definition.
882 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnereaaebc72009-04-25 08:06:05 +0000883 return;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000884 case 3:
885 if (!TypeID->isStr("SEL"))
886 break;
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +0000887 Context.ObjCSelRedefinitionType = New->getUnderlyingType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000888 // Install the built-in type for 'SEL', ignoring the current definition.
889 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnereaaebc72009-04-25 08:06:05 +0000890 return;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000891 case 8:
892 if (!TypeID->isStr("Protocol"))
893 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000894 Context.setObjCProtoType(New->getUnderlyingType());
Chris Lattnereaaebc72009-04-25 08:06:05 +0000895 return;
Steve Naroff2b255c42008-09-09 14:32:20 +0000896 }
897 // Fall through - the typedef name was not a builtin type.
898 }
John McCall68263142009-11-18 22:49:29 +0000899
Douglas Gregor66973122009-01-28 17:15:10 +0000900 // Verify the old decl was also a type.
John McCall5126fd02009-12-30 00:31:22 +0000901 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
902 if (!Old) {
Mike Stump1eb44332009-09-09 15:08:12 +0000903 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000904 << New->getDeclName();
John McCall68263142009-11-18 22:49:29 +0000905
906 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000907 if (OldD->getLocation().isValid())
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000908 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall68263142009-11-18 22:49:29 +0000909
Chris Lattnereaaebc72009-04-25 08:06:05 +0000910 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000911 }
Douglas Gregor66973122009-01-28 17:15:10 +0000912
John McCall68263142009-11-18 22:49:29 +0000913 // If the old declaration is invalid, just give up here.
914 if (Old->isInvalidDecl())
915 return New->setInvalidDecl();
916
Mike Stump1eb44332009-09-09 15:08:12 +0000917 // Determine the "old" type we'll use for checking and diagnostics.
Douglas Gregor66973122009-01-28 17:15:10 +0000918 QualType OldType;
919 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
920 OldType = OldTypedef->getUnderlyingType();
921 else
922 OldType = Context.getTypeDeclType(Old);
923
Chris Lattner99cb9972008-07-25 18:44:27 +0000924 // If the typedef types are not identical, reject them in all languages and
925 // with any extensions enabled.
Douglas Gregor66973122009-01-28 17:15:10 +0000926
Mike Stump1eb44332009-09-09 15:08:12 +0000927 if (OldType != New->getUnderlyingType() &&
928 Context.getCanonicalType(OldType) !=
Chris Lattner99cb9972008-07-25 18:44:27 +0000929 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000930 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Douglas Gregor66973122009-01-28 17:15:10 +0000931 << New->getUnderlyingType() << OldType;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000932 if (Old->getLocation().isValid())
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000933 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000934 return New->setInvalidDecl();
Chris Lattner99cb9972008-07-25 18:44:27 +0000935 }
Mike Stump1eb44332009-09-09 15:08:12 +0000936
John McCall5126fd02009-12-30 00:31:22 +0000937 // The types match. Link up the redeclaration chain if the old
938 // declaration was a typedef.
939 // FIXME: this is a potential source of wierdness if the type
940 // spellings don't match exactly.
941 if (isa<TypedefDecl>(Old))
942 New->setPreviousDeclaration(cast<TypedefDecl>(Old));
943
Steve Naroff14108da2009-07-10 23:34:53 +0000944 if (getLangOptions().Microsoft)
Chris Lattnereaaebc72009-04-25 08:06:05 +0000945 return;
Eli Friedman54ecfce2008-06-11 06:20:39 +0000946
Chris Lattner32b06752009-04-17 22:04:20 +0000947 if (getLangOptions().CPlusPlus) {
Douglas Gregor93dda722010-01-11 21:54:40 +0000948 // C++ [dcl.typedef]p2:
949 // In a given non-class scope, a typedef specifier can be used to
950 // redefine the name of any type declared in that scope to refer
951 // to the type to which it already refers.
Chris Lattner32b06752009-04-17 22:04:20 +0000952 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnereaaebc72009-04-25 08:06:05 +0000953 return;
Douglas Gregor93dda722010-01-11 21:54:40 +0000954
955 // C++0x [dcl.typedef]p4:
956 // In a given class scope, a typedef specifier can be used to redefine
957 // any class-name declared in that scope that is not also a typedef-name
958 // to refer to the type to which it already refers.
959 //
960 // This wording came in via DR424, which was a correction to the
961 // wording in DR56, which accidentally banned code like:
962 //
963 // struct S {
964 // typedef struct A { } A;
965 // };
966 //
967 // in the C++03 standard. We implement the C++0x semantics, which
968 // allow the above but disallow
969 //
970 // struct S {
971 // typedef int I;
972 // typedef int I;
973 // };
974 //
975 // since that was the intent of DR56.
Douglas Gregor05f65002010-01-11 22:30:10 +0000976 if (!isa<TypedefDecl >(Old))
Douglas Gregor93dda722010-01-11 21:54:40 +0000977 return;
978
Chris Lattner32b06752009-04-17 22:04:20 +0000979 Diag(New->getLocation(), diag::err_redefinition)
980 << New->getDeclName();
981 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000982 return New->setInvalidDecl();
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000983 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000984
Chris Lattner32b06752009-04-17 22:04:20 +0000985 // If we have a redefinition of a typedef in C, emit a warning. This warning
986 // is normally mapped to an error, but can be controlled with
Eli Friedman340a4e52009-06-04 23:03:07 +0000987 // -Wtypedef-redefinition. If either the original or the redefinition is
988 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner6d97e5e2010-03-01 20:59:53 +0000989 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman340a4e52009-06-04 23:03:07 +0000990 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
991 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattnerd0359af2009-04-27 01:46:12 +0000992 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Chris Lattner32b06752009-04-17 22:04:20 +0000994 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
995 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000996 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000997 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000998}
999
Chris Lattner6b6b5372008-06-26 18:38:35 +00001000/// DeclhasAttr - returns true if decl Declaration already has the target
1001/// attribute.
Mike Stump1eb44332009-09-09 15:08:12 +00001002static bool
Sean Huntcf807c42010-08-18 23:23:40 +00001003DeclHasAttr(const Decl *D, const Attr *A) {
1004 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1005 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1006 if ((*i)->getKind() == A->getKind()) {
1007 // FIXME: Don't hardcode this check
1008 if (OA && isa<OwnershipAttr>(*i))
1009 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
Chris Lattnerddee4232008-03-03 03:28:21 +00001010 return true;
Sean Huntcf807c42010-08-18 23:23:40 +00001011 }
Chris Lattnerddee4232008-03-03 03:28:21 +00001012
1013 return false;
1014}
1015
Sean Huntcf807c42010-08-18 23:23:40 +00001016/// MergeDeclAttributes - append attributes from the Old decl to the New one.
1017static void MergeDeclAttributes(Decl *New, Decl *Old, ASTContext &C) {
1018 if (!Old->hasAttrs())
1019 return;
1020 // Ensure that any moving of objects within the allocated map is done before
1021 // we process them.
1022 if (!New->hasAttrs())
1023 New->setAttrs(AttrVec());
Peter Collingbournea97d70b2011-01-21 02:08:36 +00001024 for (specific_attr_iterator<InheritableAttr>
1025 i = Old->specific_attr_begin<InheritableAttr>(),
1026 e = Old->specific_attr_end<InheritableAttr>(); i != e; ++i) {
1027 if (!DeclHasAttr(New, *i)) {
1028 InheritableAttr *NewAttr = cast<InheritableAttr>((*i)->clone(C));
Douglas Gregor9f9bf252009-04-28 06:37:30 +00001029 NewAttr->setInherited(true);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001030 New->addAttr(NewAttr);
Chris Lattnerddee4232008-03-03 03:28:21 +00001031 }
1032 }
1033}
1034
Dan Gohman3c46e8d2010-07-26 21:25:24 +00001035namespace {
1036
Douglas Gregorc8376562009-03-06 22:43:54 +00001037/// Used in MergeFunctionDecl to keep track of function parameters in
1038/// C.
1039struct GNUCompatibleParamWarning {
1040 ParmVarDecl *OldParm;
1041 ParmVarDecl *NewParm;
1042 QualType PromotedType;
1043};
1044
Dan Gohman3c46e8d2010-07-26 21:25:24 +00001045}
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001046
1047/// getSpecialMember - get the special member enum for a method.
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00001048Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001049 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Douglas Gregor9e9199d2009-12-22 00:34:07 +00001050 if (Ctor->isCopyConstructor())
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001051 return Sema::CXXCopyConstructor;
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00001052
1053 return Sema::CXXConstructor;
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001054 }
1055
1056 if (isa<CXXDestructorDecl>(MD))
1057 return Sema::CXXDestructor;
1058
Douglas Gregor3e9438b2010-09-27 22:37:28 +00001059 assert(MD->isCopyAssignmentOperator() &&
1060 "Must have copy assignment operator");
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001061 return Sema::CXXCopyAssignment;
1062}
1063
Sebastian Redl515ddd82010-06-09 21:17:41 +00001064/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisf3f8d2a2010-02-18 02:00:42 +00001065/// only extern inline functions can be redefined, and even then only in
1066/// GNU89 mode.
1067static bool canRedefineFunction(const FunctionDecl *FD,
1068 const LangOptions& LangOpts) {
1069 return (LangOpts.GNUMode && !LangOpts.C99 && !LangOpts.CPlusPlus &&
1070 FD->isInlineSpecified() &&
John McCalld931b082010-08-26 03:08:43 +00001071 FD->getStorageClass() == SC_Extern);
Charles Davisf3f8d2a2010-02-18 02:00:42 +00001072}
1073
Chris Lattner04421082008-04-08 04:40:51 +00001074/// MergeFunctionDecl - We just parsed a function 'New' from
1075/// declarator D which has the same name and scope as a previous
1076/// declaration 'Old'. Figure out how to resolve this situation,
1077/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001078///
1079/// In C++, New and Old must be declarations that are not
1080/// overloaded. Use IsOverload to determine whether New and Old are
1081/// overloaded, and to select the Old declaration that New should be
1082/// merged with.
Douglas Gregorcda9c672009-02-16 17:45:42 +00001083///
1084/// Returns true if there was an error, false otherwise.
1085bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001086 // Verify the old decl was also a function.
Douglas Gregore53060f2009-06-25 22:08:12 +00001087 FunctionDecl *Old = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001088 if (FunctionTemplateDecl *OldFunctionTemplate
Douglas Gregore53060f2009-06-25 22:08:12 +00001089 = dyn_cast<FunctionTemplateDecl>(OldD))
1090 Old = OldFunctionTemplate->getTemplatedDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001091 else
Douglas Gregore53060f2009-06-25 22:08:12 +00001092 Old = dyn_cast<FunctionDecl>(OldD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001093 if (!Old) {
John McCall41ce66f2009-12-10 19:51:03 +00001094 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
1095 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
1096 Diag(Shadow->getTargetDecl()->getLocation(),
1097 diag::note_using_decl_target);
1098 Diag(Shadow->getUsingDecl()->getLocation(),
1099 diag::note_using_decl) << 0;
1100 return true;
1101 }
1102
Chris Lattner5dc266a2008-11-20 06:13:02 +00001103 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00001104 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001105 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +00001106 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001107 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001108
1109 // Determine whether the previous declaration was a definition,
1110 // implicit declaration, or a declaration.
1111 diag::kind PrevDiag;
1112 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +00001113 PrevDiag = diag::note_previous_definition;
Douglas Gregorcda9c672009-02-16 17:45:42 +00001114 else if (Old->isImplicit())
1115 PrevDiag = diag::note_previous_implicit_declaration;
Mike Stump1eb44332009-09-09 15:08:12 +00001116 else
Chris Lattner5f4a6822008-11-23 23:12:31 +00001117 PrevDiag = diag::note_previous_declaration;
Mike Stump1eb44332009-09-09 15:08:12 +00001118
Chris Lattner8bcfc5b2008-04-06 23:10:54 +00001119 QualType OldQType = Context.getCanonicalType(Old->getType());
1120 QualType NewQType = Context.getCanonicalType(New->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001121
Charles Davisf3f8d2a2010-02-18 02:00:42 +00001122 // Don't complain about this if we're in GNU89 mode and the old function
1123 // is an extern inline function.
Douglas Gregor04495c82009-02-24 01:23:02 +00001124 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCalld931b082010-08-26 03:08:43 +00001125 New->getStorageClass() == SC_Static &&
1126 Old->getStorageClass() != SC_Static &&
Charles Davisf3f8d2a2010-02-18 02:00:42 +00001127 !canRedefineFunction(Old, getLangOptions())) {
Douglas Gregor04495c82009-02-24 01:23:02 +00001128 Diag(New->getLocation(), diag::err_static_non_static)
1129 << New;
1130 Diag(Old->getLocation(), PrevDiag);
1131 return true;
1132 }
1133
John McCallf82b4e82010-02-04 05:44:44 +00001134 // If a function is first declared with a calling convention, but is
1135 // later declared or defined without one, the second decl assumes the
1136 // calling convention of the first.
1137 //
1138 // For the new decl, we have to look at the NON-canonical type to tell the
1139 // difference between a function that really doesn't have a calling
1140 // convention and one that is declared cdecl. That's because in
1141 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
1142 // because it is the default calling convention.
1143 //
1144 // Note also that we DO NOT return at this point, because we still have
1145 // other tests to run.
John McCalle6a365d2010-12-19 02:44:49 +00001146 const FunctionType *OldType = cast<FunctionType>(OldQType);
John McCallf82b4e82010-02-04 05:44:44 +00001147 const FunctionType *NewType = New->getType()->getAs<FunctionType>();
John McCalle6a365d2010-12-19 02:44:49 +00001148 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
1149 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
1150 bool RequiresAdjustment = false;
Rafael Espindola264ba482010-03-30 20:24:48 +00001151 if (OldTypeInfo.getCC() != CC_Default &&
1152 NewTypeInfo.getCC() == CC_Default) {
John McCalle6a365d2010-12-19 02:44:49 +00001153 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
1154 RequiresAdjustment = true;
Rafael Espindola264ba482010-03-30 20:24:48 +00001155 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
1156 NewTypeInfo.getCC())) {
John McCallf82b4e82010-02-04 05:44:44 +00001157 // Calling conventions really aren't compatible, so complain.
John McCall04a67a62010-02-05 21:31:56 +00001158 Diag(New->getLocation(), diag::err_cconv_change)
Rafael Espindola264ba482010-03-30 20:24:48 +00001159 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
1160 << (OldTypeInfo.getCC() == CC_Default)
1161 << (OldTypeInfo.getCC() == CC_Default ? "" :
1162 FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
John McCall04a67a62010-02-05 21:31:56 +00001163 Diag(Old->getLocation(), diag::note_previous_declaration);
John McCallf82b4e82010-02-04 05:44:44 +00001164 return true;
1165 }
1166
John McCall04a67a62010-02-05 21:31:56 +00001167 // FIXME: diagnose the other way around?
John McCalle6a365d2010-12-19 02:44:49 +00001168 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
1169 NewTypeInfo = NewTypeInfo.withNoReturn(true);
1170 RequiresAdjustment = true;
John McCall04a67a62010-02-05 21:31:56 +00001171 }
1172
Douglas Gregord2c64902010-06-18 21:30:25 +00001173 // Merge regparm attribute.
John McCalle6a365d2010-12-19 02:44:49 +00001174 if (OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
1175 if (NewTypeInfo.getRegParm()) {
Douglas Gregord2c64902010-06-18 21:30:25 +00001176 Diag(New->getLocation(), diag::err_regparm_mismatch)
1177 << NewType->getRegParmType()
1178 << OldType->getRegParmType();
1179 Diag(Old->getLocation(), diag::note_previous_declaration);
1180 return true;
1181 }
John McCalle6a365d2010-12-19 02:44:49 +00001182
1183 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
1184 RequiresAdjustment = true;
1185 }
1186
1187 if (RequiresAdjustment) {
1188 NewType = Context.adjustFunctionType(NewType, NewTypeInfo);
1189 New->setType(QualType(NewType, 0));
1190 NewQType = Context.getCanonicalType(New->getType());
Douglas Gregord2c64902010-06-18 21:30:25 +00001191 }
1192
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001193 if (getLangOptions().CPlusPlus) {
1194 // (C++98 13.1p2):
1195 // Certain function declarations cannot be overloaded:
Mike Stump1eb44332009-09-09 15:08:12 +00001196 // -- Function declarations that differ only in the return type
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001197 // cannot be overloaded.
John McCalle6a365d2010-12-19 02:44:49 +00001198 QualType OldReturnType = OldType->getResultType();
1199 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
Fariborz Jahanian2390a722010-05-19 21:37:30 +00001200 QualType ResQT;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001201 if (OldReturnType != NewReturnType) {
Fariborz Jahanian2390a722010-05-19 21:37:30 +00001202 if (NewReturnType->isObjCObjectPointerType()
1203 && OldReturnType->isObjCObjectPointerType())
1204 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
1205 if (ResQT.isNull()) {
Argyrios Kyrtzidis1de34dd2011-02-05 05:54:49 +00001206 if (New->isCXXClassMember() && New->isOutOfLine())
1207 Diag(New->getLocation(),
1208 diag::err_member_def_does_not_match_ret_type) << New;
1209 else
1210 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00001211 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1212 return true;
1213 }
1214 else
1215 NewQType = ResQT;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001216 }
1217
1218 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
John McCall3d043362010-04-13 07:45:41 +00001219 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001220 if (OldMethod && NewMethod) {
John McCall3d043362010-04-13 07:45:41 +00001221 // Preserve triviality.
1222 NewMethod->setTrivial(OldMethod->isTrivial());
1223
1224 bool isFriend = NewMethod->getFriendObjectKind();
1225
1226 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord()) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001227 // -- Member function declarations with the same name and the
1228 // same parameter types cannot be overloaded if any of them
1229 // is a static member function declaration.
1230 if (OldMethod->isStatic() || NewMethod->isStatic()) {
1231 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
1232 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1233 return true;
1234 }
1235
1236 // C++ [class.mem]p1:
1237 // [...] A member shall not be declared twice in the
1238 // member-specification, except that a nested class or member
1239 // class template can be declared and then later defined.
1240 unsigned NewDiag;
1241 if (isa<CXXConstructorDecl>(OldMethod))
1242 NewDiag = diag::err_constructor_redeclared;
1243 else if (isa<CXXDestructorDecl>(NewMethod))
1244 NewDiag = diag::err_destructor_redeclared;
1245 else if (isa<CXXConversionDecl>(NewMethod))
1246 NewDiag = diag::err_conv_function_redeclared;
1247 else
1248 NewDiag = diag::err_member_redeclared;
1249
1250 Diag(New->getLocation(), NewDiag);
Douglas Gregor3e41d602009-02-13 23:20:09 +00001251 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
John McCall3d043362010-04-13 07:45:41 +00001252
1253 // Complain if this is an explicit declaration of a special
1254 // member that was initially declared implicitly.
1255 //
1256 // As an exception, it's okay to befriend such methods in order
1257 // to permit the implicit constructor/destructor/operator calls.
1258 } else if (OldMethod->isImplicit()) {
1259 if (isFriend) {
1260 NewMethod->setImplicit();
1261 } else {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001262 Diag(NewMethod->getLocation(),
1263 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00001264 << New << getSpecialMember(OldMethod);
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001265 return true;
1266 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001267 }
1268 }
1269
1270 // (C++98 8.3.5p3):
1271 // All declarations for a function shall agree exactly in both the
1272 // return type and the parameter-type-list.
John McCalle6a365d2010-12-19 02:44:49 +00001273 // We also want to respect all the extended bits except noreturn.
1274
1275 // noreturn should now match unless the old type info didn't have it.
1276 QualType OldQTypeForComparison = OldQType;
1277 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
1278 assert(OldQType == QualType(OldType, 0));
1279 const FunctionType *OldTypeForComparison
1280 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
1281 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
1282 assert(OldQTypeForComparison.isCanonical());
1283 }
1284
1285 if (OldQTypeForComparison == NewQType)
Douglas Gregor04495c82009-02-24 01:23:02 +00001286 return MergeCompatibleFunctionDecls(New, Old);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001287
1288 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +00001289 }
Chris Lattner04421082008-04-08 04:40:51 +00001290
1291 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001292 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +00001293 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +00001294 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall183700f2009-09-21 23:43:11 +00001295 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
1296 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001297 const FunctionProtoType *OldProto = 0;
1298 if (isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregorc8376562009-03-06 22:43:54 +00001299 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregor68719812009-02-16 18:20:44 +00001300 // The old declaration provided a function prototype, but the
1301 // new declaration does not. Merge in the prototype.
Sebastian Redl465226e2009-05-27 22:11:52 +00001302 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Douglas Gregor68719812009-02-16 18:20:44 +00001303 llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
1304 OldProto->arg_type_end());
1305 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001306 ParamTypes.data(), ParamTypes.size(),
John McCalle23cf432010-12-14 08:05:40 +00001307 OldProto->getExtProtoInfo());
Douglas Gregor68719812009-02-16 18:20:44 +00001308 New->setType(NewQType);
Anders Carlssona75e8532009-05-14 21:46:00 +00001309 New->setHasInheritedPrototype();
Douglas Gregor450da982009-02-16 20:58:07 +00001310
1311 // Synthesize a parameter for each argument type.
1312 llvm::SmallVector<ParmVarDecl*, 16> Params;
Mike Stump1eb44332009-09-09 15:08:12 +00001313 for (FunctionProtoType::arg_type_iterator
1314 ParamType = OldProto->arg_type_begin(),
Douglas Gregor450da982009-02-16 20:58:07 +00001315 ParamEnd = OldProto->arg_type_end();
1316 ParamType != ParamEnd; ++ParamType) {
1317 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
1318 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00001319 *ParamType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00001320 SC_None, SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001321 0);
Douglas Gregor450da982009-02-16 20:58:07 +00001322 Param->setImplicit();
1323 Params.push_back(Param);
1324 }
1325
Douglas Gregor838db382010-02-11 01:19:42 +00001326 New->setParams(Params.data(), Params.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001327 }
Douglas Gregor68719812009-02-16 18:20:44 +00001328
Douglas Gregor04495c82009-02-24 01:23:02 +00001329 return MergeCompatibleFunctionDecls(New, Old);
Chris Lattner04421082008-04-08 04:40:51 +00001330 }
Chris Lattnere3995fe2007-11-06 06:07:26 +00001331
Douglas Gregorc8376562009-03-06 22:43:54 +00001332 // GNU C permits a K&R definition to follow a prototype declaration
1333 // if the declared types of the parameters in the K&R definition
1334 // match the types in the prototype declaration, even when the
1335 // promoted types of the parameters from the K&R definition differ
1336 // from the types in the prototype. GCC then keeps the types from
1337 // the prototype.
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00001338 //
1339 // If a variadic prototype is followed by a non-variadic K&R definition,
1340 // the K&R definition becomes variadic. This is sort of an edge case, but
1341 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
1342 // C99 6.9.1p8.
Douglas Gregorc8376562009-03-06 22:43:54 +00001343 if (!getLangOptions().CPlusPlus &&
Douglas Gregorc8376562009-03-06 22:43:54 +00001344 Old->hasPrototype() && !New->hasPrototype() &&
John McCall183700f2009-09-21 23:43:11 +00001345 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregorc8376562009-03-06 22:43:54 +00001346 Old->getNumParams() == New->getNumParams()) {
1347 llvm::SmallVector<QualType, 16> ArgTypes;
1348 llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump1eb44332009-09-09 15:08:12 +00001349 const FunctionProtoType *OldProto
John McCall183700f2009-09-21 23:43:11 +00001350 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001351 const FunctionProtoType *NewProto
John McCall183700f2009-09-21 23:43:11 +00001352 = New->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001353
Douglas Gregorc8376562009-03-06 22:43:54 +00001354 // Determine whether this is the GNU C extension.
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00001355 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
1356 NewProto->getResultType());
1357 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump1eb44332009-09-09 15:08:12 +00001358 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00001359 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregorc8376562009-03-06 22:43:54 +00001360 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
1361 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump1eb44332009-09-09 15:08:12 +00001362 if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregorc8376562009-03-06 22:43:54 +00001363 NewProto->getArgType(Idx))) {
1364 ArgTypes.push_back(NewParm->getType());
1365 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor447234d2010-07-29 15:18:02 +00001366 NewParm->getType(),
1367 /*CompareUnqualified=*/true)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001368 GNUCompatibleParamWarning Warn
Douglas Gregorc8376562009-03-06 22:43:54 +00001369 = { OldParm, NewParm, NewProto->getArgType(Idx) };
1370 Warnings.push_back(Warn);
1371 ArgTypes.push_back(NewParm->getType());
1372 } else
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00001373 LooseCompatible = false;
Douglas Gregorc8376562009-03-06 22:43:54 +00001374 }
1375
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00001376 if (LooseCompatible) {
Douglas Gregorc8376562009-03-06 22:43:54 +00001377 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
1378 Diag(Warnings[Warn].NewParm->getLocation(),
1379 diag::ext_param_promoted_not_compatible_with_prototype)
1380 << Warnings[Warn].PromotedType
1381 << Warnings[Warn].OldParm->getType();
Douglas Gregor447234d2010-07-29 15:18:02 +00001382 if (Warnings[Warn].OldParm->getLocation().isValid())
1383 Diag(Warnings[Warn].OldParm->getLocation(),
1384 diag::note_previous_declaration);
Douglas Gregorc8376562009-03-06 22:43:54 +00001385 }
1386
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00001387 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
1388 ArgTypes.size(),
John McCalle23cf432010-12-14 08:05:40 +00001389 OldProto->getExtProtoInfo()));
Douglas Gregorc8376562009-03-06 22:43:54 +00001390 return MergeCompatibleFunctionDecls(New, Old);
1391 }
1392
1393 // Fall through to diagnose conflicting types.
1394 }
1395
Steve Naroff837618c2008-01-16 15:01:34 +00001396 // A function that has already been declared has been redeclared or defined
1397 // with a different type- show appropriate diagnostic
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001398 if (unsigned BuiltinID = Old->getBuiltinID()) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00001399 // The user has declared a builtin function with an incompatible
1400 // signature.
1401 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
1402 // The function the user is redeclaring is a library-defined
1403 // function like 'malloc' or 'printf'. Warn about the
Douglas Gregor374e1562009-03-23 17:47:24 +00001404 // redeclaration, then pretend that we don't know about this
1405 // library built-in.
Douglas Gregorcda9c672009-02-16 17:45:42 +00001406 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
1407 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
1408 << Old << Old->getType();
Douglas Gregor374e1562009-03-23 17:47:24 +00001409 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
1410 Old->setInvalidDecl();
1411 return false;
Douglas Gregorcda9c672009-02-16 17:45:42 +00001412 }
Steve Naroff837618c2008-01-16 15:01:34 +00001413
Douglas Gregorcda9c672009-02-16 17:45:42 +00001414 PrevDiag = diag::note_previous_builtin_declaration;
1415 }
1416
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001417 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregor3e41d602009-02-13 23:20:09 +00001418 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregorcda9c672009-02-16 17:45:42 +00001419 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001420}
1421
Douglas Gregor04495c82009-02-24 01:23:02 +00001422/// \brief Completes the merge of two function declarations that are
Mike Stump1eb44332009-09-09 15:08:12 +00001423/// known to be compatible.
Douglas Gregor04495c82009-02-24 01:23:02 +00001424///
1425/// This routine handles the merging of attributes and other
1426/// properties of function declarations form the old declaration to
1427/// the new declaration, once we know that New is in fact a
1428/// redeclaration of Old.
1429///
1430/// \returns false
1431bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
1432 // Merge the attributes
Sean Huntcf807c42010-08-18 23:23:40 +00001433 MergeDeclAttributes(New, Old, Context);
Douglas Gregor04495c82009-02-24 01:23:02 +00001434
1435 // Merge the storage class.
John McCalld931b082010-08-26 03:08:43 +00001436 if (Old->getStorageClass() != SC_Extern &&
1437 Old->getStorageClass() != SC_None)
Douglas Gregor9f9bf252009-04-28 06:37:30 +00001438 New->setStorageClass(Old->getStorageClass());
Douglas Gregor04495c82009-02-24 01:23:02 +00001439
Douglas Gregor04495c82009-02-24 01:23:02 +00001440 // Merge "pure" flag.
1441 if (Old->isPure())
1442 New->setPure();
1443
1444 // Merge the "deleted" flag.
1445 if (Old->isDeleted())
1446 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001447
Douglas Gregor04495c82009-02-24 01:23:02 +00001448 if (getLangOptions().CPlusPlus)
1449 return MergeCXXFunctionDecl(New, Old);
1450
1451 return false;
1452}
1453
Reid Spencer5f016e22007-07-11 17:01:13 +00001454/// MergeVarDecl - We just parsed a variable 'New' which has the same name
1455/// and scope as a previous declaration 'Old'. Figure out how to resolve this
1456/// situation, merging decls or emitting diagnostics as appropriate.
1457///
Mike Stump1eb44332009-09-09 15:08:12 +00001458/// Tentative definition rules (C99 6.9.2p2) are checked by
1459/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001460/// definitions here, since the initializer hasn't been attached.
Mike Stump1eb44332009-09-09 15:08:12 +00001461///
John McCall68263142009-11-18 22:49:29 +00001462void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
1463 // If the new decl is already invalid, don't do any other checking.
1464 if (New->isInvalidDecl())
1465 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001466
Reid Spencer5f016e22007-07-11 17:01:13 +00001467 // Verify the old decl was also a variable.
John McCall68263142009-11-18 22:49:29 +00001468 VarDecl *Old = 0;
1469 if (!Previous.isSingleResult() ||
1470 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001471 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00001472 << New->getDeclName();
John McCall68263142009-11-18 22:49:29 +00001473 Diag(Previous.getRepresentativeDecl()->getLocation(),
1474 diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001475 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001476 }
Chris Lattnerddee4232008-03-03 03:28:21 +00001477
Douglas Gregor7f6ff022010-08-30 14:32:14 +00001478 // C++ [class.mem]p1:
1479 // A member shall not be declared twice in the member-specification [...]
1480 //
1481 // Here, we need only consider static data members.
1482 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
1483 Diag(New->getLocation(), diag::err_duplicate_member)
1484 << New->getIdentifier();
1485 Diag(Old->getLocation(), diag::note_previous_declaration);
1486 New->setInvalidDecl();
1487 }
1488
Sean Huntcf807c42010-08-18 23:23:40 +00001489 MergeDeclAttributes(New, Old, Context);
Chris Lattnerddee4232008-03-03 03:28:21 +00001490
Eli Friedman13ca96a2009-01-24 23:49:55 +00001491 // Merge the types
Eli Friedman88d936b2009-05-16 13:54:38 +00001492 QualType MergedT;
1493 if (getLangOptions().CPlusPlus) {
1494 if (Context.hasSameType(New->getType(), Old->getType()))
1495 MergedT = New->getType();
Eli Friedman153c33e2009-12-10 08:54:47 +00001496 // C++ [basic.link]p10:
1497 // [...] the types specified by all declarations referring to a given
1498 // object or function shall be identical, except that declarations for an
1499 // array object can specify array types that differ by the presence or
1500 // absence of a major array bound (8.3.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001501 else if (Old->getType()->isIncompleteArrayType() &&
Douglas Gregor8dfb7ec2009-09-09 06:04:29 +00001502 New->getType()->isArrayType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001503 CanQual<ArrayType> OldArray
Douglas Gregor8dfb7ec2009-09-09 06:04:29 +00001504 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001505 CanQual<ArrayType> NewArray
Douglas Gregor8dfb7ec2009-09-09 06:04:29 +00001506 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1507 if (OldArray->getElementType() == NewArray->getElementType())
1508 MergedT = New->getType();
Eli Friedman153c33e2009-12-10 08:54:47 +00001509 } else if (Old->getType()->isArrayType() &&
1510 New->getType()->isIncompleteArrayType()) {
1511 CanQual<ArrayType> OldArray
1512 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1513 CanQual<ArrayType> NewArray
1514 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1515 if (OldArray->getElementType() == NewArray->getElementType())
1516 MergedT = Old->getType();
Fariborz Jahanian2390a722010-05-19 21:37:30 +00001517 } else if (New->getType()->isObjCObjectPointerType()
1518 && Old->getType()->isObjCObjectPointerType()) {
1519 MergedT = Context.mergeObjCGCQualifiers(New->getType(), Old->getType());
Douglas Gregor8dfb7ec2009-09-09 06:04:29 +00001520 }
Eli Friedman88d936b2009-05-16 13:54:38 +00001521 } else {
1522 MergedT = Context.mergeTypes(New->getType(), Old->getType());
1523 }
Eli Friedman13ca96a2009-01-24 23:49:55 +00001524 if (MergedT.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001525 Diag(New->getLocation(), diag::err_redefinition_different_type)
Douglas Gregor6037fcb2009-01-09 19:42:16 +00001526 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001527 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001528 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001529 }
Eli Friedman13ca96a2009-01-24 23:49:55 +00001530 New->setType(MergedT);
Douglas Gregor656de632009-03-11 23:52:16 +00001531
Steve Naroffb7b032e2008-01-30 00:44:01 +00001532 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
John McCalld931b082010-08-26 03:08:43 +00001533 if (New->getStorageClass() == SC_Static &&
1534 (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001535 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001536 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001537 return New->setInvalidDecl();
Steve Naroffb7b032e2008-01-30 00:44:01 +00001538 }
Mike Stump1eb44332009-09-09 15:08:12 +00001539 // C99 6.2.2p4:
Douglas Gregor5ef122e2009-03-19 22:01:50 +00001540 // For an identifier declared with the storage-class specifier
1541 // extern in a scope in which a prior declaration of that
1542 // identifier is visible,23) if the prior declaration specifies
1543 // internal or external linkage, the linkage of the identifier at
1544 // the later declaration is the same as the linkage specified at
1545 // the prior declaration. If no prior declaration is visible, or
1546 // if the prior declaration specifies no linkage, then the
1547 // identifier has external linkage.
Douglas Gregor38179b22009-03-23 16:17:01 +00001548 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor5ef122e2009-03-19 22:01:50 +00001549 /* Okay */;
John McCalld931b082010-08-26 03:08:43 +00001550 else if (New->getStorageClass() != SC_Static &&
1551 Old->getStorageClass() == SC_Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001552 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001553 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001554 return New->setInvalidDecl();
Steve Naroffb7b032e2008-01-30 00:44:01 +00001555 }
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00001556
Argyrios Kyrtzidis6684d852011-01-31 07:04:46 +00001557 // Check if extern is followed by non-extern and vice-versa.
1558 if (New->hasExternalStorage() &&
1559 !Old->hasLinkage() && Old->isLocalVarDecl()) {
1560 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
1561 Diag(Old->getLocation(), diag::note_previous_definition);
1562 return New->setInvalidDecl();
1563 }
1564 if (Old->hasExternalStorage() &&
1565 !New->hasLinkage() && New->isLocalVarDecl()) {
1566 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
1567 Diag(Old->getLocation(), diag::note_previous_definition);
1568 return New->setInvalidDecl();
1569 }
1570
Steve Naroff094cefb2008-09-17 14:05:40 +00001571 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00001573 // FIXME: The test for external storage here seems wrong? We still
1574 // need to check for mismatches.
1575 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor656de632009-03-11 23:52:16 +00001576 // Don't complain about out-of-line definitions of static members.
1577 !(Old->getLexicalDeclContext()->isRecord() &&
1578 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattner08631c52008-11-23 21:45:46 +00001579 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001580 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001581 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 }
Douglas Gregor275a3692009-03-10 23:43:53 +00001583
Eli Friedman63054b32009-04-19 20:27:55 +00001584 if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
1585 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
1586 Diag(Old->getLocation(), diag::note_previous_definition);
1587 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
1588 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
1589 Diag(Old->getLocation(), diag::note_previous_definition);
1590 }
1591
Sebastian Redl4cae1b32010-02-02 18:35:11 +00001592 // C++ doesn't have tentative definitions, so go right ahead and check here.
1593 const VarDecl *Def;
Sebastian Redl6c048a92010-02-03 02:08:48 +00001594 if (getLangOptions().CPlusPlus &&
1595 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redl4cae1b32010-02-02 18:35:11 +00001596 (Def = Old->getDefinition())) {
1597 Diag(New->getLocation(), diag::err_redefinition)
1598 << New->getDeclName();
1599 Diag(Def->getLocation(), diag::note_previous_definition);
1600 New->setInvalidDecl();
1601 return;
1602 }
Fariborz Jahanianfba9e8f2010-06-25 00:05:45 +00001603 // c99 6.2.2 P4.
1604 // For an identifier declared with the storage-class specifier extern in a
1605 // scope in which a prior declaration of that identifier is visible, if
1606 // the prior declaration specifies internal or external linkage, the linkage
1607 // of the identifier at the later declaration is the same as the linkage
1608 // specified at the prior declaration.
1609 // FIXME. revisit this code.
Fariborz Jahanian2bf6d7b2010-06-21 16:08:37 +00001610 if (New->hasExternalStorage() &&
Fariborz Jahanian7d99e982010-06-24 18:50:41 +00001611 Old->getLinkage() == InternalLinkage &&
1612 New->getDeclContext() == Old->getDeclContext())
Fariborz Jahanian2bf6d7b2010-06-21 16:08:37 +00001613 New->setStorageClass(Old->getStorageClass());
1614
Douglas Gregor275a3692009-03-10 23:43:53 +00001615 // Keep a chain of previous declarations.
1616 New->setPreviousDeclaration(Old);
John McCall46460a62010-01-20 21:53:11 +00001617
1618 // Inherit access appropriately.
1619 New->setAccess(Old->getAccess());
Reid Spencer5f016e22007-07-11 17:01:13 +00001620}
1621
1622/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
1623/// no declarator (e.g. "struct foo;") is parsed.
John McCalld226f652010-08-21 09:40:31 +00001624Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1625 DeclSpec &DS) {
Eli Friedmand2968362009-04-09 21:26:42 +00001626 // FIXME: Error on inline/virtual/explicit
Eli Friedman63054b32009-04-19 20:27:55 +00001627 // FIXME: Warn on useless __thread
Eli Friedmand2968362009-04-09 21:26:42 +00001628 // FIXME: Warn on useless const/volatile
1629 // FIXME: Warn on useless static/extern/typedef/private_extern/mutable
1630 // FIXME: Warn on useless attributes
John McCalle3af0232009-10-07 23:34:25 +00001631 Decl *TagD = 0;
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001632 TagDecl *Tag = 0;
1633 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
1634 DS.getTypeSpecType() == DeclSpec::TST_struct ||
1635 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00001636 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallb3d87482010-08-24 05:47:05 +00001637 TagD = DS.getRepAsDecl();
John McCalle3af0232009-10-07 23:34:25 +00001638
1639 if (!TagD) // We probably had an error
John McCalld226f652010-08-21 09:40:31 +00001640 return 0;
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00001641
John McCall67d1a672009-08-06 02:15:43 +00001642 // Note that the above type specs guarantee that the
1643 // type rep is a Decl, whereas in many of the others
1644 // it's a Type.
John McCalle3af0232009-10-07 23:34:25 +00001645 Tag = dyn_cast<TagDecl>(TagD);
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00001646 }
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001647
Nuno Lopes0a8bab02009-12-17 11:35:26 +00001648 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1649 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
1650 // or incomplete types shall not be restrict-qualified."
1651 if (TypeQuals & DeclSpec::TQ_restrict)
1652 Diag(DS.getRestrictSpecLoc(),
1653 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
1654 << DS.getSourceRange();
1655 }
1656
Douglas Gregord85bea22009-09-26 06:47:28 +00001657 if (DS.isFriendSpecified()) {
John McCall9a34edb2010-10-19 01:40:49 +00001658 // If we're dealing with a decl but not a TagDecl, assume that
1659 // whatever routines created it handled the friendship aspect.
1660 if (TagD && !Tag)
John McCalld226f652010-08-21 09:40:31 +00001661 return 0;
John McCalle3af0232009-10-07 23:34:25 +00001662 return ActOnFriendTypeDecl(S, DS, MultiTemplateParamsArg(*this, 0, 0));
Douglas Gregord85bea22009-09-26 06:47:28 +00001663 }
1664
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001665 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCall7f040a92010-12-24 02:08:15 +00001666 ProcessDeclAttributeList(S, Record, DS.getAttributes().getList());
Chris Lattnerd451f832009-10-25 22:21:57 +00001667
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001668 if (!Record->getDeclName() && Record->isDefinition() &&
Douglas Gregora71c1292009-03-06 23:06:59 +00001669 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
1670 if (getLangOptions().CPlusPlus ||
1671 Record->getDeclContext()->isRecord())
John McCallaec03712010-05-21 20:45:30 +00001672 return BuildAnonymousStructOrUnion(S, DS, AS, Record);
Douglas Gregora71c1292009-03-06 23:06:59 +00001673
Douglas Gregorcb821d02010-04-08 21:33:23 +00001674 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
Douglas Gregora71c1292009-03-06 23:06:59 +00001675 << DS.getSourceRange();
1676 }
Francois Pichet8e161ed2010-11-23 06:07:27 +00001677 }
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001678
Francois Pichet8e161ed2010-11-23 06:07:27 +00001679 // Check for Microsoft C extension: anonymous struct.
1680 if (getLangOptions().Microsoft && !getLangOptions().CPlusPlus &&
1681 CurContext->isRecord() &&
1682 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
1683 // Handle 2 kinds of anonymous struct:
1684 // struct STRUCT;
1685 // and
1686 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
1687 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
1688 if ((Record && Record->getDeclName() && !Record->isDefinition()) ||
1689 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
1690 DS.getRepAsType().get()->isStructureType())) {
1691 Diag(DS.getSourceRange().getBegin(), diag::ext_ms_anonymous_struct)
1692 << DS.getSourceRange();
1693 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
1694 }
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001695 }
Douglas Gregord85bea22009-09-26 06:47:28 +00001696
Douglas Gregora131d0f2010-07-13 06:24:26 +00001697 if (getLangOptions().CPlusPlus &&
1698 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
1699 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
1700 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
1701 !Enum->getIdentifier() && !Enum->isInvalidDecl())
1702 Diag(Enum->getLocation(), diag::ext_no_declarators)
1703 << DS.getSourceRange();
1704
Mike Stump1eb44332009-09-09 15:08:12 +00001705 if (!DS.isMissingDeclaratorOk() &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00001706 DS.getTypeSpecType() != DeclSpec::TST_error) {
Douglas Gregor21282df2009-01-22 16:23:54 +00001707 // Warn about typedefs of enums without names, since this is an
Douglas Gregora0ebd602010-07-16 15:40:40 +00001708 // extension in both Microsoft and GNU.
Douglas Gregor8158f692009-01-17 02:55:50 +00001709 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
1710 Tag && isa<EnumDecl>(Tag)) {
Douglas Gregora0ebd602010-07-16 15:40:40 +00001711 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
1712 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00001713 return Tag;
Douglas Gregoree159c12009-01-13 23:10:51 +00001714 }
1715
Douglas Gregorcb821d02010-04-08 21:33:23 +00001716 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
Sebastian Redla4ed0d82008-12-28 15:28:59 +00001717 << DS.getSourceRange();
Sebastian Redla4ed0d82008-12-28 15:28:59 +00001718 }
Mike Stump1eb44332009-09-09 15:08:12 +00001719
John McCalld226f652010-08-21 09:40:31 +00001720 return TagD;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001721}
1722
Fariborz Jahanianc5be7b02010-09-28 20:42:35 +00001723/// ActOnVlaStmt - This rouine if finds a vla expression in a decl spec.
1724/// builds a statement for it and returns it so it is evaluated.
1725StmtResult Sema::ActOnVlaStmt(const DeclSpec &DS) {
1726 StmtResult R;
1727 if (DS.getTypeSpecType() == DeclSpec::TST_typeofExpr) {
1728 Expr *Exp = DS.getRepAsExpr();
1729 QualType Ty = Exp->getType();
1730 if (Ty->isPointerType()) {
1731 do
1732 Ty = Ty->getAs<PointerType>()->getPointeeType();
1733 while (Ty->isPointerType());
1734 }
1735 if (Ty->isVariableArrayType()) {
1736 R = ActOnExprStmt(MakeFullExpr(Exp));
1737 }
1738 }
1739 return R;
1740}
1741
John McCall1d7c5282009-12-18 10:40:03 +00001742/// We are trying to inject an anonymous member into the given scope;
John McCall68263142009-11-18 22:49:29 +00001743/// check if there's an existing declaration that can't be overloaded.
1744///
1745/// \return true if this is a forbidden redeclaration
John McCall1d7c5282009-12-18 10:40:03 +00001746static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
1747 Scope *S,
Fariborz Jahanian588a4ad2010-01-22 18:30:17 +00001748 DeclContext *Owner,
John McCall1d7c5282009-12-18 10:40:03 +00001749 DeclarationName Name,
1750 SourceLocation NameLoc,
1751 unsigned diagnostic) {
1752 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
1753 Sema::ForRedeclaration);
1754 if (!SemaRef.LookupName(R, S)) return false;
John McCall68263142009-11-18 22:49:29 +00001755
John McCall1d7c5282009-12-18 10:40:03 +00001756 if (R.getAsSingle<TagDecl>())
John McCall68263142009-11-18 22:49:29 +00001757 return false;
1758
1759 // Pick a representative declaration.
John McCall1d7c5282009-12-18 10:40:03 +00001760 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidis2b642392010-09-23 14:26:01 +00001761 assert(PrevDecl && "Expected a non-null Decl");
1762
1763 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
1764 return false;
John McCall68263142009-11-18 22:49:29 +00001765
John McCall1d7c5282009-12-18 10:40:03 +00001766 SemaRef.Diag(NameLoc, diagnostic) << Name;
1767 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall68263142009-11-18 22:49:29 +00001768
1769 return true;
1770}
1771
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001772/// InjectAnonymousStructOrUnionMembers - Inject the members of the
1773/// anonymous struct or union AnonRecord into the owning context Owner
1774/// and scope S. This routine will be invoked just after we realize
1775/// that an unnamed union or struct is actually an anonymous union or
1776/// struct, e.g.,
1777///
1778/// @code
1779/// union {
1780/// int i;
1781/// float f;
1782/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
1783/// // f into the surrounding scope.x
1784/// @endcode
1785///
1786/// This routine is recursive, injecting the names of nested anonymous
1787/// structs/unions into the owning context and scope as well.
John McCallaec03712010-05-21 20:45:30 +00001788static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
1789 DeclContext *Owner,
1790 RecordDecl *AnonRecord,
Francois Pichet87c2e122010-11-21 06:08:52 +00001791 AccessSpecifier AS,
Francois Pichet8e161ed2010-11-23 06:07:27 +00001792 llvm::SmallVector<NamedDecl*, 2> &Chaining,
1793 bool MSAnonStruct) {
John McCall68263142009-11-18 22:49:29 +00001794 unsigned diagKind
1795 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
1796 : diag::err_anonymous_struct_member_redecl;
1797
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001798 bool Invalid = false;
Francois Pichet8e161ed2010-11-23 06:07:27 +00001799
1800 // Look every FieldDecl and IndirectFieldDecl with a name.
1801 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
1802 DEnd = AnonRecord->decls_end();
1803 D != DEnd; ++D) {
1804 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
1805 cast<NamedDecl>(*D)->getDeclName()) {
1806 ValueDecl *VD = cast<ValueDecl>(*D);
1807 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
1808 VD->getLocation(), diagKind)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001809 // C++ [class.union]p2:
1810 // The names of the members of an anonymous union shall be
1811 // distinct from the names of any other entity in the
1812 // scope in which the anonymous union is declared.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001813 Invalid = true;
1814 } else {
1815 // C++ [class.union]p2:
1816 // For the purpose of name lookup, after the anonymous union
1817 // definition, the members of the anonymous union are
1818 // considered to have been defined in the scope in which the
1819 // anonymous union is declared.
Francois Pichet8e161ed2010-11-23 06:07:27 +00001820 unsigned OldChainingSize = Chaining.size();
1821 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
1822 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
1823 PE = IF->chain_end(); PI != PE; ++PI)
1824 Chaining.push_back(*PI);
1825 else
1826 Chaining.push_back(VD);
1827
Francois Pichet87c2e122010-11-21 06:08:52 +00001828 assert(Chaining.size() >= 2);
1829 NamedDecl **NamedChain =
1830 new (SemaRef.Context)NamedDecl*[Chaining.size()];
1831 for (unsigned i = 0; i < Chaining.size(); i++)
1832 NamedChain[i] = Chaining[i];
1833
1834 IndirectFieldDecl* IndirectField =
Francois Pichet8e161ed2010-11-23 06:07:27 +00001835 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
1836 VD->getIdentifier(), VD->getType(),
Francois Pichet87c2e122010-11-21 06:08:52 +00001837 NamedChain, Chaining.size());
1838
1839 IndirectField->setAccess(AS);
1840 IndirectField->setImplicit();
1841 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallaec03712010-05-21 20:45:30 +00001842
1843 // That includes picking up the appropriate access specifier.
Francois Pichet8e161ed2010-11-23 06:07:27 +00001844 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet87c2e122010-11-21 06:08:52 +00001845
Francois Pichet8e161ed2010-11-23 06:07:27 +00001846 Chaining.resize(OldChainingSize);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001847 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001848 }
1849 }
1850
1851 return Invalid;
1852}
1853
Douglas Gregor16573fa2010-04-19 22:54:31 +00001854/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
1855/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCalld931b082010-08-26 03:08:43 +00001856/// illegal input values are mapped to SC_None.
1857static StorageClass
Abramo Bagnara35f9a192010-07-30 16:47:02 +00001858StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
Douglas Gregor16573fa2010-04-19 22:54:31 +00001859 switch (StorageClassSpec) {
John McCalld931b082010-08-26 03:08:43 +00001860 case DeclSpec::SCS_unspecified: return SC_None;
1861 case DeclSpec::SCS_extern: return SC_Extern;
1862 case DeclSpec::SCS_static: return SC_Static;
1863 case DeclSpec::SCS_auto: return SC_Auto;
1864 case DeclSpec::SCS_register: return SC_Register;
1865 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregor16573fa2010-04-19 22:54:31 +00001866 // Illegal SCSs map to None: error reporting is up to the caller.
1867 case DeclSpec::SCS_mutable: // Fall through.
John McCalld931b082010-08-26 03:08:43 +00001868 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregor16573fa2010-04-19 22:54:31 +00001869 }
1870 llvm_unreachable("unknown storage class specifier");
1871}
1872
1873/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
John McCalld931b082010-08-26 03:08:43 +00001874/// a StorageClass. Any error reporting is up to the caller:
1875/// illegal input values are mapped to SC_None.
1876static StorageClass
Abramo Bagnara35f9a192010-07-30 16:47:02 +00001877StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
Douglas Gregor16573fa2010-04-19 22:54:31 +00001878 switch (StorageClassSpec) {
John McCalld931b082010-08-26 03:08:43 +00001879 case DeclSpec::SCS_unspecified: return SC_None;
1880 case DeclSpec::SCS_extern: return SC_Extern;
1881 case DeclSpec::SCS_static: return SC_Static;
1882 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregor16573fa2010-04-19 22:54:31 +00001883 // Illegal SCSs map to None: error reporting is up to the caller.
1884 case DeclSpec::SCS_auto: // Fall through.
1885 case DeclSpec::SCS_mutable: // Fall through.
1886 case DeclSpec::SCS_register: // Fall through.
John McCalld931b082010-08-26 03:08:43 +00001887 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregor16573fa2010-04-19 22:54:31 +00001888 }
1889 llvm_unreachable("unknown storage class specifier");
1890}
1891
Francois Pichet8e161ed2010-11-23 06:07:27 +00001892/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001893/// anonymous structure or union. Anonymous unions are a C++ feature
1894/// (C++ [class.union]) and a GNU C extension; anonymous structures
Mike Stump1eb44332009-09-09 15:08:12 +00001895/// are a GNU C and GNU C++ extension.
John McCalld226f652010-08-21 09:40:31 +00001896Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1897 AccessSpecifier AS,
1898 RecordDecl *Record) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001899 DeclContext *Owner = Record->getDeclContext();
1900
1901 // Diagnose whether this anonymous struct/union is an extension.
1902 if (Record->isUnion() && !getLangOptions().CPlusPlus)
1903 Diag(Record->getLocation(), diag::ext_anonymous_union);
1904 else if (!Record->isUnion())
1905 Diag(Record->getLocation(), diag::ext_anonymous_struct);
Mike Stump1eb44332009-09-09 15:08:12 +00001906
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001907 // C and C++ require different kinds of checks for anonymous
1908 // structs/unions.
1909 bool Invalid = false;
1910 if (getLangOptions().CPlusPlus) {
1911 const char* PrevSpec = 0;
John McCallfec54012009-08-03 20:12:06 +00001912 unsigned DiagID;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001913 // C++ [class.union]p3:
1914 // Anonymous unions declared in a named namespace or in the
1915 // global namespace shall be declared static.
1916 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
1917 (isa<TranslationUnitDecl>(Owner) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001918 (isa<NamespaceDecl>(Owner) &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001919 cast<NamespaceDecl>(Owner)->getDeclName()))) {
1920 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
1921 Invalid = true;
1922
1923 // Recover by adding 'static'.
John McCallfec54012009-08-03 20:12:06 +00001924 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(),
Peter Collingbournee2f82f72011-02-11 19:59:54 +00001925 PrevSpec, DiagID, getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +00001926 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001927 // C++ [class.union]p3:
1928 // A storage class is not allowed in a declaration of an
1929 // anonymous union in a class scope.
1930 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1931 isa<RecordDecl>(Owner)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001932 Diag(DS.getStorageClassSpecLoc(),
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001933 diag::err_anonymous_union_with_storage_spec);
1934 Invalid = true;
1935
1936 // Recover by removing the storage specifier.
1937 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
Peter Collingbournee2f82f72011-02-11 19:59:54 +00001938 PrevSpec, DiagID, getLangOptions());
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001939 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001940
Mike Stump1eb44332009-09-09 15:08:12 +00001941 // C++ [class.union]p2:
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001942 // The member-specification of an anonymous union shall only
1943 // define non-static data members. [Note: nested types and
1944 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001945 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
1946 MemEnd = Record->decls_end();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001947 Mem != MemEnd; ++Mem) {
1948 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
1949 // C++ [class.union]p3:
1950 // An anonymous union shall not have private or protected
1951 // members (clause 11).
John McCallaec03712010-05-21 20:45:30 +00001952 assert(FD->getAccess() != AS_none);
1953 if (FD->getAccess() != AS_public) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001954 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
1955 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
1956 Invalid = true;
1957 }
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +00001958
1959 if (CheckNontrivialField(FD))
1960 Invalid = true;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001961 } else if ((*Mem)->isImplicit()) {
1962 // Any implicit members are fine.
Douglas Gregor1931b442009-02-03 00:34:39 +00001963 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
1964 // This is a type that showed up in an
1965 // elaborated-type-specifier inside the anonymous struct or
1966 // union, but which actually declares a type outside of the
1967 // anonymous struct or union. It's okay.
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001968 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
1969 if (!MemRecord->isAnonymousStructOrUnion() &&
1970 MemRecord->getDeclName()) {
Francois Pichet538e0d02010-09-08 11:32:25 +00001971 // Visual C++ allows type definition in anonymous struct or union.
1972 if (getLangOptions().Microsoft)
1973 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
1974 << (int)Record->isUnion();
1975 else {
1976 // This is a nested type declaration.
1977 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
1978 << (int)Record->isUnion();
1979 Invalid = true;
1980 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001981 }
Abramo Bagnara6206d532010-06-05 05:09:32 +00001982 } else if (isa<AccessSpecDecl>(*Mem)) {
1983 // Any access specifier is fine.
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001984 } else {
1985 // We have something that isn't a non-static data
1986 // member. Complain about it.
1987 unsigned DK = diag::err_anonymous_record_bad_member;
1988 if (isa<TypeDecl>(*Mem))
1989 DK = diag::err_anonymous_record_with_type;
1990 else if (isa<FunctionDecl>(*Mem))
1991 DK = diag::err_anonymous_record_with_function;
1992 else if (isa<VarDecl>(*Mem))
1993 DK = diag::err_anonymous_record_with_static;
Francois Pichet538e0d02010-09-08 11:32:25 +00001994
1995 // Visual C++ allows type definition in anonymous struct or union.
1996 if (getLangOptions().Microsoft &&
1997 DK == diag::err_anonymous_record_with_type)
1998 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001999 << (int)Record->isUnion();
Francois Pichet538e0d02010-09-08 11:32:25 +00002000 else {
2001 Diag((*Mem)->getLocation(), DK)
2002 << (int)Record->isUnion();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002003 Invalid = true;
Francois Pichet538e0d02010-09-08 11:32:25 +00002004 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002005 }
2006 }
Mike Stump1eb44332009-09-09 15:08:12 +00002007 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002008
2009 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002010 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
2011 << (int)getLangOptions().CPlusPlus;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002012 Invalid = true;
2013 }
2014
John McCalleb692e02009-10-22 23:31:08 +00002015 // Mock up a declarator.
2016 Declarator Dc(DS, Declarator::TypeNameContext);
John McCallbf1a0282010-06-04 23:28:52 +00002017 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCalla93c9342009-12-07 02:54:59 +00002018 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCalleb692e02009-10-22 23:31:08 +00002019
Mike Stump1eb44332009-09-09 15:08:12 +00002020 // Create a declaration for this anonymous struct/union.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002021 NamedDecl *Anon = 0;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002022 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
2023 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002024 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00002025 Context.getTypeDeclType(Record),
John McCalla93c9342009-12-07 02:54:59 +00002026 TInfo,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00002027 /*BitWidth=*/0, /*Mutable=*/false);
John McCallaec03712010-05-21 20:45:30 +00002028 Anon->setAccess(AS);
Douglas Gregor2cf9d652010-09-28 20:38:10 +00002029 if (getLangOptions().CPlusPlus)
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002030 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002031 } else {
Douglas Gregor16573fa2010-04-19 22:54:31 +00002032 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
2033 assert(SCSpec != DeclSpec::SCS_typedef &&
2034 "Parser allowed 'typedef' as storage class VarDecl.");
Abramo Bagnara35f9a192010-07-30 16:47:02 +00002035 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregor16573fa2010-04-19 22:54:31 +00002036 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002037 // mutable can only appear on non-static class members, so it's always
2038 // an error here
2039 Diag(Record->getLocation(), diag::err_mutable_nonmember);
2040 Invalid = true;
John McCalld931b082010-08-26 03:08:43 +00002041 SC = SC_None;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002042 }
Douglas Gregor16573fa2010-04-19 22:54:31 +00002043 SCSpec = DS.getStorageClassSpecAsWritten();
2044 VarDecl::StorageClass SCAsWritten
Abramo Bagnara35f9a192010-07-30 16:47:02 +00002045 = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002046
2047 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002048 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00002049 Context.getTypeDeclType(Record),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002050 TInfo, SC, SCAsWritten);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002051 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00002052 Anon->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002053
2054 // Add the anonymous struct/union object to the current
2055 // context. We'll be referencing this object when we refer to one of
2056 // its members.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002057 Owner->addDecl(Anon);
Douglas Gregorfe60f842010-05-03 15:18:25 +00002058
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002059 // Inject the members of the anonymous struct/union into the owning
2060 // context and into the identifier resolver chain for name lookup
2061 // purposes.
Francois Pichet87c2e122010-11-21 06:08:52 +00002062 llvm::SmallVector<NamedDecl*, 2> Chain;
2063 Chain.push_back(Anon);
2064
Francois Pichet8e161ed2010-11-23 06:07:27 +00002065 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
2066 Chain, false))
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002067 Invalid = true;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002068
2069 // Mark this as an anonymous struct/union type. Note that we do not
2070 // do this until after we have already checked and injected the
2071 // members of this anonymous struct/union type, because otherwise
2072 // the members could be injected twice: once by DeclContext when it
2073 // builds its lookup table, and once by
Mike Stump1eb44332009-09-09 15:08:12 +00002074 // InjectAnonymousStructOrUnionMembers.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002075 Record->setAnonymousStructOrUnion(true);
2076
2077 if (Invalid)
2078 Anon->setInvalidDecl();
2079
John McCalld226f652010-08-21 09:40:31 +00002080 return Anon;
Reid Spencer5f016e22007-07-11 17:01:13 +00002081}
2082
Francois Pichet8e161ed2010-11-23 06:07:27 +00002083/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
2084/// Microsoft C anonymous structure.
2085/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
2086/// Example:
2087///
2088/// struct A { int a; };
2089/// struct B { struct A; int b; };
2090///
2091/// void foo() {
2092/// B var;
2093/// var.a = 3;
2094/// }
2095///
2096Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2097 RecordDecl *Record) {
2098
2099 // If there is no Record, get the record via the typedef.
2100 if (!Record)
2101 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
2102
2103 // Mock up a declarator.
2104 Declarator Dc(DS, Declarator::TypeNameContext);
2105 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
2106 assert(TInfo && "couldn't build declarator info for anonymous struct");
2107
2108 // Create a declaration for this anonymous struct.
2109 NamedDecl* Anon = FieldDecl::Create(Context,
2110 cast<RecordDecl>(CurContext),
2111 DS.getSourceRange().getBegin(),
2112 /*IdentifierInfo=*/0,
2113 Context.getTypeDeclType(Record),
2114 TInfo,
2115 /*BitWidth=*/0, /*Mutable=*/false);
2116 Anon->setImplicit();
2117
2118 // Add the anonymous struct object to the current context.
2119 CurContext->addDecl(Anon);
2120
2121 // Inject the members of the anonymous struct into the current
2122 // context and into the identifier resolver chain for name lookup
2123 // purposes.
2124 llvm::SmallVector<NamedDecl*, 2> Chain;
2125 Chain.push_back(Anon);
2126
2127 if (InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
2128 Record->getDefinition(),
2129 AS_none, Chain, true))
2130 Anon->setInvalidDecl();
2131
2132 return Anon;
2133}
Steve Narofff0090632007-09-02 02:04:30 +00002134
Douglas Gregor10bd3682008-11-17 22:58:34 +00002135/// GetNameForDeclarator - Determine the full declaration name for the
2136/// given Declarator.
Abramo Bagnara25777432010-08-11 22:01:17 +00002137DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregor02a24ee2009-11-03 16:56:39 +00002138 return GetNameFromUnqualifiedId(D.getName());
2139}
2140
Abramo Bagnara25777432010-08-11 22:01:17 +00002141/// \brief Retrieves the declaration name from a parsed unqualified-id.
2142DeclarationNameInfo
2143Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
2144 DeclarationNameInfo NameInfo;
2145 NameInfo.setLoc(Name.StartLocation);
2146
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002147 switch (Name.getKind()) {
Sean Hunt0486d742009-11-28 04:44:28 +00002148
Abramo Bagnara25777432010-08-11 22:01:17 +00002149 case UnqualifiedId::IK_Identifier:
2150 NameInfo.setName(Name.Identifier);
2151 NameInfo.setLoc(Name.StartLocation);
2152 return NameInfo;
Sean Hunt0486d742009-11-28 04:44:28 +00002153
Abramo Bagnara25777432010-08-11 22:01:17 +00002154 case UnqualifiedId::IK_OperatorFunctionId:
2155 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
2156 Name.OperatorFunctionId.Operator));
2157 NameInfo.setLoc(Name.StartLocation);
2158 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
2159 = Name.OperatorFunctionId.SymbolLocations[0];
2160 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
2161 = Name.EndLocation.getRawEncoding();
2162 return NameInfo;
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002163
Abramo Bagnara25777432010-08-11 22:01:17 +00002164 case UnqualifiedId::IK_LiteralOperatorId:
2165 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
2166 Name.Identifier));
2167 NameInfo.setLoc(Name.StartLocation);
2168 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
2169 return NameInfo;
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002170
Abramo Bagnara25777432010-08-11 22:01:17 +00002171 case UnqualifiedId::IK_ConversionFunctionId: {
2172 TypeSourceInfo *TInfo;
2173 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
2174 if (Ty.isNull())
2175 return DeclarationNameInfo();
2176 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
2177 Context.getCanonicalType(Ty)));
2178 NameInfo.setLoc(Name.StartLocation);
2179 NameInfo.setNamedTypeInfo(TInfo);
2180 return NameInfo;
Douglas Gregordb422df2009-09-25 21:45:23 +00002181 }
Abramo Bagnara25777432010-08-11 22:01:17 +00002182
2183 case UnqualifiedId::IK_ConstructorName: {
2184 TypeSourceInfo *TInfo;
2185 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
2186 if (Ty.isNull())
2187 return DeclarationNameInfo();
2188 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
2189 Context.getCanonicalType(Ty)));
2190 NameInfo.setLoc(Name.StartLocation);
2191 NameInfo.setNamedTypeInfo(TInfo);
2192 return NameInfo;
2193 }
2194
2195 case UnqualifiedId::IK_ConstructorTemplateId: {
2196 // In well-formed code, we can only have a constructor
2197 // template-id that refers to the current context, so go there
2198 // to find the actual type being constructed.
2199 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
2200 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
2201 return DeclarationNameInfo();
2202
2203 // Determine the type of the class being constructed.
2204 QualType CurClassType = Context.getTypeDeclType(CurClass);
2205
2206 // FIXME: Check two things: that the template-id names the same type as
2207 // CurClassType, and that the template-id does not occur when the name
2208 // was qualified.
2209
2210 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
2211 Context.getCanonicalType(CurClassType)));
2212 NameInfo.setLoc(Name.StartLocation);
2213 // FIXME: should we retrieve TypeSourceInfo?
2214 NameInfo.setNamedTypeInfo(0);
2215 return NameInfo;
2216 }
2217
2218 case UnqualifiedId::IK_DestructorName: {
2219 TypeSourceInfo *TInfo;
2220 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
2221 if (Ty.isNull())
2222 return DeclarationNameInfo();
2223 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
2224 Context.getCanonicalType(Ty)));
2225 NameInfo.setLoc(Name.StartLocation);
2226 NameInfo.setNamedTypeInfo(TInfo);
2227 return NameInfo;
2228 }
2229
2230 case UnqualifiedId::IK_TemplateId: {
John McCall2b5289b2010-08-23 07:28:44 +00002231 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnara25777432010-08-11 22:01:17 +00002232 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
2233 return Context.getNameForTemplate(TName, TNameLoc);
2234 }
2235
2236 } // switch (Name.getKind())
2237
Douglas Gregor10bd3682008-11-17 22:58:34 +00002238 assert(false && "Unknown name kind");
Abramo Bagnara25777432010-08-11 22:01:17 +00002239 return DeclarationNameInfo();
Douglas Gregor10bd3682008-11-17 22:58:34 +00002240}
2241
Douglas Gregor4ce205f2009-02-06 17:46:57 +00002242/// isNearlyMatchingFunction - Determine whether the C++ functions
2243/// Declaration and Definition are "nearly" matching. This heuristic
2244/// is used to improve diagnostics in the case where an out-of-line
2245/// function definition doesn't match any declaration within
2246/// the class or namespace.
2247static bool isNearlyMatchingFunction(ASTContext &Context,
2248 FunctionDecl *Declaration,
2249 FunctionDecl *Definition) {
Douglas Gregor584049d2008-12-15 23:53:10 +00002250 if (Declaration->param_size() != Definition->param_size())
2251 return false;
2252 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
2253 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
2254 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
2255
Douglas Gregora4923eb2009-11-16 21:35:15 +00002256 if (!Context.hasSameUnqualifiedType(DeclParamTy.getNonReferenceType(),
2257 DefParamTy.getNonReferenceType()))
Douglas Gregor584049d2008-12-15 23:53:10 +00002258 return false;
2259 }
2260
2261 return true;
2262}
2263
John McCall63b43852010-04-29 23:50:39 +00002264/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
2265/// declarator needs to be rebuilt in the current instantiation.
2266/// Any bits of declarator which appear before the name are valid for
2267/// consideration here. That's specifically the type in the decl spec
2268/// and the base type in any member-pointer chunks.
2269static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
2270 DeclarationName Name) {
2271 // The types we specifically need to rebuild are:
2272 // - typenames, typeofs, and decltypes
2273 // - types which will become injected class names
2274 // Of course, we also need to rebuild any type referencing such a
2275 // type. It's safest to just say "dependent", but we call out a
2276 // few cases here.
2277
2278 DeclSpec &DS = D.getMutableDeclSpec();
2279 switch (DS.getTypeSpecType()) {
2280 case DeclSpec::TST_typename:
2281 case DeclSpec::TST_typeofType:
John McCall63b43852010-04-29 23:50:39 +00002282 case DeclSpec::TST_decltype: {
2283 // Grab the type from the parser.
2284 TypeSourceInfo *TSI = 0;
John McCallb3d87482010-08-24 05:47:05 +00002285 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall63b43852010-04-29 23:50:39 +00002286 if (T.isNull() || !T->isDependentType()) break;
2287
2288 // Make sure there's a type source info. This isn't really much
2289 // of a waste; most dependent types should have type source info
2290 // attached already.
2291 if (!TSI)
2292 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
2293
2294 // Rebuild the type in the current instantiation.
2295 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
2296 if (!TSI) return true;
2297
2298 // Store the new type back in the decl spec.
John McCallb3d87482010-08-24 05:47:05 +00002299 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
2300 DS.UpdateTypeRep(LocType);
2301 break;
2302 }
2303
2304 case DeclSpec::TST_typeofExpr: {
2305 Expr *E = DS.getRepAsExpr();
John McCall60d7b3a2010-08-24 06:29:42 +00002306 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallb3d87482010-08-24 05:47:05 +00002307 if (Result.isInvalid()) return true;
2308 DS.UpdateExprRep(Result.get());
John McCall63b43852010-04-29 23:50:39 +00002309 break;
2310 }
2311
2312 default:
2313 // Nothing to do for these decl specs.
2314 break;
2315 }
2316
2317 // It doesn't matter what order we do this in.
2318 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
2319 DeclaratorChunk &Chunk = D.getTypeObject(I);
2320
2321 // The only type information in the declarator which can come
2322 // before the declaration name is the base type of a member
2323 // pointer.
2324 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
2325 continue;
2326
2327 // Rebuild the scope specifier in-place.
2328 CXXScopeSpec &SS = Chunk.Mem.Scope();
2329 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
2330 return true;
2331 }
2332
2333 return false;
2334}
2335
John McCall7cd088e2010-08-24 07:21:54 +00002336Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
2337 return HandleDeclarator(S, D, MultiTemplateParamsArg(*this), false);
2338}
2339
John McCalld226f652010-08-21 09:40:31 +00002340Decl *Sema::HandleDeclarator(Scope *S, Declarator &D,
2341 MultiTemplateParamsArg TemplateParamLists,
2342 bool IsFunctionDefinition) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002343 // TODO: consider using NameInfo for diagnostic.
2344 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2345 DeclarationName Name = NameInfo.getName();
Douglas Gregor10bd3682008-11-17 22:58:34 +00002346
Chris Lattnere80a59c2007-07-25 00:24:17 +00002347 // All of these full declarators require an identifier. If it doesn't have
2348 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00002349 if (!Name) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00002350 if (!D.isInvalidType()) // Reject this if we think it is valid.
Chris Lattner1f6f54b2008-11-11 06:13:16 +00002351 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002352 diag::err_declarator_need_ident)
2353 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +00002354 return 0;
Douglas Gregor56c04582010-12-16 00:46:58 +00002355 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
2356 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002357
Chris Lattner31e05722007-08-26 06:24:45 +00002358 // The scope passed in may not be a decl scope. Zip up the scope tree until
2359 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00002360 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregoraaba5e32009-02-04 19:02:06 +00002361 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00002362 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00002363
John McCall63b43852010-04-29 23:50:39 +00002364 DeclContext *DC = CurContext;
2365 if (D.getCXXScopeSpec().isInvalid())
2366 D.setInvalidType();
2367 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6ccab972010-12-16 01:14:37 +00002368 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
2369 UPPC_DeclarationQualifier))
2370 return 0;
2371
John McCall63b43852010-04-29 23:50:39 +00002372 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
2373 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
2374 if (!DC) {
2375 // If we could not compute the declaration context, it's because the
2376 // declaration context is dependent but does not refer to a class,
2377 // class template, or class template partial specialization. Complain
2378 // and return early, to avoid the coming semantic disaster.
2379 Diag(D.getIdentifierLoc(),
2380 diag::err_template_qualified_declarator_no_match)
2381 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
2382 << D.getCXXScopeSpec().getRange();
John McCalld226f652010-08-21 09:40:31 +00002383 return 0;
John McCall63b43852010-04-29 23:50:39 +00002384 }
John McCall0dd7ceb2009-12-19 09:35:56 +00002385
John McCall63b43852010-04-29 23:50:39 +00002386 bool IsDependentContext = DC->isDependentContext();
John McCall0dd7ceb2009-12-19 09:35:56 +00002387
John McCall63b43852010-04-29 23:50:39 +00002388 if (!IsDependentContext &&
John McCall77bb1aa2010-05-01 00:40:08 +00002389 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCalld226f652010-08-21 09:40:31 +00002390 return 0;
John McCall63b43852010-04-29 23:50:39 +00002391
Douglas Gregor922fff22010-10-13 22:19:53 +00002392 if (isa<CXXRecordDecl>(DC)) {
2393 if (!cast<CXXRecordDecl>(DC)->hasDefinition()) {
2394 Diag(D.getIdentifierLoc(),
2395 diag::err_member_def_undefined_record)
2396 << Name << DC << D.getCXXScopeSpec().getRange();
2397 D.setInvalidType();
2398 } else if (isa<CXXRecordDecl>(CurContext) &&
2399 !D.getDeclSpec().isFriendSpecified()) {
2400 // The user provided a superfluous scope specifier inside a class
2401 // definition:
2402 //
2403 // class X {
2404 // void X::f();
2405 // };
2406 if (CurContext->Equals(DC))
2407 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
2408 << Name << FixItHint::CreateRemoval(D.getCXXScopeSpec().getRange());
2409 else
2410 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2411 << Name << D.getCXXScopeSpec().getRange();
2412
2413 // Pretend that this qualifier was not here.
2414 D.getCXXScopeSpec().clear();
2415 }
John McCall63b43852010-04-29 23:50:39 +00002416 }
2417
2418 // Check whether we need to rebuild the type of the given
2419 // declaration in the current instantiation.
2420 if (EnteringContext && IsDependentContext &&
2421 TemplateParamLists.size() != 0) {
2422 ContextRAII SavedContext(*this, DC);
2423 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
2424 D.setInvalidType();
Douglas Gregor4a959d82009-08-06 16:20:37 +00002425 }
2426 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00002427
2428 // C++ [class.mem]p13:
2429 // If T is the name of a class, then each of the following shall have a
2430 // name different from T:
2431 // - every static data member of class T;
2432 // - every member function of class T
2433 // - every member of class T that is itself a type;
2434 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
2435 if (Record->getIdentifier() && Record->getDeclName() == Name) {
2436 Diag(D.getIdentifierLoc(), diag::err_member_name_of_class)
2437 << Name;
2438
2439 // If this is a typedef, we'll end up spewing multiple diagnostics.
2440 // Just return early; it's safer.
2441 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2442 return 0;
2443 }
2444
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002445 NamedDecl *New;
Douglas Gregorcda9c672009-02-16 17:45:42 +00002446
John McCallbf1a0282010-06-04 23:28:52 +00002447 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
2448 QualType R = TInfo->getType();
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00002449
Douglas Gregord0937222010-12-13 22:49:22 +00002450 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
2451 UPPC_DeclarationType))
2452 D.setInvalidType();
2453
Abramo Bagnara25777432010-08-11 22:01:17 +00002454 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00002455 ForRedeclaration);
2456
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002457 // See if this is a redefinition of a variable in the same scope.
John McCall63b43852010-04-29 23:50:39 +00002458 if (!D.getCXXScopeSpec().isSet()) {
John McCall68263142009-11-18 22:49:29 +00002459 bool IsLinkageLookup = false;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00002460
2461 // If the declaration we're planning to build will be a function
2462 // or object with linkage, then look for another declaration with
2463 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
2464 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2465 /* Do nothing*/;
2466 else if (R->isFunctionType()) {
Douglas Gregor6bec78d2009-07-07 17:00:05 +00002467 if (CurContext->isFunctionOrMethod() ||
2468 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall68263142009-11-18 22:49:29 +00002469 IsLinkageLookup = true;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00002470 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
John McCall68263142009-11-18 22:49:29 +00002471 IsLinkageLookup = true;
Sebastian Redl7a126a42010-08-31 00:36:30 +00002472 else if (CurContext->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor6bec78d2009-07-07 17:00:05 +00002473 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall68263142009-11-18 22:49:29 +00002474 IsLinkageLookup = true;
2475
2476 if (IsLinkageLookup)
2477 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00002478
John McCall68263142009-11-18 22:49:29 +00002479 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002480 } else { // Something like "int foo::x;"
John McCall68263142009-11-18 22:49:29 +00002481 LookupQualifiedName(Previous, DC);
2482
2483 // Don't consider using declarations as previous declarations for
2484 // out-of-line members.
2485 RemoveUsingDecls(Previous);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002486
2487 // C++ 7.3.1.2p2:
2488 // Members (including explicit specializations of templates) of a named
2489 // namespace can also be defined outside that namespace by explicit
2490 // qualification of the name being defined, provided that the entity being
2491 // defined was already declared in the namespace and the definition appears
2492 // after the point of declaration in a namespace that encloses the
2493 // declarations namespace.
2494 //
Douglas Gregor584049d2008-12-15 23:53:10 +00002495 // Note that we only check the context at this point. We don't yet
2496 // have enough information to make sure that PrevDecl is actually
2497 // the declaration we want to match. For example, given:
2498 //
Douglas Gregor9d350972008-12-12 08:25:50 +00002499 // class X {
2500 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00002501 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00002502 // };
2503 //
Douglas Gregor584049d2008-12-15 23:53:10 +00002504 // void X::f(int) { } // ill-formed
2505 //
2506 // In this case, PrevDecl will point to the overload set
2507 // containing the two f's declared in X, but neither of them
Mike Stump1eb44332009-09-09 15:08:12 +00002508 // matches.
Douglas Gregor4ce205f2009-02-06 17:46:57 +00002509
2510 // First check whether we named the global scope.
2511 if (isa<TranslationUnitDecl>(DC)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002512 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
Douglas Gregor4ce205f2009-02-06 17:46:57 +00002513 << Name << D.getCXXScopeSpec().getRange();
Sebastian Redl9770ef02009-11-08 11:36:54 +00002514 } else {
2515 DeclContext *Cur = CurContext;
2516 while (isa<LinkageSpecDecl>(Cur))
2517 Cur = Cur->getParent();
2518 if (!Cur->Encloses(DC)) {
2519 // The qualifying scope doesn't enclose the original declaration.
2520 // Emit diagnostic based on current scope.
2521 SourceLocation L = D.getIdentifierLoc();
2522 SourceRange R = D.getCXXScopeSpec().getRange();
2523 if (isa<FunctionDecl>(Cur))
2524 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
2525 else
2526 Diag(L, diag::err_invalid_declarator_scope)
2527 << Name << cast<NamedDecl>(DC) << R;
2528 D.setInvalidType();
2529 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002530 }
2531 }
2532
John McCall68263142009-11-18 22:49:29 +00002533 if (Previous.isSingleResult() &&
2534 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002535 // Maybe we will complain about the shadowed template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00002536 if (!D.isInvalidType())
John McCall68263142009-11-18 22:49:29 +00002537 if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
2538 Previous.getFoundDecl()))
Chris Lattnereaaebc72009-04-25 08:06:05 +00002539 D.setInvalidType();
Mike Stump1eb44332009-09-09 15:08:12 +00002540
Douglas Gregor72c3f312008-12-05 18:15:24 +00002541 // Just pretend that we didn't see the previous declaration.
John McCall68263142009-11-18 22:49:29 +00002542 Previous.clear();
Douglas Gregor72c3f312008-12-05 18:15:24 +00002543 }
2544
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002545 // In C++, the previous declaration we find might be a tag type
2546 // (class or enum). In this case, the new declaration will hide the
Douglas Gregor66973122009-01-28 17:15:10 +00002547 // tag type. Note that this does does not apply if we're declaring a
2548 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00002549 if (Previous.isSingleTagDecl() &&
Douglas Gregor66973122009-01-28 17:15:10 +00002550 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall68263142009-11-18 22:49:29 +00002551 Previous.clear();
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002552
Douglas Gregorcda9c672009-02-16 17:45:42 +00002553 bool Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002554 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregore542c862009-06-23 23:11:28 +00002555 if (TemplateParamLists.size()) {
2556 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
John McCalld226f652010-08-21 09:40:31 +00002557 return 0;
Douglas Gregore542c862009-06-23 23:11:28 +00002558 }
Mike Stump1eb44332009-09-09 15:08:12 +00002559
John McCalla93c9342009-12-07 02:54:59 +00002560 New = ActOnTypedefDeclarator(S, D, DC, R, TInfo, Previous, Redeclaration);
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00002561 } else if (R->isFunctionType()) {
John McCalla93c9342009-12-07 02:54:59 +00002562 New = ActOnFunctionDeclarator(S, D, DC, R, TInfo, Previous,
Douglas Gregore542c862009-06-23 23:11:28 +00002563 move(TemplateParamLists),
Chris Lattnereaaebc72009-04-25 08:06:05 +00002564 IsFunctionDefinition, Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +00002565 } else {
John McCalla93c9342009-12-07 02:54:59 +00002566 New = ActOnVariableDeclarator(S, D, DC, R, TInfo, Previous,
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00002567 move(TemplateParamLists),
2568 Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +00002569 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002570
2571 if (New == 0)
John McCalld226f652010-08-21 09:40:31 +00002572 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002573
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00002574 // If this has an identifier and is not an invalid redeclaration or
2575 // function template specialization, add it to the scope stack.
Douglas Gregorf178dca2010-07-24 00:10:38 +00002576 if (New->getDeclName() && !(Redeclaration && New->isInvalidDecl()))
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002577 PushOnScopeChains(New, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002578
John McCalld226f652010-08-21 09:40:31 +00002579 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +00002580}
2581
Eli Friedman1ca48132009-02-21 00:44:51 +00002582/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2583/// types into constant array types in certain situations which would otherwise
2584/// be errors (for GCC compatibility).
2585static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2586 ASTContext &Context,
Douglas Gregor2767ce22010-08-18 00:39:00 +00002587 bool &SizeIsNegative,
2588 llvm::APSInt &Oversized) {
Eli Friedman1ca48132009-02-21 00:44:51 +00002589 // This method tries to turn a variable array into a constant
2590 // array even when the size isn't an ICE. This is necessary
2591 // for compatibility with code that depends on gcc's buggy
2592 // constant expression folding, like struct {char x[(int)(char*)2];}
2593 SizeIsNegative = false;
Douglas Gregor2767ce22010-08-18 00:39:00 +00002594 Oversized = 0;
2595
2596 if (T->isDependentType())
2597 return QualType();
2598
John McCall0953e762009-09-24 19:53:00 +00002599 QualifierCollector Qs;
2600 const Type *Ty = Qs.strip(T);
2601
2602 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedman1ca48132009-02-21 00:44:51 +00002603 QualType Pointee = PTy->getPointeeType();
2604 QualType FixedType =
Douglas Gregor2767ce22010-08-18 00:39:00 +00002605 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
2606 Oversized);
Eli Friedman1ca48132009-02-21 00:44:51 +00002607 if (FixedType.isNull()) return FixedType;
Eli Friedman61125c82009-02-21 00:58:02 +00002608 FixedType = Context.getPointerType(FixedType);
John McCall49f4e1c2010-12-10 11:01:00 +00002609 return Qs.apply(Context, FixedType);
Eli Friedman1ca48132009-02-21 00:44:51 +00002610 }
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002611 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
2612 QualType Inner = PTy->getInnerType();
2613 QualType FixedType =
2614 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
2615 Oversized);
2616 if (FixedType.isNull()) return FixedType;
2617 FixedType = Context.getParenType(FixedType);
2618 return Qs.apply(Context, FixedType);
2619 }
Eli Friedman1ca48132009-02-21 00:44:51 +00002620
2621 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanbc592e62009-02-26 03:58:54 +00002622 if (!VLATy)
2623 return QualType();
2624 // FIXME: We should probably handle this case
2625 if (VLATy->getElementType()->isVariablyModifiedType())
2626 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00002627
Eli Friedman1ca48132009-02-21 00:44:51 +00002628 Expr::EvalResult EvalResult;
2629 if (!VLATy->getSizeExpr() ||
Eli Friedmanbc592e62009-02-26 03:58:54 +00002630 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
2631 !EvalResult.Val.isInt())
Eli Friedman1ca48132009-02-21 00:44:51 +00002632 return QualType();
Eli Friedmanbc592e62009-02-26 03:58:54 +00002633
Douglas Gregor2767ce22010-08-18 00:39:00 +00002634 // Check whether the array size is negative.
Eli Friedman1ca48132009-02-21 00:44:51 +00002635 llvm::APSInt &Res = EvalResult.Val.getInt();
Douglas Gregor2767ce22010-08-18 00:39:00 +00002636 if (Res.isSigned() && Res.isNegative()) {
2637 SizeIsNegative = true;
2638 return QualType();
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002639 }
Eli Friedman1ca48132009-02-21 00:44:51 +00002640
Douglas Gregor2767ce22010-08-18 00:39:00 +00002641 // Check whether the array is too large to be addressed.
2642 unsigned ActiveSizeBits
2643 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
2644 Res);
2645 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2646 Oversized = Res;
2647 return QualType();
2648 }
2649
2650 return Context.getConstantArrayType(VLATy->getElementType(),
2651 Res, ArrayType::Normal, 0);
Eli Friedman1ca48132009-02-21 00:44:51 +00002652}
2653
Douglas Gregor63935192009-03-02 00:19:53 +00002654/// \brief Register the given locally-scoped external C declaration so
2655/// that it can be found later for redeclarations
Mike Stump1eb44332009-09-09 15:08:12 +00002656void
John McCall68263142009-11-18 22:49:29 +00002657Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
2658 const LookupResult &Previous,
Douglas Gregor63935192009-03-02 00:19:53 +00002659 Scope *S) {
2660 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
2661 "Decl is not a locally-scoped decl!");
2662 // Note that we have a locally-scoped external with this name.
2663 LocallyScopedExternalDecls[ND->getDeclName()] = ND;
2664
John McCall68263142009-11-18 22:49:29 +00002665 if (!Previous.isSingleResult())
Douglas Gregor63935192009-03-02 00:19:53 +00002666 return;
2667
John McCall68263142009-11-18 22:49:29 +00002668 NamedDecl *PrevDecl = Previous.getFoundDecl();
2669
Douglas Gregor63935192009-03-02 00:19:53 +00002670 // If there was a previous declaration of this variable, it may be
2671 // in our identifier chain. Update the identifier chain with the new
2672 // declaration.
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002673 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
Douglas Gregor63935192009-03-02 00:19:53 +00002674 // The previous declaration was found on the identifer resolver
2675 // chain, so remove it from its scope.
John McCalld226f652010-08-21 09:40:31 +00002676 while (S && !S->isDeclScope(PrevDecl))
Douglas Gregor63935192009-03-02 00:19:53 +00002677 S = S->getParent();
2678
2679 if (S)
John McCalld226f652010-08-21 09:40:31 +00002680 S->RemoveDecl(PrevDecl);
Douglas Gregor63935192009-03-02 00:19:53 +00002681 }
2682}
2683
Eli Friedman85a53192009-04-07 19:37:57 +00002684/// \brief Diagnose function specifiers on a declaration of an identifier that
2685/// does not identify a function.
2686void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
2687 // FIXME: We should probably indicate the identifier in question to avoid
2688 // confusion for constructs like "inline int a(), b;"
2689 if (D.getDeclSpec().isInlineSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00002690 Diag(D.getDeclSpec().getInlineSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00002691 diag::err_inline_non_function);
2692
2693 if (D.getDeclSpec().isVirtualSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00002694 Diag(D.getDeclSpec().getVirtualSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00002695 diag::err_virtual_non_function);
2696
2697 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00002698 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00002699 diag::err_explicit_non_function);
2700}
2701
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002702NamedDecl*
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002703Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
John McCalla93c9342009-12-07 02:54:59 +00002704 QualType R, TypeSourceInfo *TInfo,
John McCall68263142009-11-18 22:49:29 +00002705 LookupResult &Previous, bool &Redeclaration) {
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002706 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
2707 if (D.getCXXScopeSpec().isSet()) {
2708 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
2709 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00002710 D.setInvalidType();
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002711 // Pretend we didn't see the scope specifier.
Douglas Gregor9de672f2010-03-23 15:26:55 +00002712 DC = CurContext;
2713 Previous.clear();
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002714 }
2715
Douglas Gregor021c3b32009-03-11 23:00:04 +00002716 if (getLangOptions().CPlusPlus) {
2717 // Check that there are no default arguments (C++ only).
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002718 CheckExtraCXXDefaultArguments(D);
Douglas Gregor021c3b32009-03-11 23:00:04 +00002719 }
2720
Eli Friedman85a53192009-04-07 19:37:57 +00002721 DiagnoseFunctionSpecifiers(D);
2722
Eli Friedman63054b32009-04-19 20:27:55 +00002723 if (D.getDeclSpec().isThreadSpecified())
2724 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2725
Douglas Gregoraef01992010-07-13 06:37:01 +00002726 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
2727 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
2728 << D.getName().getSourceRange();
2729 return 0;
2730 }
2731
John McCalla93c9342009-12-07 02:54:59 +00002732 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, TInfo);
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002733 if (!NewTD) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002734
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002735 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002736 ProcessDeclAttributes(S, NewTD, D);
John McCall68263142009-11-18 22:49:29 +00002737
Chris Lattner38c5ebd2009-04-19 05:21:20 +00002738 // C99 6.7.7p2: If a typedef name specifies a variably modified type
2739 // then it shall have block scope.
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00002740 // Note that variably modified types must be fixed before merging the decl so
2741 // that redeclarations will match.
Chris Lattner38c5ebd2009-04-19 05:21:20 +00002742 QualType T = NewTD->getUnderlyingType();
2743 if (T->isVariablyModifiedType()) {
John McCall781472f2010-08-25 08:40:02 +00002744 getCurFunction()->setHasBranchProtectedScope();
Mike Stump1eb44332009-09-09 15:08:12 +00002745
Chris Lattner38c5ebd2009-04-19 05:21:20 +00002746 if (S->getFnParent() == 0) {
Eli Friedman1ca48132009-02-21 00:44:51 +00002747 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +00002748 llvm::APSInt Oversized;
Eli Friedman1ca48132009-02-21 00:44:51 +00002749 QualType FixedTy =
Douglas Gregor2767ce22010-08-18 00:39:00 +00002750 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
2751 Oversized);
Eli Friedman1ca48132009-02-21 00:44:51 +00002752 if (!FixedTy.isNull()) {
2753 Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size);
John McCalla93c9342009-12-07 02:54:59 +00002754 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
Eli Friedman1ca48132009-02-21 00:44:51 +00002755 } else {
2756 if (SizeIsNegative)
2757 Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size);
2758 else if (T->isVariableArrayType())
2759 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
Douglas Gregor2767ce22010-08-18 00:39:00 +00002760 else if (Oversized.getBoolValue())
2761 Diag(D.getIdentifierLoc(), diag::err_array_too_large)
2762 << Oversized.toString(10);
Eli Friedman1ca48132009-02-21 00:44:51 +00002763 else
2764 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002765 NewTD->setInvalidDecl();
Eli Friedman1ca48132009-02-21 00:44:51 +00002766 }
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002767 }
2768 }
Douglas Gregorc29f77b2009-07-07 16:35:42 +00002769
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00002770 // Merge the decl with the existing one if appropriate. If the decl is
2771 // in an outer scope, it isn't the same thing.
2772 FilterLookupForScope(*this, Previous, DC, S, /*ConsiderLinkage*/ false);
2773 if (!Previous.empty()) {
2774 Redeclaration = true;
2775 MergeTypeDefDecl(NewTD, Previous);
2776 }
2777
Douglas Gregorc29f77b2009-07-07 16:35:42 +00002778 // If this is the C FILE type, notify the AST context.
2779 if (IdentifierInfo *II = NewTD->getIdentifier())
2780 if (!NewTD->isInvalidDecl() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00002781 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stump782fa302009-07-28 02:25:19 +00002782 if (II->isStr("FILE"))
2783 Context.setFILEDecl(NewTD);
2784 else if (II->isStr("jmp_buf"))
2785 Context.setjmp_bufDecl(NewTD);
2786 else if (II->isStr("sigjmp_buf"))
2787 Context.setsigjmp_bufDecl(NewTD);
Douglas Gregor4a1bb8c2010-10-05 15:41:24 +00002788 else if (II->isStr("__builtin_va_list"))
2789 Context.setBuiltinVaListType(Context.getTypedefType(NewTD));
Mike Stump782fa302009-07-28 02:25:19 +00002790 }
2791
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002792 return NewTD;
2793}
2794
Douglas Gregor8f301052009-02-24 19:23:27 +00002795/// \brief Determines whether the given declaration is an out-of-scope
2796/// previous declaration.
2797///
2798/// This routine should be invoked when name lookup has found a
2799/// previous declaration (PrevDecl) that is not in the scope where a
2800/// new declaration by the same name is being introduced. If the new
2801/// declaration occurs in a local scope, previous declarations with
2802/// linkage may still be considered previous declarations (C99
2803/// 6.2.2p4-5, C++ [basic.link]p6).
2804///
2805/// \param PrevDecl the previous declaration found by name
2806/// lookup
Mike Stump1eb44332009-09-09 15:08:12 +00002807///
Douglas Gregor8f301052009-02-24 19:23:27 +00002808/// \param DC the context in which the new declaration is being
2809/// declared.
2810///
2811/// \returns true if PrevDecl is an out-of-scope previous declaration
2812/// for a new delcaration with the same name.
Mike Stump1eb44332009-09-09 15:08:12 +00002813static bool
Douglas Gregor8f301052009-02-24 19:23:27 +00002814isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
2815 ASTContext &Context) {
2816 if (!PrevDecl)
Sebastian Redl7a126a42010-08-31 00:36:30 +00002817 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00002818
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00002819 if (!PrevDecl->hasLinkage())
2820 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00002821
2822 if (Context.getLangOptions().CPlusPlus) {
2823 // C++ [basic.link]p6:
2824 // If there is a visible declaration of an entity with linkage
2825 // having the same name and type, ignoring entities declared
2826 // outside the innermost enclosing namespace scope, the block
2827 // scope declaration declares that same entity and receives the
2828 // linkage of the previous declaration.
Sebastian Redl7a126a42010-08-31 00:36:30 +00002829 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor8f301052009-02-24 19:23:27 +00002830 if (!OuterContext->isFunctionOrMethod())
2831 // This rule only applies to block-scope declarations.
2832 return false;
Douglas Gregor757c6002010-08-27 22:55:10 +00002833
2834 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
2835 if (PrevOuterContext->isRecord())
2836 // We found a member function: ignore it.
2837 return false;
2838
2839 // Find the innermost enclosing namespace for the new and
2840 // previous declarations.
Sebastian Redl7a126a42010-08-31 00:36:30 +00002841 OuterContext = OuterContext->getEnclosingNamespaceContext();
2842 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002843
Douglas Gregor757c6002010-08-27 22:55:10 +00002844 // The previous declaration is in a different namespace, so it
2845 // isn't the same function.
2846 if (!OuterContext->Equals(PrevOuterContext))
2847 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00002848 }
2849
Douglas Gregor8f301052009-02-24 19:23:27 +00002850 return true;
2851}
2852
John McCallb6217662010-03-15 10:12:16 +00002853static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
2854 CXXScopeSpec &SS = D.getCXXScopeSpec();
2855 if (!SS.isSet()) return;
2856 DD->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2857 SS.getRange());
2858}
2859
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002860NamedDecl*
Chris Lattner16c5dea2010-10-10 18:16:20 +00002861Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
John McCalla93c9342009-12-07 02:54:59 +00002862 QualType R, TypeSourceInfo *TInfo,
John McCall68263142009-11-18 22:49:29 +00002863 LookupResult &Previous,
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00002864 MultiTemplateParamsArg TemplateParamLists,
Douglas Gregorcda9c672009-02-16 17:45:42 +00002865 bool &Redeclaration) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002866 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002867
2868 // Check that there are no default arguments (C++ only).
2869 if (getLangOptions().CPlusPlus)
2870 CheckExtraCXXDefaultArguments(D);
2871
Douglas Gregor16573fa2010-04-19 22:54:31 +00002872 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
2873 assert(SCSpec != DeclSpec::SCS_typedef &&
2874 "Parser allowed 'typedef' as storage class VarDecl.");
Abramo Bagnara35f9a192010-07-30 16:47:02 +00002875 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregor16573fa2010-04-19 22:54:31 +00002876 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002877 // mutable can only appear on non-static class members, so it's always
2878 // an error here
2879 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002880 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00002881 SC = SC_None;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002882 }
Douglas Gregor16573fa2010-04-19 22:54:31 +00002883 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
2884 VarDecl::StorageClass SCAsWritten
Abramo Bagnara35f9a192010-07-30 16:47:02 +00002885 = StorageClassSpecToVarDeclStorageClass(SCSpec);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002886
2887 IdentifierInfo *II = Name.getAsIdentifierInfo();
2888 if (!II) {
2889 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
2890 << Name.getAsString();
2891 return 0;
2892 }
2893
Eli Friedman85a53192009-04-07 19:37:57 +00002894 DiagnoseFunctionSpecifiers(D);
Douglas Gregor021c3b32009-03-11 23:00:04 +00002895
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00002896 if (!DC->isRecord() && S->getFnParent() == 0) {
2897 // C99 6.9p2: The storage-class specifiers auto and register shall not
2898 // appear in the declaration specifiers in an external declaration.
John McCalld931b082010-08-26 03:08:43 +00002899 if (SC == SC_Auto || SC == SC_Register) {
Mike Stump1eb44332009-09-09 15:08:12 +00002900
Chris Lattnerd4b19d52009-05-12 21:44:00 +00002901 // If this is a register variable with an asm label specified, then this
2902 // is a GNU extension.
John McCalld931b082010-08-26 03:08:43 +00002903 if (SC == SC_Register && D.getAsmLabel())
Chris Lattnerd4b19d52009-05-12 21:44:00 +00002904 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
2905 else
2906 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002907 D.setInvalidType();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002908 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002909 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00002910
Ted Kremenek9577abc2011-01-23 17:04:59 +00002911 bool isExplicitSpecialization = false;
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00002912 VarDecl *NewVD;
2913 if (!getLangOptions().CPlusPlus) {
2914 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
2915 II, R, TInfo, SC, SCAsWritten);
2916
2917 if (D.isInvalidType())
2918 NewVD->setInvalidDecl();
2919 } else {
2920 if (DC->isRecord() && !CurContext->isRecord()) {
2921 // This is an out-of-line definition of a static data member.
2922 if (SC == SC_Static) {
2923 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2924 diag::err_static_out_of_line)
2925 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
2926 } else if (SC == SC_None)
2927 SC = SC_Static;
Anders Carlssone98da2e2009-06-24 00:28:53 +00002928 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00002929 if (SC == SC_Static) {
2930 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
2931 if (RD->isLocalClass())
2932 Diag(D.getIdentifierLoc(),
2933 diag::err_static_data_member_not_allowed_in_local_class)
2934 << Name << RD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00002935
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00002936 // C++ [class.union]p1: If a union contains a static data member,
2937 // the program is ill-formed.
2938 //
2939 // We also disallow static data members in anonymous structs.
2940 if (CurContext->isRecord() && (RD->isUnion() || !RD->getDeclName()))
2941 Diag(D.getIdentifierLoc(),
2942 diag::err_static_data_member_not_allowed_in_union_or_anon_struct)
2943 << Name << RD->isUnion();
2944 }
2945 }
2946
2947 // Match up the template parameter lists with the scope specifier, then
2948 // determine whether we have a template or a template specialization.
2949 isExplicitSpecialization = false;
2950 unsigned NumMatchedTemplateParamLists = TemplateParamLists.size();
2951 bool Invalid = false;
2952 if (TemplateParameterList *TemplateParams
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002953 = MatchTemplateParametersToScopeSpecifier(
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00002954 D.getDeclSpec().getSourceRange().getBegin(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002955 D.getCXXScopeSpec(),
John McCall9a34edb2010-10-19 01:40:49 +00002956 TemplateParamLists.get(),
2957 TemplateParamLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00002958 /*never a friend*/ false,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00002959 isExplicitSpecialization,
2960 Invalid)) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00002961 // All but one template parameter lists have been matching.
2962 --NumMatchedTemplateParamLists;
Abramo Bagnara9b934882010-06-12 08:15:14 +00002963
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00002964 if (TemplateParams->size() > 0) {
2965 // There is no such thing as a variable template.
2966 Diag(D.getIdentifierLoc(), diag::err_template_variable)
2967 << II
2968 << SourceRange(TemplateParams->getTemplateLoc(),
2969 TemplateParams->getRAngleLoc());
2970 return 0;
2971 } else {
2972 // There is an extraneous 'template<>' for this variable. Complain
2973 // about it, but allow the declaration of the variable.
2974 Diag(TemplateParams->getTemplateLoc(),
2975 diag::err_template_variable_noparams)
2976 << II
2977 << SourceRange(TemplateParams->getTemplateLoc(),
2978 TemplateParams->getRAngleLoc());
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002979
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00002980 isExplicitSpecialization = true;
2981 }
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00002982 }
Mike Stump1eb44332009-09-09 15:08:12 +00002983
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00002984 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
2985 II, R, TInfo, SC, SCAsWritten);
Eli Friedman63054b32009-04-19 20:27:55 +00002986
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00002987 if (D.isInvalidType() || Invalid)
2988 NewVD->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002989
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00002990 SetNestedNameSpecifier(NewVD, D);
John McCallb6217662010-03-15 10:12:16 +00002991
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00002992 if (NumMatchedTemplateParamLists > 0 && D.getCXXScopeSpec().isSet()) {
2993 NewVD->setTemplateParameterListsInfo(Context,
2994 NumMatchedTemplateParamLists,
2995 TemplateParamLists.release());
2996 }
Abramo Bagnara9b934882010-06-12 08:15:14 +00002997 }
2998
Eli Friedman63054b32009-04-19 20:27:55 +00002999 if (D.getDeclSpec().isThreadSpecified()) {
3000 if (NewVD->hasLocalStorage())
3001 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
Eli Friedman4fb71b02009-04-19 21:48:33 +00003002 else if (!Context.Target.isTLSSupported())
3003 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
Eli Friedman63054b32009-04-19 20:27:55 +00003004 else
3005 NewVD->setThreadSpecified(true);
3006 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003007
Douglas Gregor656de632009-03-11 23:52:16 +00003008 // Set the lexical context. If the declarator has a C++ scope specifier, the
3009 // lexical context will be different from the semantic context.
3010 NewVD->setLexicalDeclContext(CurContext);
3011
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00003012 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003013 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00003014
3015 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner16c5dea2010-10-10 18:16:20 +00003016 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00003017 // The parser guarantees this is a string.
Mike Stump1eb44332009-09-09 15:08:12 +00003018 StringLiteral *SE = cast<StringLiteral>(E);
Rafael Espindolabaf86952011-01-01 21:47:03 +00003019 llvm::StringRef Label = SE->getString();
Abramo Bagnara2b57aef2011-01-11 15:16:52 +00003020 if (S->getFnParent() != 0) {
3021 switch (SC) {
3022 case SC_None:
3023 case SC_Auto:
3024 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
3025 break;
3026 case SC_Register:
3027 if (!Context.Target.isValidGCCRegisterName(Label))
3028 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
3029 break;
3030 case SC_Static:
3031 case SC_Extern:
3032 case SC_PrivateExtern:
3033 break;
3034 }
3035 }
3036
3037 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Rafael Espindolabaf86952011-01-01 21:47:03 +00003038 Context, Label));
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00003039 }
3040
John McCall8472af42010-03-16 21:48:18 +00003041 // Diagnose shadowed variables before filtering for scope.
John McCalla369a952010-03-20 04:12:52 +00003042 if (!D.getCXXScopeSpec().isSet())
John McCall053f4bd2010-03-22 09:20:08 +00003043 CheckShadow(S, NewVD, Previous);
John McCall8472af42010-03-16 21:48:18 +00003044
John McCall68263142009-11-18 22:49:29 +00003045 // Don't consider existing declarations that are in a different
3046 // scope and are out-of-semantic-context declarations (if the new
3047 // declaration has linkage).
3048 FilterLookupForScope(*this, Previous, DC, S, NewVD->hasLinkage());
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003049
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003050 if (!getLangOptions().CPlusPlus)
3051 CheckVariableDeclaration(NewVD, Previous, Redeclaration);
3052 else {
3053 // Merge the decl with the existing one if appropriate.
3054 if (!Previous.empty()) {
3055 if (Previous.isSingleResult() &&
3056 isa<FieldDecl>(Previous.getFoundDecl()) &&
3057 D.getCXXScopeSpec().isSet()) {
3058 // The user tried to define a non-static data member
3059 // out-of-line (C++ [dcl.meaning]p1).
3060 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
3061 << D.getCXXScopeSpec().getRange();
3062 Previous.clear();
3063 NewVD->setInvalidDecl();
3064 }
3065 } else if (D.getCXXScopeSpec().isSet()) {
3066 // No previous declaration in the qualifying scope.
3067 Diag(D.getIdentifierLoc(), diag::err_no_member)
3068 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00003069 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00003070 NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00003071 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003072
3073 CheckVariableDeclaration(NewVD, Previous, Redeclaration);
3074
3075 // This is an explicit specialization of a static data member. Check it.
3076 if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
3077 CheckMemberSpecialization(NewVD, Previous))
3078 NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00003079 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003080
Ryan Flynn478fbc62009-07-25 22:29:44 +00003081 // attributes declared post-definition are currently ignored
Sean Huntcf807c42010-08-18 23:23:40 +00003082 // FIXME: This should be handled in attribute merging, not
3083 // here.
John McCall68263142009-11-18 22:49:29 +00003084 if (Previous.isSingleResult()) {
Sebastian Redl31310a22010-02-01 20:16:42 +00003085 VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl());
3086 if (Def && (Def = Def->getDefinition()) &&
3087 Def != NewVD && D.hasAttributes()) {
Ryan Flynn478fbc62009-07-25 22:29:44 +00003088 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
3089 Diag(Def->getLocation(), diag::note_previous_definition);
3090 }
3091 }
3092
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00003093 // If this is a locally-scoped extern C variable, update the map of
3094 // such variables.
Douglas Gregor48a83b52009-09-12 00:17:51 +00003095 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
Chris Lattnereaaebc72009-04-25 08:06:05 +00003096 !NewVD->isInvalidDecl())
John McCall68263142009-11-18 22:49:29 +00003097 RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00003098
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003099 // If there's a #pragma GCC visibility in scope, and this isn't a class
3100 // member, set the visibility of this variable.
3101 if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord())
3102 AddPushedVisibilityAttribute(NewVD);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003103
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00003104 MarkUnusedFileScopedDecl(NewVD);
3105
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00003106 return NewVD;
3107}
3108
John McCall053f4bd2010-03-22 09:20:08 +00003109/// \brief Diagnose variable or built-in function shadowing. Implements
3110/// -Wshadow.
John McCall8472af42010-03-16 21:48:18 +00003111///
John McCall053f4bd2010-03-22 09:20:08 +00003112/// This method is called whenever a VarDecl is added to a "useful"
3113/// scope.
John McCall8472af42010-03-16 21:48:18 +00003114///
John McCalla369a952010-03-20 04:12:52 +00003115/// \param S the scope in which the shadowing name is being declared
3116/// \param R the lookup of the name
John McCall8472af42010-03-16 21:48:18 +00003117///
John McCall053f4bd2010-03-22 09:20:08 +00003118void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCall8472af42010-03-16 21:48:18 +00003119 // Return if warning is ignored.
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003120 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
3121 Diagnostic::Ignored)
John McCall8472af42010-03-16 21:48:18 +00003122 return;
3123
Argyrios Kyrtzidis651f86f2011-02-08 18:21:25 +00003124 // Don't diagnose declarations at file scope.
3125 DeclContext *NewDC = D->getDeclContext();
3126 if (NewDC->isFileContext())
John McCall8472af42010-03-16 21:48:18 +00003127 return;
John McCalla369a952010-03-20 04:12:52 +00003128
3129 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregorc48c9162010-03-17 16:03:44 +00003130 if (R.getResultKind() != LookupResult::Found)
John McCall8472af42010-03-16 21:48:18 +00003131 return;
John McCall8472af42010-03-16 21:48:18 +00003132
John McCall8472af42010-03-16 21:48:18 +00003133 NamedDecl* ShadowedDecl = R.getFoundDecl();
3134 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
3135 return;
3136
Argyrios Kyrtzidis36eb5e42011-01-31 07:04:54 +00003137 // Fields are not shadowed by variables in C++ static methods.
3138 if (isa<FieldDecl>(ShadowedDecl))
3139 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
3140 if (MD->isStatic())
3141 return;
3142
Argyrios Kyrtzidis49a61722011-01-31 07:04:50 +00003143 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
3144 if (shadowedVar->isExternC()) {
3145 // Don't warn for this case:
3146 //
3147 // @code
3148 // extern int bob;
3149 // void f() {
3150 // extern int bob;
3151 // }
3152 // @endcode
3153 if (D->isExternC())
Argyrios Kyrtzidis6df96e02011-01-31 07:04:41 +00003154 return;
3155
Argyrios Kyrtzidis49a61722011-01-31 07:04:50 +00003156 // For shadowing external vars, make sure that we point to the global
3157 // declaration, not a locally scoped extern declaration.
3158 for (VarDecl::redecl_iterator
3159 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
3160 I != E; ++I)
3161 if (I->isFileVarDecl()) {
3162 ShadowedDecl = *I;
3163 break;
3164 }
3165 }
3166
3167 DeclContext *OldDC = ShadowedDecl->getDeclContext();
3168
John McCalla369a952010-03-20 04:12:52 +00003169 // Only warn about certain kinds of shadowing for class members.
3170 if (NewDC && NewDC->isRecord()) {
3171 // In particular, don't warn about shadowing non-class members.
3172 if (!OldDC->isRecord())
3173 return;
3174
3175 // TODO: should we warn about static data members shadowing
3176 // static data members from base classes?
3177
3178 // TODO: don't diagnose for inaccessible shadowed members.
3179 // This is hard to do perfectly because we might friend the
3180 // shadowing context, but that's just a false negative.
3181 }
3182
3183 // Determine what kind of declaration we're shadowing.
John McCall8472af42010-03-16 21:48:18 +00003184 unsigned Kind;
John McCalla369a952010-03-20 04:12:52 +00003185 if (isa<RecordDecl>(OldDC)) {
John McCall8472af42010-03-16 21:48:18 +00003186 if (isa<FieldDecl>(ShadowedDecl))
3187 Kind = 3; // field
3188 else
3189 Kind = 2; // static data member
John McCalla369a952010-03-20 04:12:52 +00003190 } else if (OldDC->isFileContext())
John McCall8472af42010-03-16 21:48:18 +00003191 Kind = 1; // global
3192 else
3193 Kind = 0; // local
3194
John McCalla369a952010-03-20 04:12:52 +00003195 DeclarationName Name = R.getLookupName();
3196
John McCall8472af42010-03-16 21:48:18 +00003197 // Emit warning and note.
John McCalla369a952010-03-20 04:12:52 +00003198 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCall8472af42010-03-16 21:48:18 +00003199 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
3200}
3201
John McCall053f4bd2010-03-22 09:20:08 +00003202/// \brief Check -Wshadow without the advantage of a previous lookup.
3203void Sema::CheckShadow(Scope *S, VarDecl *D) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003204 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
3205 Diagnostic::Ignored)
3206 return;
3207
John McCall053f4bd2010-03-22 09:20:08 +00003208 LookupResult R(*this, D->getDeclName(), D->getLocation(),
3209 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
3210 LookupName(R, S);
3211 CheckShadow(S, D, R);
3212}
3213
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00003214/// \brief Perform semantic checking on a newly-created variable
3215/// declaration.
3216///
3217/// This routine performs all of the type-checking required for a
Douglas Gregor180bb632009-05-01 15:47:09 +00003218/// variable declaration once it has been built. It is used both to
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00003219/// check variables after they have been parsed and their declarators
Douglas Gregor180bb632009-05-01 15:47:09 +00003220/// have been translated into a declaration, and to check variables
3221/// that have been instantiated from a template.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00003222///
Chris Lattnereaaebc72009-04-25 08:06:05 +00003223/// Sets NewVD->isInvalidDecl() if an error was encountered.
John McCall68263142009-11-18 22:49:29 +00003224void Sema::CheckVariableDeclaration(VarDecl *NewVD,
3225 LookupResult &Previous,
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00003226 bool &Redeclaration) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00003227 // If the decl is already known invalid, don't check it.
3228 if (NewVD->isInvalidDecl())
3229 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003230
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00003231 QualType T = NewVD->getType();
3232
John McCallc12c5bb2010-05-15 11:32:37 +00003233 if (T->isObjCObjectType()) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00003234 Diag(NewVD->getLocation(), diag::err_statically_allocated_object);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003235 return NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00003236 }
Mike Stump1eb44332009-09-09 15:08:12 +00003237
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00003238 // Emit an error if an address space was applied to decl with local storage.
3239 // This includes arrays of objects with address space qualifiers, but not
3240 // automatic variables that point to other address spaces.
3241 // ISO/IEC TR 18037 S5.1.2
Chris Lattner16c5dea2010-10-10 18:16:20 +00003242 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00003243 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003244 return NewVD->setInvalidDecl();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00003245 }
Fariborz Jahanian7b5b3172009-02-21 19:44:02 +00003246
Mike Stumpf33651c2009-04-14 00:57:29 +00003247 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003248 && !NewVD->hasAttr<BlocksAttr>())
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00003249 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Chris Lattner16c5dea2010-10-10 18:16:20 +00003250
Chris Lattner38c5ebd2009-04-19 05:21:20 +00003251 bool isVM = T->isVariablyModifiedType();
Chris Lattnerbe6d2592009-07-19 20:17:11 +00003252 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalle46f62c2010-08-01 01:24:59 +00003253 NewVD->hasAttr<BlocksAttr>())
John McCall781472f2010-08-25 08:40:02 +00003254 getCurFunction()->setHasBranchProtectedScope();
Mike Stump1eb44332009-09-09 15:08:12 +00003255
Chris Lattner38c5ebd2009-04-19 05:21:20 +00003256 if ((isVM && NewVD->hasLinkage()) ||
3257 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00003258 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +00003259 llvm::APSInt Oversized;
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00003260 QualType FixedTy =
Douglas Gregor2767ce22010-08-18 00:39:00 +00003261 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
3262 Oversized);
Mike Stump1eb44332009-09-09 15:08:12 +00003263
Chris Lattnereaaebc72009-04-25 08:06:05 +00003264 if (FixedTy.isNull() && T->isVariableArrayType()) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00003265 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003266 // FIXME: This won't give the correct result for
3267 // int a[10][n];
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00003268 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003269
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00003270 if (NewVD->isFileVarDecl())
3271 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnereaaebc72009-04-25 08:06:05 +00003272 << SizeRange;
John McCalld931b082010-08-26 03:08:43 +00003273 else if (NewVD->getStorageClass() == SC_Static)
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00003274 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnereaaebc72009-04-25 08:06:05 +00003275 << SizeRange;
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00003276 else
3277 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnereaaebc72009-04-25 08:06:05 +00003278 << SizeRange;
3279 return NewVD->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003280 }
3281
Chris Lattnereaaebc72009-04-25 08:06:05 +00003282 if (FixedTy.isNull()) {
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00003283 if (NewVD->isFileVarDecl())
3284 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
3285 else
3286 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003287 return NewVD->setInvalidDecl();
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00003288 }
Mike Stump1eb44332009-09-09 15:08:12 +00003289
Chris Lattnereaaebc72009-04-25 08:06:05 +00003290 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
3291 NewVD->setType(FixedTy);
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00003292 }
3293
John McCall68263142009-11-18 22:49:29 +00003294 if (Previous.empty() && NewVD->isExternC()) {
Douglas Gregor63935192009-03-02 00:19:53 +00003295 // Since we did not find anything by this name and we're declaring
3296 // an extern "C" variable, look for a non-visible extern "C"
3297 // declaration with the same name.
3298 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00003299 = LocallyScopedExternalDecls.find(NewVD->getDeclName());
Douglas Gregor63935192009-03-02 00:19:53 +00003300 if (Pos != LocallyScopedExternalDecls.end())
John McCall68263142009-11-18 22:49:29 +00003301 Previous.addDecl(Pos->second);
Douglas Gregor63935192009-03-02 00:19:53 +00003302 }
3303
Chris Lattnereaaebc72009-04-25 08:06:05 +00003304 if (T->isVoidType() && !NewVD->hasExternalStorage()) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00003305 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
3306 << T;
Chris Lattnereaaebc72009-04-25 08:06:05 +00003307 return NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00003308 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00003309
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003310 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpea000bf2009-04-30 00:19:40 +00003311 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
3312 return NewVD->setInvalidDecl();
3313 }
Mike Stump1eb44332009-09-09 15:08:12 +00003314
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003315 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpc975bb02009-05-01 23:41:47 +00003316 Diag(NewVD->getLocation(), diag::err_block_on_vm);
3317 return NewVD->setInvalidDecl();
3318 }
3319
Sebastian Redlf9ea1f32010-07-12 23:11:43 +00003320 // Function pointers and references cannot have qualified function type, only
3321 // function pointer-to-members can do that.
3322 QualType Pointee;
3323 unsigned PtrOrRef = 0;
3324 if (const PointerType *Ptr = T->getAs<PointerType>())
3325 Pointee = Ptr->getPointeeType();
3326 else if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
3327 Pointee = Ref->getPointeeType();
3328 PtrOrRef = 1;
3329 }
3330 if (!Pointee.isNull() && Pointee->isFunctionProtoType() &&
3331 Pointee->getAs<FunctionProtoType>()->getTypeQuals() != 0) {
3332 Diag(NewVD->getLocation(), diag::err_invalid_qualified_function_pointer)
3333 << PtrOrRef;
3334 return NewVD->setInvalidDecl();
3335 }
3336
John McCall68263142009-11-18 22:49:29 +00003337 if (!Previous.empty()) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00003338 Redeclaration = true;
John McCall68263142009-11-18 22:49:29 +00003339 MergeVarDecl(NewVD, Previous);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00003340 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00003341}
3342
Douglas Gregora8f32e02009-10-06 17:59:45 +00003343/// \brief Data used with FindOverriddenMethod
3344struct FindOverriddenMethodData {
3345 Sema *S;
3346 CXXMethodDecl *Method;
3347};
3348
3349/// \brief Member lookup function that determines whether a given C++
3350/// method overrides a method in a base class, to be used with
3351/// CXXRecordDecl::lookupInBases().
John McCallaf8e6ed2009-11-12 03:15:40 +00003352static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregora8f32e02009-10-06 17:59:45 +00003353 CXXBasePath &Path,
3354 void *UserData) {
3355 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlsson95496802009-11-26 20:50:40 +00003356
Douglas Gregora8f32e02009-10-06 17:59:45 +00003357 FindOverriddenMethodData *Data
3358 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlsson95496802009-11-26 20:50:40 +00003359
3360 DeclarationName Name = Data->Method->getDeclName();
3361
3362 // FIXME: Do we care about other names here too?
3363 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCallad00b772010-06-16 08:42:20 +00003364 // We really want to find the base class destructor here.
Anders Carlsson95496802009-11-26 20:50:40 +00003365 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
3366 CanQualType CT = Data->S->Context.getCanonicalType(T);
3367
Anders Carlsson1a689722009-11-27 01:26:58 +00003368 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlsson95496802009-11-26 20:50:40 +00003369 }
3370
3371 for (Path.Decls = BaseRecord->lookup(Name);
Douglas Gregora8f32e02009-10-06 17:59:45 +00003372 Path.Decls.first != Path.Decls.second;
3373 ++Path.Decls.first) {
John McCall52a02752010-06-16 09:33:39 +00003374 NamedDecl *D = *Path.Decls.first;
John McCallad00b772010-06-16 08:42:20 +00003375 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
3376 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregora8f32e02009-10-06 17:59:45 +00003377 return true;
3378 }
3379 }
3380
3381 return false;
3382}
3383
Sebastian Redla165da02009-11-18 21:51:29 +00003384/// AddOverriddenMethods - See if a method overrides any in the base classes,
3385/// and if so, check that it's a valid override and remember it.
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00003386bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redla165da02009-11-18 21:51:29 +00003387 // Look for virtual methods in base classes that this method might override.
3388 CXXBasePaths Paths;
3389 FindOverriddenMethodData Data;
3390 Data.Method = MD;
3391 Data.S = this;
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00003392 bool AddedAny = false;
Sebastian Redla165da02009-11-18 21:51:29 +00003393 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
3394 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
3395 E = Paths.found_decls_end(); I != E; ++I) {
3396 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
3397 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Sean Huntbbd37c62009-11-21 08:43:09 +00003398 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
Anders Carlsson2e1c7302011-01-20 16:25:36 +00003399 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
Anders Carlsson3aaf4862009-12-04 05:51:56 +00003400 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00003401 AddedAny = true;
3402 }
Sebastian Redla165da02009-11-18 21:51:29 +00003403 }
3404 }
3405 }
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00003406
3407 return AddedAny;
Sebastian Redla165da02009-11-18 21:51:29 +00003408}
3409
John McCall29ae6e52010-10-13 05:45:15 +00003410static void DiagnoseInvalidRedeclaration(Sema &S, FunctionDecl *NewFD) {
3411 LookupResult Prev(S, NewFD->getDeclName(), NewFD->getLocation(),
3412 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
3413 S.LookupQualifiedName(Prev, NewFD->getDeclContext());
3414 assert(!Prev.isAmbiguous() &&
3415 "Cannot have an ambiguity in previous-declaration lookup");
3416 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
3417 Func != FuncEnd; ++Func) {
3418 if (isa<FunctionDecl>(*Func) &&
3419 isNearlyMatchingFunction(S.Context, cast<FunctionDecl>(*Func), NewFD))
3420 S.Diag((*Func)->getLocation(), diag::note_member_def_close_match);
3421 }
3422}
3423
Mike Stump1eb44332009-09-09 15:08:12 +00003424NamedDecl*
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003425Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
John McCalla93c9342009-12-07 02:54:59 +00003426 QualType R, TypeSourceInfo *TInfo,
John McCall68263142009-11-18 22:49:29 +00003427 LookupResult &Previous,
Douglas Gregore542c862009-06-23 23:11:28 +00003428 MultiTemplateParamsArg TemplateParamLists,
Chris Lattnereaaebc72009-04-25 08:06:05 +00003429 bool IsFunctionDefinition, bool &Redeclaration) {
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003430 assert(R.getTypePtr()->isFunctionType());
3431
Abramo Bagnara25777432010-08-11 22:01:17 +00003432 // TODO: consider using NameInfo for diagnostic.
3433 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3434 DeclarationName Name = NameInfo.getName();
John McCalld931b082010-08-26 03:08:43 +00003435 FunctionDecl::StorageClass SC = SC_None;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003436 switch (D.getDeclSpec().getStorageClassSpec()) {
3437 default: assert(0 && "Unknown storage class!");
3438 case DeclSpec::SCS_auto:
3439 case DeclSpec::SCS_register:
3440 case DeclSpec::SCS_mutable:
Mike Stump1eb44332009-09-09 15:08:12 +00003441 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregor04495c82009-02-24 01:23:02 +00003442 diag::err_typecheck_sclass_func);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003443 D.setInvalidType();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003444 break;
John McCalld931b082010-08-26 03:08:43 +00003445 case DeclSpec::SCS_unspecified: SC = SC_None; break;
3446 case DeclSpec::SCS_extern: SC = SC_Extern; break;
Douglas Gregor04495c82009-02-24 01:23:02 +00003447 case DeclSpec::SCS_static: {
Sebastian Redl7a126a42010-08-31 00:36:30 +00003448 if (CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregor04495c82009-02-24 01:23:02 +00003449 // C99 6.7.1p5:
3450 // The declaration of an identifier for a function that has
3451 // block scope shall have no explicit storage-class specifier
3452 // other than extern
3453 // See also (C++ [dcl.stc]p4).
Mike Stump1eb44332009-09-09 15:08:12 +00003454 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregor04495c82009-02-24 01:23:02 +00003455 diag::err_static_block_func);
John McCalld931b082010-08-26 03:08:43 +00003456 SC = SC_None;
Douglas Gregor04495c82009-02-24 01:23:02 +00003457 } else
John McCalld931b082010-08-26 03:08:43 +00003458 SC = SC_Static;
Douglas Gregor04495c82009-02-24 01:23:02 +00003459 break;
3460 }
Gabor Greifa4a301d2010-09-08 00:31:13 +00003461 case DeclSpec::SCS_private_extern: SC = SC_PrivateExtern; break;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003462 }
3463
Eli Friedman63054b32009-04-19 20:27:55 +00003464 if (D.getDeclSpec().isThreadSpecified())
3465 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
3466
Chris Lattnerbb749822009-04-11 19:17:25 +00003467 // Do not allow returning a objc interface by-value.
John McCallc12c5bb2010-05-15 11:32:37 +00003468 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
Chris Lattnerbb749822009-04-11 19:17:25 +00003469 Diag(D.getIdentifierLoc(),
3470 diag::err_object_cannot_be_passed_returned_by_value) << 0
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003471 << R->getAs<FunctionType>()->getResultType();
Chris Lattnereaaebc72009-04-25 08:06:05 +00003472 D.setInvalidType();
Chris Lattnerbb749822009-04-11 19:17:25 +00003473 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003474
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003475 FunctionDecl *NewFD;
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003476 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor3922ed02010-12-10 19:28:19 +00003477 bool isFriend = false;
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003478 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
3479 FunctionDecl::StorageClass SCAsWritten
3480 = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
Douglas Gregor3922ed02010-12-10 19:28:19 +00003481 FunctionTemplateDecl *FunctionTemplate = 0;
3482 bool isExplicitSpecialization = false;
3483 bool isFunctionTemplateSpecialization = false;
3484 unsigned NumMatchedTemplateParamLists = 0;
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003485
3486 if (!getLangOptions().CPlusPlus) {
Douglas Gregord874def2009-03-19 18:33:54 +00003487 // Determine whether the function was written with a
3488 // prototype. This true when:
Douglas Gregord874def2009-03-19 18:33:54 +00003489 // - there is a prototype in the declarator, or
3490 // - the type R of the function is some kind of typedef or other reference
3491 // to a type name (which eventually refers to a function type).
Mike Stump1eb44332009-09-09 15:08:12 +00003492 bool HasPrototype =
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003493 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003494 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
3495
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003496 NewFD = FunctionDecl::Create(Context, DC,
Abramo Bagnara25777432010-08-11 22:01:17 +00003497 NameInfo, R, TInfo, SC, SCAsWritten, isInline,
Douglas Gregor16573fa2010-04-19 22:54:31 +00003498 HasPrototype);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003499 if (D.isInvalidType())
3500 NewFD->setInvalidDecl();
3501
3502 // Set the lexical context.
3503 NewFD->setLexicalDeclContext(CurContext);
3504 // Filter out previous declarations that don't match the scope.
3505 FilterLookupForScope(*this, Previous, DC, S, NewFD->hasLinkage());
3506 } else {
3507 isFriend = D.getDeclSpec().isFriendSpecified();
Douglas Gregor3922ed02010-12-10 19:28:19 +00003508 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
3509 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
3510 bool isVirtualOkay = false;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003511
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003512 // Check that the return type is not an abstract class type.
3513 // For record types, this is done by the AbstractClassUsageDiagnoser once
3514 // the class has been completely parsed.
3515 if (!DC->isRecord() &&
3516 RequireNonAbstractType(D.getIdentifierLoc(),
3517 R->getAs<FunctionType>()->getResultType(),
3518 diag::err_abstract_type_in_decl,
3519 AbstractReturnType))
3520 D.setInvalidType();
Mike Stump1eb44332009-09-09 15:08:12 +00003521
John McCallb6217662010-03-15 10:12:16 +00003522
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003523 if (isFriend) {
3524 // C++ [class.friend]p5
3525 // A function can be defined in a friend declaration of a
3526 // class . . . . Such a function is implicitly inline.
3527 isInline |= IsFunctionDefinition;
3528 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003529
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003530 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
3531 // This is a C++ constructor declaration.
3532 assert(DC->isRecord() &&
3533 "Constructors can only be declared in a member context");
3534
3535 R = CheckConstructorDeclarator(D, R, SC);
3536
3537 // Create the new declaration
3538 NewFD = CXXConstructorDecl::Create(Context,
3539 cast<CXXRecordDecl>(DC),
3540 NameInfo, R, TInfo,
3541 isExplicit, isInline,
3542 /*isImplicitlyDeclared=*/false);
3543 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
3544 // This is a C++ destructor declaration.
3545 if (DC->isRecord()) {
3546 R = CheckDestructorDeclarator(D, R, SC);
3547
3548 NewFD = CXXDestructorDecl::Create(Context,
3549 cast<CXXRecordDecl>(DC),
3550 NameInfo, R, TInfo,
3551 isInline,
3552 /*isImplicitlyDeclared=*/false);
3553 isVirtualOkay = true;
3554 } else {
3555 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
3556
3557 // Create a FunctionDecl to satisfy the function definition parsing
3558 // code path.
3559 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
3560 Name, R, TInfo, SC, SCAsWritten, isInline,
3561 /*hasPrototype=*/true);
3562 D.setInvalidType();
3563 }
3564 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
3565 if (!DC->isRecord()) {
3566 Diag(D.getIdentifierLoc(),
3567 diag::err_conv_function_not_member);
3568 return 0;
3569 }
3570
3571 CheckConversionDeclarator(D, R, SC);
3572 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
3573 NameInfo, R, TInfo,
3574 isInline, isExplicit);
3575
3576 isVirtualOkay = true;
3577 } else if (DC->isRecord()) {
3578 // If the of the function is the same as the name of the record, then this
3579 // must be an invalid constructor that has a return type.
3580 // (The parser checks for a return type and makes the declarator a
3581 // constructor if it has no return type).
3582 // must have an invalid constructor that has a return type
3583 if (Name.getAsIdentifierInfo() &&
3584 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
3585 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
3586 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3587 << SourceRange(D.getIdentifierLoc());
3588 return 0;
3589 }
3590
3591 bool isStatic = SC == SC_Static;
3592
3593 // [class.free]p1:
3594 // Any allocation function for a class T is a static member
3595 // (even if not explicitly declared static).
3596 if (Name.getCXXOverloadedOperator() == OO_New ||
3597 Name.getCXXOverloadedOperator() == OO_Array_New)
3598 isStatic = true;
3599
3600 // [class.free]p6 Any deallocation function for a class X is a static member
3601 // (even if not explicitly declared static).
3602 if (Name.getCXXOverloadedOperator() == OO_Delete ||
3603 Name.getCXXOverloadedOperator() == OO_Array_Delete)
3604 isStatic = true;
3605
3606 // This is a C++ method declaration.
3607 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
3608 NameInfo, R, TInfo,
3609 isStatic, SCAsWritten, isInline);
3610
3611 isVirtualOkay = !isStatic;
3612 } else {
3613 // Determine whether the function was written with a
3614 // prototype. This true when:
3615 // - we're in C++ (where every function has a prototype),
3616 NewFD = FunctionDecl::Create(Context, DC,
3617 NameInfo, R, TInfo, SC, SCAsWritten, isInline,
3618 true/*HasPrototype*/);
3619 }
3620 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003621 isExplicitSpecialization = false;
3622 isFunctionTemplateSpecialization = false;
3623 NumMatchedTemplateParamLists = TemplateParamLists.size();
3624 if (D.isInvalidType())
3625 NewFD->setInvalidDecl();
3626
3627 // Set the lexical context. If the declarator has a C++
3628 // scope specifier, or is the object of a friend declaration, the
3629 // lexical context will be different from the semantic context.
3630 NewFD->setLexicalDeclContext(CurContext);
3631
3632 // Match up the template parameter lists with the scope specifier, then
3633 // determine whether we have a template or a template specialization.
3634 bool Invalid = false;
3635 if (TemplateParameterList *TemplateParams
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003636 = MatchTemplateParametersToScopeSpecifier(
3637 D.getDeclSpec().getSourceRange().getBegin(),
3638 D.getCXXScopeSpec(),
John McCall6102ca12010-10-16 06:59:13 +00003639 TemplateParamLists.get(),
3640 TemplateParamLists.size(),
3641 isFriend,
3642 isExplicitSpecialization,
3643 Invalid)) {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003644 // All but one template parameter lists have been matching.
3645 --NumMatchedTemplateParamLists;
Abramo Bagnara9b934882010-06-12 08:15:14 +00003646
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003647 if (TemplateParams->size() > 0) {
3648 // This is a function template
Mike Stump1eb44332009-09-09 15:08:12 +00003649
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003650 // Check that we can declare a template here.
3651 if (CheckTemplateDeclScope(S, TemplateParams))
3652 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003653
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003654 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
Douglas Gregorc5c903a2009-06-24 00:23:40 +00003655 NewFD->getLocation(),
3656 Name, TemplateParams,
3657 NewFD);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003658 FunctionTemplate->setLexicalDeclContext(CurContext);
3659 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
3660 } else {
3661 // This is a function template specialization.
3662 isFunctionTemplateSpecialization = true;
John McCall7ad650f2010-03-24 07:46:06 +00003663
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003664 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
3665 if (isFriend && isFunctionTemplateSpecialization) {
3666 // We want to remove the "template<>", found here.
3667 SourceRange RemoveRange = TemplateParams->getSourceRange();
John McCall5fd378b2010-03-24 08:27:58 +00003668
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003669 // If we remove the template<> and the name is not a
3670 // template-id, we're actually silently creating a problem:
3671 // the friend declaration will refer to an untemplated decl,
3672 // and clearly the user wants a template specialization. So
3673 // we need to insert '<>' after the name.
3674 SourceLocation InsertLoc;
3675 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
3676 InsertLoc = D.getName().getSourceRange().getEnd();
3677 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
3678 }
3679
3680 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
3681 << Name << RemoveRange
3682 << FixItHint::CreateRemoval(RemoveRange)
3683 << FixItHint::CreateInsertion(InsertLoc, "<>");
3684 }
3685 }
John McCall5fd378b2010-03-24 08:27:58 +00003686 }
3687
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003688 if (NumMatchedTemplateParamLists > 0 && D.getCXXScopeSpec().isSet()) {
3689 NewFD->setTemplateParameterListsInfo(Context,
3690 NumMatchedTemplateParamLists,
3691 TemplateParamLists.release());
3692 }
3693
3694 if (Invalid) {
3695 NewFD->setInvalidDecl();
3696 if (FunctionTemplate)
3697 FunctionTemplate->setInvalidDecl();
3698 }
3699
3700 // C++ [dcl.fct.spec]p5:
3701 // The virtual specifier shall only be used in declarations of
3702 // nonstatic class member functions that appear within a
3703 // member-specification of a class declaration; see 10.3.
3704 //
3705 if (isVirtual && !NewFD->isInvalidDecl()) {
3706 if (!isVirtualOkay) {
3707 Diag(D.getDeclSpec().getVirtualSpecLoc(),
3708 diag::err_virtual_non_function);
3709 } else if (!CurContext->isRecord()) {
3710 // 'virtual' was specified outside of the class.
Anders Carlssonf1602a52011-01-22 14:43:56 +00003711 Diag(D.getDeclSpec().getVirtualSpecLoc(),
3712 diag::err_virtual_out_of_class)
3713 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
3714 } else if (NewFD->getDescribedFunctionTemplate()) {
3715 // C++ [temp.mem]p3:
3716 // A member function template shall not be virtual.
3717 Diag(D.getDeclSpec().getVirtualSpecLoc(),
3718 diag::err_virtual_member_function_template)
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003719 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
3720 } else {
3721 // Okay: Add virtual to the method.
3722 NewFD->setVirtualAsWritten(true);
John McCall7ad650f2010-03-24 07:46:06 +00003723 }
Douglas Gregorc5c903a2009-06-24 00:23:40 +00003724 }
Abramo Bagnara9b934882010-06-12 08:15:14 +00003725
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003726 // C++ [dcl.fct.spec]p3:
3727 // The inline specifier shall not appear on a block scope function declaration.
3728 if (isInline && !NewFD->isInvalidDecl()) {
3729 if (CurContext->isFunctionOrMethod()) {
3730 // 'inline' is not allowed on block scope function declaration.
3731 Diag(D.getDeclSpec().getInlineSpecLoc(),
3732 diag::err_inline_declaration_block_scope) << Name
3733 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
3734 }
3735 }
3736
3737 // C++ [dcl.fct.spec]p6:
3738 // The explicit specifier shall be used only in the declaration of a
3739 // constructor or conversion function within its class definition; see 12.3.1
3740 // and 12.3.2.
3741 if (isExplicit && !NewFD->isInvalidDecl()) {
3742 if (!CurContext->isRecord()) {
3743 // 'explicit' was specified outside of the class.
3744 Diag(D.getDeclSpec().getExplicitSpecLoc(),
3745 diag::err_explicit_out_of_class)
3746 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
3747 } else if (!isa<CXXConstructorDecl>(NewFD) &&
3748 !isa<CXXConversionDecl>(NewFD)) {
3749 // 'explicit' was specified on a function that wasn't a constructor
3750 // or conversion function.
3751 Diag(D.getDeclSpec().getExplicitSpecLoc(),
3752 diag::err_explicit_non_ctor_or_conv_function)
3753 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
3754 }
3755 }
Abramo Bagnara9b934882010-06-12 08:15:14 +00003756
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003757 // Filter out previous declarations that don't match the scope.
3758 FilterLookupForScope(*this, Previous, DC, S, NewFD->hasLinkage());
3759
3760 if (isFriend) {
3761 // For now, claim that the objects have no previous declaration.
3762 if (FunctionTemplate) {
3763 FunctionTemplate->setObjectOfFriendDecl(false);
3764 FunctionTemplate->setAccess(AS_public);
3765 }
3766 NewFD->setObjectOfFriendDecl(false);
3767 NewFD->setAccess(AS_public);
3768 }
3769
John McCallbfdcdc82010-12-15 04:00:32 +00003770 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && IsFunctionDefinition) {
3771 // A method is implicitly inline if it's defined in its class
3772 // definition.
3773 NewFD->setImplicitlyInline();
3774 }
3775
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003776 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
3777 !CurContext->isRecord()) {
3778 // C++ [class.static]p1:
3779 // A data or function member of a class may be declared static
3780 // in a class definition, in which case it is a static member of
3781 // the class.
3782
3783 // Complain about the 'static' specifier if it's on an out-of-line
3784 // member function definition.
3785 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
3786 diag::err_static_out_of_line)
3787 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3788 }
Douglas Gregor0167f3c2010-07-14 23:14:12 +00003789 }
3790
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003791 // Handle GNU asm-label extension (encoded as an attribute).
3792 if (Expr *E = (Expr*) D.getAsmLabel()) {
3793 // The parser guarantees this is a string.
Mike Stump1eb44332009-09-09 15:08:12 +00003794 StringLiteral *SE = cast<StringLiteral>(E);
Sean Huntcf807c42010-08-18 23:23:40 +00003795 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
3796 SE->getString()));
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003797 }
3798
Chris Lattner2dbd2852009-04-25 06:12:16 +00003799 // Copy the parameter declarations from the declarator D to the function
3800 // declaration NewFD, if they are available. First scavenge them into Params.
3801 llvm::SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara723df242010-12-14 22:11:44 +00003802 if (D.isFunctionDeclarator()) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00003803 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003804
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003805 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
3806 // function that takes no arguments, not a function that takes a
3807 // single void argument.
3808 // We let through "const void" here because Sema::GetTypeForDeclarator
3809 // already checks for that case.
3810 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3811 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00003812 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
Chris Lattner2dbd2852009-04-25 06:12:16 +00003813 // Empty arg list, don't push any params.
John McCalld226f652010-08-21 09:40:31 +00003814 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[0].Param);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003815
3816 // In C++, the empty parameter-type-list must be spelled "void"; a
3817 // typedef of void is not permitted.
3818 if (getLangOptions().CPlusPlus &&
Chris Lattner584be452009-04-25 05:44:12 +00003819 Param->getType().getUnqualifiedType() != Context.VoidTy)
Douglas Gregora3a83512009-04-01 23:51:29 +00003820 Diag(Param->getLocation(), diag::err_param_typedef_of_void);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003821 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00003822 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00003823 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00003824 assert(Param->getDeclContext() != NewFD && "Was set before ?");
3825 Param->setDeclContext(NewFD);
3826 Params.push_back(Param);
John McCallf19de1c2010-04-14 01:27:20 +00003827
3828 if (Param->isInvalidDecl())
3829 NewFD->setInvalidDecl();
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00003830 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003831 }
Mike Stump1eb44332009-09-09 15:08:12 +00003832
John McCall183700f2009-09-21 23:43:11 +00003833 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner1ad9b282009-04-25 06:03:53 +00003834 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003835 // following example, we'll need to synthesize (unnamed)
3836 // parameters for use in the declaration.
3837 //
3838 // @code
3839 // typedef void fn(int);
3840 // fn f;
3841 // @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003842
Chris Lattner1ad9b282009-04-25 06:03:53 +00003843 // Synthesize a parameter for each argument type.
Chris Lattner1ad9b282009-04-25 06:03:53 +00003844 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
3845 AE = FT->arg_type_end(); AI != AE; ++AI) {
John McCall82dc0092010-06-04 11:21:44 +00003846 ParmVarDecl *Param =
3847 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
Chris Lattner1ad9b282009-04-25 06:03:53 +00003848 Params.push_back(Param);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003849 }
Chris Lattner84bb9442009-04-25 18:38:18 +00003850 } else {
3851 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
3852 "Should not need args for typedef of non-prototype fn");
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003853 }
Chris Lattner2dbd2852009-04-25 06:12:16 +00003854 // Finally, we know we have the right number of parameters, install them.
Douglas Gregor838db382010-02-11 01:19:42 +00003855 NewFD->setParams(Params.data(), Params.size());
Mike Stump1eb44332009-09-09 15:08:12 +00003856
Peter Collingbournec80e8112011-01-21 02:08:54 +00003857 // Process the non-inheritable attributes on this declaration.
3858 ProcessDeclAttributes(S, NewFD, D,
3859 /*NonInheritable=*/true, /*Inheritable=*/false);
3860
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003861 if (!getLangOptions().CPlusPlus) {
3862 // Perform semantic checking on the function declaration.
Fariborz Jahanian9913d6e2010-12-10 17:05:33 +00003863 bool isExplctSpecialization=false;
3864 CheckFunctionDeclaration(S, NewFD, Previous, isExplctSpecialization,
Peter Collingbournec80e8112011-01-21 02:08:54 +00003865 Redeclaration);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003866 assert((NewFD->isInvalidDecl() || !Redeclaration ||
3867 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
3868 "previous declaration set still overloaded");
3869 } else {
3870 // If the declarator is a template-id, translate the parser's template
3871 // argument list into our AST format.
3872 bool HasExplicitTemplateArgs = false;
3873 TemplateArgumentListInfo TemplateArgs;
3874 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
3875 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3876 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
3877 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
3878 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3879 TemplateId->getTemplateArgs(),
3880 TemplateId->NumArgs);
3881 translateTemplateArguments(TemplateArgsPtr,
3882 TemplateArgs);
3883 TemplateArgsPtr.release();
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00003884
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003885 HasExplicitTemplateArgs = true;
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00003886
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003887 if (FunctionTemplate) {
Douglas Gregor5505c722011-01-24 18:54:39 +00003888 // Function template with explicit template arguments.
3889 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
3890 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
3891
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003892 HasExplicitTemplateArgs = false;
3893 } else if (!isFunctionTemplateSpecialization &&
3894 !D.getDeclSpec().isFriendSpecified()) {
3895 // We have encountered something that the user meant to be a
3896 // specialization (because it has explicitly-specified template
3897 // arguments) but that was not introduced with a "template<>" (or had
3898 // too few of them).
3899 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
3900 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
3901 << FixItHint::CreateInsertion(
3902 D.getDeclSpec().getSourceRange().getBegin(),
3903 "template<> ");
3904 isFunctionTemplateSpecialization = true;
John McCall29ae6e52010-10-13 05:45:15 +00003905 } else {
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003906 // "friend void foo<>(int);" is an implicit specialization decl.
3907 isFunctionTemplateSpecialization = true;
Francois Pichetc71d8eb2010-10-01 21:19:28 +00003908 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003909 } else if (isFriend && isFunctionTemplateSpecialization) {
3910 // This combination is only possible in a recovery case; the user
3911 // wrote something like:
3912 // template <> friend void foo(int);
3913 // which we're recovering from as if the user had written:
3914 // friend void foo<>(int);
3915 // Go ahead and fake up a template id.
3916 HasExplicitTemplateArgs = true;
3917 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
3918 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003919 }
John McCall29ae6e52010-10-13 05:45:15 +00003920
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003921 // If it's a friend (and only if it's a friend), it's possible
3922 // that either the specialized function type or the specialized
3923 // template is dependent, and therefore matching will fail. In
3924 // this case, don't check the specialization yet.
3925 if (isFunctionTemplateSpecialization && isFriend &&
3926 (NewFD->getType()->isDependentType() || DC->isDependentContext())) {
3927 assert(HasExplicitTemplateArgs &&
3928 "friend function specialization without template args");
3929 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
3930 Previous))
3931 NewFD->setInvalidDecl();
3932 } else if (isFunctionTemplateSpecialization) {
3933 if (CheckFunctionTemplateSpecialization(NewFD,
3934 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
3935 Previous))
3936 NewFD->setInvalidDecl();
3937 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
3938 if (CheckMemberSpecialization(NewFD, Previous))
3939 NewFD->setInvalidDecl();
3940 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003941
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003942 // Perform semantic checking on the function declaration.
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003943 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization,
Peter Collingbournec80e8112011-01-21 02:08:54 +00003944 Redeclaration);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003945
3946 assert((NewFD->isInvalidDecl() || !Redeclaration ||
3947 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
3948 "previous declaration set still overloaded");
3949
3950 NamedDecl *PrincipalDecl = (FunctionTemplate
3951 ? cast<NamedDecl>(FunctionTemplate)
3952 : NewFD);
3953
3954 if (isFriend && Redeclaration) {
3955 AccessSpecifier Access = AS_public;
3956 if (!NewFD->isInvalidDecl())
3957 Access = NewFD->getPreviousDeclaration()->getAccess();
3958
3959 NewFD->setAccess(Access);
3960 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
3961
3962 PrincipalDecl->setObjectOfFriendDecl(true);
3963 }
3964
3965 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
3966 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
3967 PrincipalDecl->setNonMemberOperator();
3968
3969 // If we have a function template, check the template parameter
3970 // list. This will check and merge default template arguments.
3971 if (FunctionTemplate) {
3972 FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration();
3973 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
3974 PrevTemplate? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregord89d86f2011-02-04 04:20:44 +00003975 D.getDeclSpec().isFriendSpecified()
3976 ? (IsFunctionDefinition
3977 ? TPC_FriendFunctionTemplateDefinition
3978 : TPC_FriendFunctionTemplate)
3979 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor461bf2e2011-02-04 12:22:53 +00003980 DC && DC->isRecord() &&
3981 DC->isDependentContext())
Douglas Gregord89d86f2011-02-04 04:20:44 +00003982 ? TPC_ClassTemplateMember
3983 : TPC_FunctionTemplate);
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00003984 }
3985
3986 if (NewFD->isInvalidDecl()) {
3987 // Ignore all the rest of this.
3988 } else if (!Redeclaration) {
3989 // Fake up an access specifier if it's supposed to be a class member.
3990 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
3991 NewFD->setAccess(AS_public);
3992
3993 // Qualified decls generally require a previous declaration.
3994 if (D.getCXXScopeSpec().isSet()) {
3995 // ...with the major exception of templated-scope or
3996 // dependent-scope friend declarations.
3997
3998 // TODO: we currently also suppress this check in dependent
3999 // contexts because (1) the parameter depth will be off when
4000 // matching friend templates and (2) we might actually be
4001 // selecting a friend based on a dependent factor. But there
4002 // are situations where these conditions don't apply and we
4003 // can actually do this check immediately.
4004 if (isFriend &&
4005 (NumMatchedTemplateParamLists ||
4006 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
4007 CurContext->isDependentContext())) {
4008 // ignore these
4009 } else {
4010 // The user tried to provide an out-of-line definition for a
4011 // function that is a member of a class or namespace, but there
4012 // was no such member function declared (C++ [class.mfct]p2,
4013 // C++ [namespace.memdef]p2). For example:
4014 //
4015 // class X {
4016 // void f() const;
4017 // };
4018 //
4019 // void X::f() { } // ill-formed
4020 //
4021 // Complain about this problem, and attempt to suggest close
4022 // matches (e.g., those that differ only in cv-qualifiers and
4023 // whether the parameter types are references).
4024 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
4025 << Name << DC << D.getCXXScopeSpec().getRange();
4026 NewFD->setInvalidDecl();
4027
4028 DiagnoseInvalidRedeclaration(*this, NewFD);
4029 }
4030
4031 // Unqualified local friend declarations are required to resolve
4032 // to something.
4033 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
4034 Diag(D.getIdentifierLoc(), diag::err_no_matching_local_friend);
4035 NewFD->setInvalidDecl();
4036 DiagnoseInvalidRedeclaration(*this, NewFD);
4037 }
4038
4039 } else if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
4040 !isFriend && !isFunctionTemplateSpecialization &&
4041 !isExplicitSpecialization) {
4042 // An out-of-line member function declaration must also be a
4043 // definition (C++ [dcl.meaning]p1).
4044 // Note that this is not the case for explicit specializations of
4045 // function templates or member functions of class templates, per
4046 // C++ [temp.expl.spec]p2. We also allow these declarations as an extension
4047 // for compatibility with old SWIG code which likes to generate them.
4048 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
4049 << D.getCXXScopeSpec().getRange();
4050 }
4051 }
4052
4053
Douglas Gregor2dc0e642009-03-23 23:06:20 +00004054 // Handle attributes. We need to have merged decls when handling attributes
4055 // (for example to check for conflicts, etc).
4056 // FIXME: This needs to happen before we merge declarations. Then,
4057 // let attribute merging cope with attribute conflicts.
Peter Collingbournec80e8112011-01-21 02:08:54 +00004058 ProcessDeclAttributes(S, NewFD, D,
4059 /*NonInheritable=*/false, /*Inheritable=*/true);
Ryan Flynn478fbc62009-07-25 22:29:44 +00004060
4061 // attributes declared post-definition are currently ignored
Sean Huntcf807c42010-08-18 23:23:40 +00004062 // FIXME: This should happen during attribute merging
John McCall68263142009-11-18 22:49:29 +00004063 if (Redeclaration && Previous.isSingleResult()) {
4064 const FunctionDecl *Def;
4065 FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00004066 if (PrevFD && PrevFD->hasBody(Def) && D.hasAttributes()) {
Ryan Flynn478fbc62009-07-25 22:29:44 +00004067 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
4068 Diag(Def->getLocation(), diag::note_previous_definition);
4069 }
4070 }
4071
Douglas Gregor2dc0e642009-03-23 23:06:20 +00004072 AddKnownFunctionAttributes(NewFD);
4073
Douglas Gregord9455382010-08-06 13:50:58 +00004074 if (NewFD->hasAttr<OverloadableAttr>() &&
4075 !NewFD->getType()->getAs<FunctionProtoType>()) {
4076 Diag(NewFD->getLocation(),
4077 diag::err_attribute_overloadable_no_prototype)
4078 << NewFD;
4079
4080 // Turn this into a variadic function with no parameters.
4081 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
John McCalle23cf432010-12-14 08:05:40 +00004082 FunctionProtoType::ExtProtoInfo EPI;
4083 EPI.Variadic = true;
4084 EPI.ExtInfo = FT->getExtInfo();
4085
4086 QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI);
Douglas Gregord9455382010-08-06 13:50:58 +00004087 NewFD->setType(R);
4088 }
4089
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00004090 // If there's a #pragma GCC visibility in scope, and this isn't a class
4091 // member, set the visibility of this function.
4092 if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
4093 AddPushedVisibilityAttribute(NewFD);
4094
Douglas Gregor2dc0e642009-03-23 23:06:20 +00004095 // If this is a locally-scoped extern C function, update the
4096 // map of such names.
Douglas Gregor48a83b52009-09-12 00:17:51 +00004097 if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
Chris Lattnereaaebc72009-04-25 08:06:05 +00004098 && !NewFD->isInvalidDecl())
John McCall68263142009-11-18 22:49:29 +00004099 RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00004100
Argyrios Kyrtzidis16f19302009-06-25 18:22:24 +00004101 // Set this FunctionDecl's range up to the right paren.
4102 NewFD->setLocEnd(D.getSourceRange().getEnd());
4103
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00004104 if (getLangOptions().CPlusPlus) {
4105 if (FunctionTemplate) {
4106 if (NewFD->isInvalidDecl())
4107 FunctionTemplate->setInvalidDecl();
4108 return FunctionTemplate;
4109 }
Fariborz Jahanianbfe57882010-12-09 23:11:32 +00004110 }
Mike Stump1eb44332009-09-09 15:08:12 +00004111
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004112 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00004113
4114 if (getLangOptions().CUDA)
4115 if (IdentifierInfo *II = NewFD->getIdentifier())
4116 if (!NewFD->isInvalidDecl() &&
4117 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
4118 if (II->isStr("cudaConfigureCall")) {
4119 if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
4120 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
4121
4122 Context.setcudaConfigureCallDecl(NewFD);
4123 }
4124 }
4125
Douglas Gregor2dc0e642009-03-23 23:06:20 +00004126 return NewFD;
4127}
4128
4129/// \brief Perform semantic checking of a new function declaration.
4130///
4131/// Performs semantic analysis of the new function declaration
4132/// NewFD. This routine performs all semantic checking that does not
4133/// require the actual declarator involved in the declaration, and is
4134/// used both for the declaration of functions as they are parsed
4135/// (called via ActOnDeclarator) and for the declaration of functions
4136/// that have been instantiated via C++ template instantiation (called
4137/// via InstantiateDecl).
4138///
Douglas Gregorfd056bc2009-10-13 16:30:37 +00004139/// \param IsExplicitSpecialiation whether this new function declaration is
4140/// an explicit specialization of the previous declaration.
4141///
Chris Lattnereaaebc72009-04-25 08:06:05 +00004142/// This sets NewFD->isInvalidDecl() to true if there was an error.
John McCall9f54ad42009-12-10 09:41:52 +00004143void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall68263142009-11-18 22:49:29 +00004144 LookupResult &Previous,
Douglas Gregorfd056bc2009-10-13 16:30:37 +00004145 bool IsExplicitSpecialization,
Peter Collingbournec80e8112011-01-21 02:08:54 +00004146 bool &Redeclaration) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00004147 // If NewFD is already known erroneous, don't do any of this checking.
John McCallfcadea22010-08-12 00:57:17 +00004148 if (NewFD->isInvalidDecl()) {
4149 // If this is a class member, mark the class invalid immediately.
4150 // This avoids some consistency errors later.
4151 if (isa<CXXMethodDecl>(NewFD))
4152 cast<CXXMethodDecl>(NewFD)->getParent()->setInvalidDecl();
4153
Chris Lattnereaaebc72009-04-25 08:06:05 +00004154 return;
John McCallfcadea22010-08-12 00:57:17 +00004155 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00004156
Eli Friedman88f7b572009-05-16 12:15:55 +00004157 if (NewFD->getResultType()->isVariablyModifiedType()) {
4158 // Functions returning a variably modified type violate C99 6.7.5.2p2
4159 // because all functions have linkage.
4160 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
4161 return NewFD->setInvalidDecl();
4162 }
4163
Douglas Gregor48a83b52009-09-12 00:17:51 +00004164 if (NewFD->isMain())
4165 CheckMain(NewFD);
John McCall8c4859a2009-07-24 03:03:21 +00004166
Douglas Gregor2dc0e642009-03-23 23:06:20 +00004167 // Check for a previous declaration of this name.
John McCall68263142009-11-18 22:49:29 +00004168 if (Previous.empty() && NewFD->isExternC()) {
Douglas Gregor63935192009-03-02 00:19:53 +00004169 // Since we did not find anything by this name and we're declaring
4170 // an extern "C" function, look for a non-visible extern "C"
4171 // declaration with the same name.
4172 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregor2dc0e642009-03-23 23:06:20 +00004173 = LocallyScopedExternalDecls.find(NewFD->getDeclName());
Douglas Gregor63935192009-03-02 00:19:53 +00004174 if (Pos != LocallyScopedExternalDecls.end())
John McCall68263142009-11-18 22:49:29 +00004175 Previous.addDecl(Pos->second);
Douglas Gregor63935192009-03-02 00:19:53 +00004176 }
4177
Douglas Gregor04495c82009-02-24 01:23:02 +00004178 // Merge or overload the declaration with an existing declaration of
4179 // the same name, if appropriate.
John McCall68263142009-11-18 22:49:29 +00004180 if (!Previous.empty()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00004181 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00004182 // a declaration that requires merging. If it's an overload,
4183 // there's no more work to do here; we'll just add the new
4184 // function to the scope.
Douglas Gregorae170942009-02-13 00:26:38 +00004185
John McCall68263142009-11-18 22:49:29 +00004186 NamedDecl *OldDecl = 0;
John McCall871b2e72009-12-09 03:35:25 +00004187 if (!AllowOverloadingOfFunction(Previous, Context)) {
4188 Redeclaration = true;
4189 OldDecl = Previous.getFoundDecl();
4190 } else {
John McCallad00b772010-06-16 08:42:20 +00004191 switch (CheckOverload(S, NewFD, Previous, OldDecl,
4192 /*NewIsUsingDecl*/ false)) {
John McCall871b2e72009-12-09 03:35:25 +00004193 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00004194 Redeclaration = true;
John McCall871b2e72009-12-09 03:35:25 +00004195 break;
4196
4197 case Ovl_NonFunction:
4198 Redeclaration = true;
4199 break;
4200
4201 case Ovl_Overload:
4202 Redeclaration = false;
4203 break;
John McCall68263142009-11-18 22:49:29 +00004204 }
Peter Collingbournec80e8112011-01-21 02:08:54 +00004205
4206 if (!getLangOptions().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
4207 // If a function name is overloadable in C, then every function
4208 // with that name must be marked "overloadable".
4209 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
4210 << Redeclaration << NewFD;
4211 NamedDecl *OverloadedDecl = 0;
4212 if (Redeclaration)
4213 OverloadedDecl = OldDecl;
4214 else if (!Previous.empty())
4215 OverloadedDecl = Previous.getRepresentativeDecl();
4216 if (OverloadedDecl)
4217 Diag(OverloadedDecl->getLocation(),
4218 diag::note_attribute_overloadable_prev_overload);
4219 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
4220 Context));
4221 }
John McCall68263142009-11-18 22:49:29 +00004222 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00004223
John McCall68263142009-11-18 22:49:29 +00004224 if (Redeclaration) {
Douglas Gregor2dc0e642009-03-23 23:06:20 +00004225 // NewFD and OldDecl represent declarations that need to be
Mike Stump1eb44332009-09-09 15:08:12 +00004226 // merged.
Douglas Gregorcda9c672009-02-16 17:45:42 +00004227 if (MergeFunctionDecl(NewFD, OldDecl))
Chris Lattnereaaebc72009-04-25 08:06:05 +00004228 return NewFD->setInvalidDecl();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00004229
John McCall68263142009-11-18 22:49:29 +00004230 Previous.clear();
4231 Previous.addDecl(OldDecl);
4232
Douglas Gregore53060f2009-06-25 22:08:12 +00004233 if (FunctionTemplateDecl *OldTemplateDecl
Douglas Gregor37d681852009-10-12 22:27:17 +00004234 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
Douglas Gregorfd056bc2009-10-13 16:30:37 +00004235 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
Douglas Gregor37d681852009-10-12 22:27:17 +00004236 FunctionTemplateDecl *NewTemplateDecl
4237 = NewFD->getDescribedFunctionTemplate();
4238 assert(NewTemplateDecl && "Template/non-template mismatch");
4239 if (CXXMethodDecl *Method
4240 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
4241 Method->setAccess(OldTemplateDecl->getAccess());
4242 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
4243 }
Douglas Gregorfd056bc2009-10-13 16:30:37 +00004244
4245 // If this is an explicit specialization of a member that is a function
4246 // template, mark it as a member specialization.
4247 if (IsExplicitSpecialization &&
4248 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
4249 NewTemplateDecl->setMemberSpecialization();
4250 assert(OldTemplateDecl->isMemberSpecialization());
4251 }
Douglas Gregor37d681852009-10-12 22:27:17 +00004252 } else {
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00004253 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
4254 NewFD->setAccess(OldDecl->getAccess());
Douglas Gregore53060f2009-06-25 22:08:12 +00004255 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00004256 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00004257 }
Douglas Gregor4ce205f2009-02-06 17:46:57 +00004258 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00004259
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00004260 // Semantic checking for this function declaration (in isolation).
4261 if (getLangOptions().CPlusPlus) {
4262 // C++-specific checks.
4263 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
4264 CheckConstructor(Constructor);
Anders Carlsson6d701392009-11-15 22:49:34 +00004265 } else if (CXXDestructorDecl *Destructor =
4266 dyn_cast<CXXDestructorDecl>(NewFD)) {
4267 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00004268 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson6d701392009-11-15 22:49:34 +00004269
Douglas Gregor4923aa22010-07-02 20:37:36 +00004270 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson6d701392009-11-15 22:49:34 +00004271 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00004272 if (!ClassType->isDependentType()) {
4273 DeclarationName Name
4274 = Context.DeclarationNames.getCXXDestructorName(
4275 Context.getCanonicalType(ClassType));
4276 if (NewFD->getDeclName() != Name) {
4277 Diag(NewFD->getLocation(), diag::err_destructor_name);
4278 return NewFD->setInvalidDecl();
4279 }
4280 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00004281 } else if (CXXConversionDecl *Conversion
Douglas Gregor4ba31362009-12-01 17:24:26 +00004282 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00004283 ActOnConversionDeclarator(Conversion);
Douglas Gregor4ba31362009-12-01 17:24:26 +00004284 }
4285
4286 // Find any virtual functions that this function overrides.
Douglas Gregore6342c02009-12-01 17:35:23 +00004287 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
4288 if (!Method->isFunctionTemplateSpecialization() &&
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00004289 !Method->getDescribedFunctionTemplate()) {
4290 if (AddOverriddenMethods(Method->getParent(), Method)) {
4291 // If the function was marked as "static", we have a problem.
4292 if (NewFD->getStorageClass() == SC_Static) {
4293 Diag(NewFD->getLocation(), diag::err_static_overrides_virtual)
4294 << NewFD->getDeclName();
4295 for (CXXMethodDecl::method_iterator
4296 Overridden = Method->begin_overridden_methods(),
4297 OverriddenEnd = Method->end_overridden_methods();
4298 Overridden != OverriddenEnd;
4299 ++Overridden) {
4300 Diag((*Overridden)->getLocation(),
4301 diag::note_overridden_virtual_function);
4302 }
4303 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004304 }
Douglas Gregora6c1e3a2010-10-13 22:55:32 +00004305 }
Douglas Gregore6342c02009-12-01 17:35:23 +00004306 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00004307
4308 // Extra checking for C++ overloaded operators (C++ [over.oper]).
4309 if (NewFD->isOverloadedOperator() &&
4310 CheckOverloadedOperatorDeclaration(NewFD))
4311 return NewFD->setInvalidDecl();
Sean Hunta6c058d2010-01-13 09:01:02 +00004312
4313 // Extra checking for C++0x literal operators (C++0x [over.literal]).
4314 if (NewFD->getLiteralIdentifier() &&
4315 CheckLiteralOperatorDeclaration(NewFD))
4316 return NewFD->setInvalidDecl();
4317
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00004318 // In C++, check default arguments now that we have merged decls. Unless
4319 // the lexical context is the class, because in this case this is done
4320 // during delayed parsing anyway.
4321 if (!CurContext->isRecord())
4322 CheckCXXDefaultArguments(NewFD);
Douglas Gregorb68e3992010-12-21 19:47:46 +00004323
4324 // If this function declares a builtin function, check the type of this
4325 // declaration against the expected type for the builtin.
4326 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
4327 ASTContext::GetBuiltinTypeError Error;
4328 QualType T = Context.GetBuiltinType(BuiltinID, Error);
4329 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
4330 // The type of this function differs from the type of the builtin,
4331 // so forget about the builtin entirely.
4332 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
4333 }
4334 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00004335 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00004336}
4337
John McCall8c4859a2009-07-24 03:03:21 +00004338void Sema::CheckMain(FunctionDecl* FD) {
John McCall13591ed2009-07-25 04:36:53 +00004339 // C++ [basic.start.main]p3: A program that declares main to be inline
4340 // or static is ill-formed.
4341 // C99 6.7.4p4: In a hosted environment, the inline function specifier
4342 // shall not appear in a declaration of main.
4343 // static main is not an error under C99, but we should warn about it.
Douglas Gregor0130f3c2009-10-27 21:01:01 +00004344 bool isInline = FD->isInlineSpecified();
John McCalld931b082010-08-26 03:08:43 +00004345 bool isStatic = FD->getStorageClass() == SC_Static;
John McCall13591ed2009-07-25 04:36:53 +00004346 if (isInline || isStatic) {
4347 unsigned diagID = diag::warn_unusual_main_decl;
4348 if (isInline || getLangOptions().CPlusPlus)
4349 diagID = diag::err_unusual_main_decl;
4350
4351 int which = isStatic + (isInline << 1) - 1;
4352 Diag(FD->getLocation(), diagID) << which;
4353 }
4354
4355 QualType T = FD->getType();
4356 assert(T->isFunctionType() && "function decl is not of function type");
John McCall183700f2009-09-21 23:43:11 +00004357 const FunctionType* FT = T->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004358
John McCall13591ed2009-07-25 04:36:53 +00004359 if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
Gabor Greifa4a301d2010-09-08 00:31:13 +00004360 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
Abramo Bagnara723df242010-12-14 22:11:44 +00004361 TypeLoc TL = TSI->getTypeLoc().IgnoreParens();
Gabor Greifa4a301d2010-09-08 00:31:13 +00004362 const SemaDiagnosticBuilder& D = Diag(FD->getTypeSpecStartLoc(),
4363 diag::err_main_returns_nonint);
4364 if (FunctionTypeLoc* PTL = dyn_cast<FunctionTypeLoc>(&TL)) {
4365 D << FixItHint::CreateReplacement(PTL->getResultLoc().getSourceRange(),
4366 "int");
4367 }
John McCall13591ed2009-07-25 04:36:53 +00004368 FD->setInvalidDecl(true);
4369 }
4370
4371 // Treat protoless main() as nullary.
4372 if (isa<FunctionNoProtoType>(FT)) return;
4373
4374 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
4375 unsigned nparams = FTP->getNumArgs();
4376 assert(FD->getNumParams() == nparams);
4377
John McCall66755862009-12-24 09:58:38 +00004378 bool HasExtraParameters = (nparams > 3);
4379
4380 // Darwin passes an undocumented fourth argument of type char**. If
4381 // other platforms start sprouting these, the logic below will start
4382 // getting shifty.
4383 if (nparams == 4 &&
4384 Context.Target.getTriple().getOS() == llvm::Triple::Darwin)
4385 HasExtraParameters = false;
4386
4387 if (HasExtraParameters) {
John McCall13591ed2009-07-25 04:36:53 +00004388 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
4389 FD->setInvalidDecl(true);
4390 nparams = 3;
4391 }
4392
4393 // FIXME: a lot of the following diagnostics would be improved
4394 // if we had some location information about types.
4395
4396 QualType CharPP =
4397 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall66755862009-12-24 09:58:38 +00004398 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall13591ed2009-07-25 04:36:53 +00004399
4400 for (unsigned i = 0; i < nparams; ++i) {
4401 QualType AT = FTP->getArgType(i);
4402
4403 bool mismatch = true;
4404
4405 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
4406 mismatch = false;
4407 else if (Expected[i] == CharPP) {
4408 // As an extension, the following forms are okay:
4409 // char const **
4410 // char const * const *
4411 // char * const *
4412
John McCall0953e762009-09-24 19:53:00 +00004413 QualifierCollector qs;
John McCall13591ed2009-07-25 04:36:53 +00004414 const PointerType* PT;
Ted Kremenek6217b802009-07-29 21:53:49 +00004415 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
4416 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
John McCall13591ed2009-07-25 04:36:53 +00004417 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
4418 qs.removeConst();
4419 mismatch = !qs.empty();
4420 }
4421 }
4422
4423 if (mismatch) {
4424 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
4425 // TODO: suggest replacing given type with expected type
4426 FD->setInvalidDecl(true);
4427 }
4428 }
4429
4430 if (nparams == 1 && !FD->isInvalidDecl()) {
4431 Diag(FD->getLocation(), diag::warn_main_one_arg);
4432 }
Douglas Gregor0bab54c2010-10-21 16:57:46 +00004433
4434 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
4435 Diag(FD->getLocation(), diag::err_main_template_decl);
4436 FD->setInvalidDecl();
4437 }
John McCall8c4859a2009-07-24 03:03:21 +00004438}
4439
Eli Friedmanc594b322008-05-20 13:48:25 +00004440bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman3b8a36a2009-02-27 04:17:12 +00004441 // FIXME: Need strict checking. In C89, we need to check for
4442 // any assignment, increment, decrement, function-calls, or
4443 // commas outside of a sizeof. In C99, it's the same list,
4444 // except that the aforementioned are allowed in unevaluated
4445 // expressions. Everything else falls under the
4446 // "may accept other forms of constant expressions" exception.
4447 // (We never end up here for C++, so the constant expression
4448 // rules there don't matter.)
John McCall4204f072010-08-02 21:13:48 +00004449 if (Init->isConstantInitializer(Context, false))
Eli Friedman578a9722009-02-22 06:45:27 +00004450 return false;
Eli Friedman21298282009-02-26 04:47:58 +00004451 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
4452 << Init->getSourceRange();
Eli Friedmanc594b322008-05-20 13:48:25 +00004453 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00004454}
4455
John McCall9ae2f072010-08-23 23:25:46 +00004456void Sema::AddInitializerToDecl(Decl *dcl, Expr *init) {
4457 AddInitializerToDecl(dcl, init, /*DirectInit=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004458}
4459
4460/// AddInitializerToDecl - Adds the initializer Init to the
4461/// declaration dcl. If DirectInit is true, this is C++ direct
4462/// initialization rather than copy initialization.
John McCall9ae2f072010-08-23 23:25:46 +00004463void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
Chris Lattner9a11b9a2007-10-19 20:10:30 +00004464 // If there is no declaration, there was an error parsing it. Just ignore
4465 // the initializer.
Eli Friedman3b8a36a2009-02-27 04:17:12 +00004466 if (RealDecl == 0)
Chris Lattner9a11b9a2007-10-19 20:10:30 +00004467 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004468
Douglas Gregor021c3b32009-03-11 23:00:04 +00004469 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
4470 // With declarators parsed the way they are, the parser cannot
4471 // distinguish between a normal initializer and a pure-specifier.
4472 // Thus this grotesque test.
4473 IntegerLiteral *IL;
Douglas Gregor021c3b32009-03-11 23:00:04 +00004474 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor4ba31362009-12-01 17:24:26 +00004475 Context.getCanonicalType(IL->getType()) == Context.IntTy)
4476 CheckPureMethod(Method, Init->getSourceRange());
4477 else {
Douglas Gregor021c3b32009-03-11 23:00:04 +00004478 Diag(Method->getLocation(), diag::err_member_function_initialization)
4479 << Method->getDeclName() << Init->getSourceRange();
4480 Method->setInvalidDecl();
4481 }
4482 return;
4483 }
4484
Steve Naroff410e3e22007-09-12 20:13:48 +00004485 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4486 if (!VDecl) {
Douglas Gregor021c3b32009-03-11 23:00:04 +00004487 if (getLangOptions().CPlusPlus &&
4488 RealDecl->getLexicalDeclContext()->isRecord() &&
4489 isa<NamedDecl>(RealDecl))
John McCall4e635642010-09-10 23:21:22 +00004490 Diag(RealDecl->getLocation(), diag::err_member_initialization);
Douglas Gregor021c3b32009-03-11 23:00:04 +00004491 else
4492 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00004493 RealDecl->setInvalidDecl();
4494 return;
Eli Friedman3b8a36a2009-02-27 04:17:12 +00004495 }
4496
Douglas Gregor3a91abf2010-08-24 05:27:49 +00004497
4498
Eli Friedman49e2b8e2009-11-14 03:40:14 +00004499 // A definition must end up with a complete type, which means it must be
4500 // complete with the restriction that an array type might be completed by the
4501 // initializer; note that later code assumes this restriction.
4502 QualType BaseDeclType = VDecl->getType();
4503 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
4504 BaseDeclType = Array->getElementType();
4505 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
Eli Friedmana31feca2009-04-13 21:28:54 +00004506 diag::err_typecheck_decl_incomplete_type)) {
4507 RealDecl->setInvalidDecl();
4508 return;
4509 }
4510
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004511 // The variable can not have an abstract class type.
4512 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4513 diag::err_abstract_type_in_decl,
4514 AbstractVariableType))
4515 VDecl->setInvalidDecl();
4516
Sebastian Redl31310a22010-02-01 20:16:42 +00004517 const VarDecl *Def;
4518 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004519 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor275a3692009-03-10 23:43:53 +00004520 << VDecl->getDeclName();
4521 Diag(Def->getLocation(), diag::note_previous_definition);
4522 VDecl->setInvalidDecl();
4523 return;
4524 }
Douglas Gregor3a91abf2010-08-24 05:27:49 +00004525
Douglas Gregor3a91abf2010-08-24 05:27:49 +00004526 const VarDecl* PrevInit = 0;
Douglas Gregora31040f2010-12-16 01:31:22 +00004527 if (getLangOptions().CPlusPlus) {
4528 // C++ [class.static.data]p4
4529 // If a static data member is of const integral or const
4530 // enumeration type, its declaration in the class definition can
4531 // specify a constant-initializer which shall be an integral
4532 // constant expression (5.19). In that case, the member can appear
4533 // in integral constant expressions. The member shall still be
4534 // defined in a namespace scope if it is used in the program and the
4535 // namespace scope definition shall not contain an initializer.
4536 //
4537 // We already performed a redefinition check above, but for static
4538 // data members we also need to check whether there was an in-class
4539 // declaration with an initializer.
4540 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
4541 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
4542 Diag(PrevInit->getLocation(), diag::note_previous_definition);
4543 return;
4544 }
Douglas Gregor275a3692009-03-10 23:43:53 +00004545
Douglas Gregora31040f2010-12-16 01:31:22 +00004546 if (VDecl->hasLocalStorage())
4547 getCurFunction()->setHasBranchProtectedScope();
4548
4549 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
4550 VDecl->setInvalidDecl();
4551 return;
4552 }
4553 }
John McCalle46f62c2010-08-01 01:24:59 +00004554
Douglas Gregor99a2e602009-12-16 01:38:02 +00004555 // Capture the variable that is being initialized and the style of
4556 // initialization.
4557 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4558
4559 // FIXME: Poor source location information.
4560 InitializationKind Kind
4561 = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(),
4562 Init->getLocStart(),
4563 Init->getLocEnd())
4564 : InitializationKind::CreateCopy(VDecl->getLocation(),
4565 Init->getLocStart());
4566
Steve Naroffbb204692007-09-12 14:07:44 +00004567 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00004568 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00004569 QualType DclT = VDecl->getType(), SavT = DclT;
John McCallb6bbcc92010-10-15 04:57:14 +00004570 if (VDecl->isLocalVarDecl()) {
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00004571 if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00004572 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00004573 VDecl->setInvalidDecl();
4574 } else if (!VDecl->isInvalidDecl()) {
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004575 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00004576 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00004577 MultiExprArg(*this, &Init, 1),
Eli Friedmana91eb542009-12-22 02:10:53 +00004578 &DclT);
4579 if (Result.isInvalid()) {
Steve Naroff248a7532008-04-15 22:42:06 +00004580 VDecl->setInvalidDecl();
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004581 return;
4582 }
Mike Stump1eb44332009-09-09 15:08:12 +00004583
Eli Friedmana91eb542009-12-22 02:10:53 +00004584 Init = Result.takeAs<Expr>();
4585
Anders Carlssonc5eb7312008-08-22 05:00:02 +00004586 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmanda153232009-02-20 01:34:21 +00004587 // Don't check invalid declarations to avoid emitting useless diagnostics.
4588 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
John McCalld931b082010-08-26 03:08:43 +00004589 if (VDecl->getStorageClass() == SC_Static) // C99 6.7.8p4.
Anders Carlssonc5eb7312008-08-22 05:00:02 +00004590 CheckForConstantInitializer(Init, DclT);
4591 }
Steve Naroffbb204692007-09-12 14:07:44 +00004592 }
Mike Stump1eb44332009-09-09 15:08:12 +00004593 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor021c3b32009-03-11 23:00:04 +00004594 VDecl->getLexicalDeclContext()->isRecord()) {
4595 // This is an in-class initialization for a static data member, e.g.,
4596 //
4597 // struct S {
4598 // static const int value = 17;
4599 // };
4600
John McCall4e635642010-09-10 23:21:22 +00004601 // Try to perform the initialization regardless.
4602 if (!VDecl->isInvalidDecl()) {
4603 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
4604 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
4605 MultiExprArg(*this, &Init, 1),
4606 &DclT);
4607 if (Result.isInvalid()) {
4608 VDecl->setInvalidDecl();
4609 return;
4610 }
4611
4612 Init = Result.takeAs<Expr>();
4613 }
Douglas Gregor021c3b32009-03-11 23:00:04 +00004614
4615 // C++ [class.mem]p4:
4616 // A member-declarator can contain a constant-initializer only
4617 // if it declares a static member (9.4) of const integral or
4618 // const enumeration type, see 9.4.2.
4619 QualType T = VDecl->getType();
John McCall4e635642010-09-10 23:21:22 +00004620
4621 // Do nothing on dependent types.
4622 if (T->isDependentType()) {
4623
4624 // Require constness.
4625 } else if (!T.isConstQualified()) {
4626 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
4627 << Init->getSourceRange();
Douglas Gregor021c3b32009-03-11 23:00:04 +00004628 VDecl->setInvalidDecl();
John McCall4e635642010-09-10 23:21:22 +00004629
4630 // We allow integer constant expressions in all cases.
4631 } else if (T->isIntegralOrEnumerationType()) {
4632 if (!Init->isValueDependent()) {
Douglas Gregor021c3b32009-03-11 23:00:04 +00004633 // Check whether the expression is a constant expression.
4634 llvm::APSInt Value;
4635 SourceLocation Loc;
4636 if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) {
4637 Diag(Loc, diag::err_in_class_initializer_non_constant)
4638 << Init->getSourceRange();
4639 VDecl->setInvalidDecl();
John McCall4e635642010-09-10 23:21:22 +00004640 }
4641 }
4642
4643 // We allow floating-point constants as an extension in C++03, and
4644 // C++0x has far more complicated rules that we don't really
4645 // implement fully.
4646 } else {
4647 bool Allowed = false;
4648 if (getLangOptions().CPlusPlus0x) {
4649 Allowed = T->isLiteralType();
4650 } else if (T->isFloatingType()) { // also permits complex, which is ok
4651 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
4652 << T << Init->getSourceRange();
4653 Allowed = true;
4654 }
4655
4656 if (!Allowed) {
4657 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
4658 << T << Init->getSourceRange();
4659 VDecl->setInvalidDecl();
4660
4661 // TODO: there are probably expressions that pass here that shouldn't.
4662 } else if (!Init->isValueDependent() &&
4663 !Init->isConstantInitializer(Context, false)) {
4664 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
4665 << Init->getSourceRange();
4666 VDecl->setInvalidDecl();
Douglas Gregor021c3b32009-03-11 23:00:04 +00004667 }
4668 }
Steve Naroff248a7532008-04-15 22:42:06 +00004669 } else if (VDecl->isFileVarDecl()) {
Douglas Gregor66c42d42010-10-15 01:21:46 +00004670 if (VDecl->getStorageClassAsWritten() == SC_Extern &&
Douglas Gregor66dd9392010-04-22 14:36:26 +00004671 (!getLangOptions().CPlusPlus ||
4672 !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
Steve Naroff410e3e22007-09-12 20:13:48 +00004673 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedmana91eb542009-12-22 02:10:53 +00004674 if (!VDecl->isInvalidDecl()) {
4675 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
John McCall60d7b3a2010-08-24 06:29:42 +00004676 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCallca0408f2010-08-23 06:44:23 +00004677 MultiExprArg(*this, &Init, 1),
Eli Friedmana91eb542009-12-22 02:10:53 +00004678 &DclT);
4679 if (Result.isInvalid()) {
Steve Naroff248a7532008-04-15 22:42:06 +00004680 VDecl->setInvalidDecl();
Eli Friedmana91eb542009-12-22 02:10:53 +00004681 return;
4682 }
4683
4684 Init = Result.takeAs<Expr>();
4685 }
Mike Stump1eb44332009-09-09 15:08:12 +00004686
Anders Carlssonc5eb7312008-08-22 05:00:02 +00004687 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmanda153232009-02-20 01:34:21 +00004688 // Don't check invalid declarations to avoid emitting useless diagnostics.
4689 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
Anders Carlssonc5eb7312008-08-22 05:00:02 +00004690 // C99 6.7.8p4. All file scoped initializers need to be constant.
4691 CheckForConstantInitializer(Init, DclT);
4692 }
Steve Naroffbb204692007-09-12 14:07:44 +00004693 }
4694 // If the type changed, it means we had an incomplete type that was
Mike Stump1eb44332009-09-09 15:08:12 +00004695 // completed by the initializer. For example:
Steve Naroffbb204692007-09-12 14:07:44 +00004696 // int ary[] = { 1, 3, 5 };
4697 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00004698 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00004699 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00004700 Init->setType(DclT);
4701 }
Mike Stump1eb44332009-09-09 15:08:12 +00004702
Chris Lattner16c5dea2010-10-10 18:16:20 +00004703
4704 // If this variable is a local declaration with record type, make sure it
4705 // doesn't have a flexible member initialization. We only support this as a
4706 // global/static definition.
4707 if (VDecl->hasLocalStorage())
4708 if (const RecordType *RT = VDecl->getType()->getAs<RecordType>())
Douglas Gregorc6eddf52010-10-15 23:53:28 +00004709 if (RT->getDecl()->hasFlexibleArrayMember()) {
4710 // Check whether the initializer tries to initialize the flexible
4711 // array member itself to anything other than an empty initializer list.
4712 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
4713 unsigned Index = std::distance(RT->getDecl()->field_begin(),
4714 RT->getDecl()->field_end()) - 1;
4715 if (Index < ILE->getNumInits() &&
4716 !(isa<InitListExpr>(ILE->getInit(Index)) &&
4717 cast<InitListExpr>(ILE->getInit(Index))->getNumInits() == 0)) {
4718 Diag(VDecl->getLocation(), diag::err_nonstatic_flexible_variable);
4719 VDecl->setInvalidDecl();
4720 }
4721 }
Chris Lattner16c5dea2010-10-10 18:16:20 +00004722 }
4723
John McCallb4eb64d2010-10-08 02:01:28 +00004724 // Check any implicit conversions within the expression.
4725 CheckImplicitConversions(Init, VDecl->getLocation());
4726
John McCall4765fa02010-12-06 08:20:24 +00004727 Init = MaybeCreateExprWithCleanups(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00004728 // Attach the initializer to the decl.
Douglas Gregor838db382010-02-11 01:19:42 +00004729 VDecl->setInit(Init);
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00004730
John McCall2998d6b2011-01-19 11:48:09 +00004731 CheckCompleteVariableDeclaration(VDecl);
Steve Naroffbb204692007-09-12 14:07:44 +00004732}
4733
John McCall7727acf2010-03-31 02:13:20 +00004734/// ActOnInitializerError - Given that there was an error parsing an
4735/// initializer for the given declaration, try to return to some form
4736/// of sanity.
John McCalld226f652010-08-21 09:40:31 +00004737void Sema::ActOnInitializerError(Decl *D) {
John McCall7727acf2010-03-31 02:13:20 +00004738 // Our main concern here is re-establishing invariants like "a
4739 // variable's type is either dependent or complete".
John McCall7727acf2010-03-31 02:13:20 +00004740 if (!D || D->isInvalidDecl()) return;
4741
4742 VarDecl *VD = dyn_cast<VarDecl>(D);
4743 if (!VD) return;
4744
4745 QualType Ty = VD->getType();
4746 if (Ty->isDependentType()) return;
4747
4748 // Require a complete type.
4749 if (RequireCompleteType(VD->getLocation(),
4750 Context.getBaseElementType(Ty),
4751 diag::err_typecheck_decl_incomplete_type)) {
4752 VD->setInvalidDecl();
4753 return;
4754 }
4755
4756 // Require an abstract type.
4757 if (RequireNonAbstractType(VD->getLocation(), Ty,
4758 diag::err_abstract_type_in_decl,
4759 AbstractVariableType)) {
4760 VD->setInvalidDecl();
4761 return;
4762 }
4763
4764 // Don't bother complaining about constructors or destructors,
4765 // though.
4766}
4767
John McCalld226f652010-08-21 09:40:31 +00004768void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Anders Carlsson6a75cd92009-07-11 00:34:39 +00004769 bool TypeContainsUndeducedAuto) {
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00004770 // If there is no declaration, there was an error parsing it. Just ignore it.
4771 if (RealDecl == 0)
4772 return;
4773
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004774 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
4775 QualType Type = Var->getType();
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00004776
Anders Carlsson6a75cd92009-07-11 00:34:39 +00004777 // C++0x [dcl.spec.auto]p3
4778 if (TypeContainsUndeducedAuto) {
4779 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
4780 << Var->getDeclName() << Type;
4781 Var->setInvalidDecl();
4782 return;
4783 }
Mike Stump1eb44332009-09-09 15:08:12 +00004784
Douglas Gregor60c93c92010-02-09 07:26:29 +00004785 switch (Var->isThisDeclarationADefinition()) {
4786 case VarDecl::Definition:
4787 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
4788 break;
4789
4790 // We have an out-of-line definition of a static data member
4791 // that has an in-class initializer, so we type-check this like
4792 // a declaration.
4793 //
4794 // Fall through
4795
4796 case VarDecl::DeclarationOnly:
4797 // It's only a declaration.
4798
4799 // Block scope. C99 6.7p7: If an identifier for an object is
4800 // declared with no linkage (C99 6.2.2p6), the type for the
4801 // object shall be complete.
John McCallb6bbcc92010-10-15 04:57:14 +00004802 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Douglas Gregor60c93c92010-02-09 07:26:29 +00004803 !Var->getLinkage() && !Var->isInvalidDecl() &&
4804 RequireCompleteType(Var->getLocation(), Type,
4805 diag::err_typecheck_decl_incomplete_type))
4806 Var->setInvalidDecl();
4807
4808 // Make sure that the type is not abstract.
4809 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
4810 RequireNonAbstractType(Var->getLocation(), Type,
4811 diag::err_abstract_type_in_decl,
4812 AbstractVariableType))
4813 Var->setInvalidDecl();
4814 return;
4815
4816 case VarDecl::TentativeDefinition:
4817 // File scope. C99 6.9.2p2: A declaration of an identifier for an
4818 // object that has file scope without an initializer, and without a
4819 // storage-class specifier or with the storage-class specifier "static",
4820 // constitutes a tentative definition. Note: A tentative definition with
4821 // external linkage is valid (C99 6.2.2p5).
4822 if (!Var->isInvalidDecl()) {
4823 if (const IncompleteArrayType *ArrayT
4824 = Context.getAsIncompleteArrayType(Type)) {
4825 if (RequireCompleteType(Var->getLocation(),
4826 ArrayT->getElementType(),
4827 diag::err_illegal_decl_array_incomplete_type))
4828 Var->setInvalidDecl();
John McCalld931b082010-08-26 03:08:43 +00004829 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregor60c93c92010-02-09 07:26:29 +00004830 // C99 6.9.2p3: If the declaration of an identifier for an object is
4831 // a tentative definition and has internal linkage (C99 6.2.2p3), the
4832 // declared type shall not be an incomplete type.
4833 // NOTE: code such as the following
4834 // static struct s;
4835 // struct s { int a; };
4836 // is accepted by gcc. Hence here we issue a warning instead of
4837 // an error and we do not invalidate the static declaration.
4838 // NOTE: to avoid multiple warnings, only check the first declaration.
4839 if (Var->getPreviousDeclaration() == 0)
4840 RequireCompleteType(Var->getLocation(), Type,
4841 diag::ext_typecheck_decl_incomplete_type);
4842 }
4843 }
4844
4845 // Record the tentative definition; we're done.
4846 if (!Var->isInvalidDecl())
4847 TentativeDefinitions.push_back(Var);
4848 return;
4849 }
4850
4851 // Provide a specific diagnostic for uninitialized variable
4852 // definitions with incomplete array type.
4853 if (Type->isIncompleteArrayType()) {
Sebastian Redl6e824752009-11-05 19:47:47 +00004854 Diag(Var->getLocation(),
4855 diag::err_typecheck_incomplete_array_needs_initializer);
4856 Var->setInvalidDecl();
4857 return;
4858 }
4859
John McCallb567a8b2010-08-01 01:25:24 +00004860 // Provide a specific diagnostic for uninitialized variable
4861 // definitions with reference type.
4862 if (Type->isReferenceType()) {
4863 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
4864 << Var->getDeclName()
4865 << SourceRange(Var->getLocation(), Var->getLocation());
4866 Var->setInvalidDecl();
4867 return;
4868 }
Douglas Gregor60c93c92010-02-09 07:26:29 +00004869
4870 // Do not attempt to type-check the default initializer for a
4871 // variable with dependent type.
4872 if (Type->isDependentType())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004873 return;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004874
Douglas Gregor60c93c92010-02-09 07:26:29 +00004875 if (Var->isInvalidDecl())
4876 return;
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004877
Douglas Gregor60c93c92010-02-09 07:26:29 +00004878 if (RequireCompleteType(Var->getLocation(),
4879 Context.getBaseElementType(Type),
4880 diag::err_typecheck_decl_incomplete_type)) {
4881 Var->setInvalidDecl();
4882 return;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004883 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004884
Douglas Gregor60c93c92010-02-09 07:26:29 +00004885 // The variable can not have an abstract class type.
4886 if (RequireNonAbstractType(Var->getLocation(), Type,
4887 diag::err_abstract_type_in_decl,
4888 AbstractVariableType)) {
4889 Var->setInvalidDecl();
4890 return;
4891 }
4892
Douglas Gregor516a6bc2010-03-08 02:45:10 +00004893 const RecordType *Record
4894 = Context.getBaseElementType(Type)->getAs<RecordType>();
4895 if (Record && getLangOptions().CPlusPlus && !getLangOptions().CPlusPlus0x &&
4896 cast<CXXRecordDecl>(Record->getDecl())->isPOD()) {
4897 // C++03 [dcl.init]p9:
4898 // If no initializer is specified for an object, and the
4899 // object is of (possibly cv-qualified) non-POD class type (or
4900 // array thereof), the object shall be default-initialized; if
4901 // the object is of const-qualified type, the underlying class
4902 // type shall have a user-declared default
4903 // constructor. Otherwise, if no initializer is specified for
4904 // a non- static object, the object and its subobjects, if
4905 // any, have an indeterminate initial value); if the object
4906 // or any of its subobjects are of const-qualified type, the
4907 // program is ill-formed.
4908 // FIXME: DPG thinks it is very fishy that C++0x disables this.
4909 } else {
John McCalle46f62c2010-08-01 01:24:59 +00004910 // Check for jumps past the implicit initializer. C++0x
4911 // clarifies that this applies to a "variable with automatic
4912 // storage duration", not a "local variable".
4913 if (getLangOptions().CPlusPlus && Var->hasLocalStorage())
John McCall781472f2010-08-25 08:40:02 +00004914 getCurFunction()->setHasBranchProtectedScope();
John McCalle46f62c2010-08-01 01:24:59 +00004915
Douglas Gregor516a6bc2010-03-08 02:45:10 +00004916 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
4917 InitializationKind Kind
4918 = InitializationKind::CreateDefault(Var->getLocation());
Douglas Gregor60c93c92010-02-09 07:26:29 +00004919
Douglas Gregor516a6bc2010-03-08 02:45:10 +00004920 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00004921 ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
4922 MultiExprArg(*this, 0, 0));
Douglas Gregor516a6bc2010-03-08 02:45:10 +00004923 if (Init.isInvalid())
4924 Var->setInvalidDecl();
John McCall2998d6b2011-01-19 11:48:09 +00004925 else if (Init.get())
Douglas Gregor53c374f2010-12-07 00:41:46 +00004926 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Douglas Gregor60c93c92010-02-09 07:26:29 +00004927 }
Douglas Gregor516a6bc2010-03-08 02:45:10 +00004928
John McCall2998d6b2011-01-19 11:48:09 +00004929 CheckCompleteVariableDeclaration(Var);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004930 }
4931}
4932
John McCall2998d6b2011-01-19 11:48:09 +00004933void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
4934 if (var->isInvalidDecl()) return;
4935
4936 // All the following checks are C++ only.
4937 if (!getLangOptions().CPlusPlus) return;
4938
4939 QualType baseType = Context.getBaseElementType(var->getType());
4940 if (baseType->isDependentType()) return;
4941
4942 // __block variables might require us to capture a copy-initializer.
4943 if (var->hasAttr<BlocksAttr>()) {
4944 // It's currently invalid to ever have a __block variable with an
4945 // array type; should we diagnose that here?
4946
4947 // Regardless, we don't want to ignore array nesting when
4948 // constructing this copy.
4949 QualType type = var->getType();
4950
4951 if (type->isStructureOrClassType()) {
4952 SourceLocation poi = var->getLocation();
4953 Expr *varRef = new (Context) DeclRefExpr(var, type, VK_LValue, poi);
4954 ExprResult result =
4955 PerformCopyInitialization(
4956 InitializedEntity::InitializeBlock(poi, type, false),
4957 poi, Owned(varRef));
4958 if (!result.isInvalid()) {
4959 result = MaybeCreateExprWithCleanups(result);
4960 Expr *init = result.takeAs<Expr>();
4961 Context.setBlockVarCopyInits(var, init);
4962 }
4963 }
4964 }
4965
4966 // Check for global constructors.
4967 if (!var->getDeclContext()->isDependentContext() &&
4968 var->hasGlobalStorage() &&
4969 !var->isStaticLocal() &&
4970 var->getInit() &&
4971 !var->getInit()->isConstantInitializer(Context,
4972 baseType->isReferenceType()))
4973 Diag(var->getLocation(), diag::warn_global_constructor)
4974 << var->getInit()->getSourceRange();
4975
4976 // Require the destructor.
4977 if (const RecordType *recordType = baseType->getAs<RecordType>())
4978 FinalizeVarWithDestructor(var, recordType);
4979}
4980
John McCallb3d87482010-08-24 05:47:05 +00004981Sema::DeclGroupPtrTy
4982Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
4983 Decl **Group, unsigned NumDecls) {
Chris Lattner682bf922009-03-29 16:50:03 +00004984 llvm::SmallVector<Decl*, 8> Decls;
Eli Friedmanc1dc6532009-05-29 01:49:24 +00004985
4986 if (DS.isTypeSpecOwned())
John McCallb3d87482010-08-24 05:47:05 +00004987 Decls.push_back(DS.getRepAsDecl());
Eli Friedmanc1dc6532009-05-29 01:49:24 +00004988
Chris Lattner682bf922009-03-29 16:50:03 +00004989 for (unsigned i = 0; i != NumDecls; ++i)
John McCalld226f652010-08-21 09:40:31 +00004990 if (Decl *D = Group[i])
Chris Lattner682bf922009-03-29 16:50:03 +00004991 Decls.push_back(D);
Mike Stump1eb44332009-09-09 15:08:12 +00004992
Chris Lattner682bf922009-03-29 16:50:03 +00004993 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context,
Jay Foadbeaaccd2009-05-21 09:52:38 +00004994 Decls.data(), Decls.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00004995}
Steve Naroffe1223f72007-08-28 03:03:08 +00004996
Chris Lattner682bf922009-03-29 16:50:03 +00004997
Chris Lattner04421082008-04-08 04:40:51 +00004998/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
4999/// to introduce parameters into function prototype scope.
John McCalld226f652010-08-21 09:40:31 +00005000Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00005001 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00005002
Chris Lattner04421082008-04-08 04:40:51 +00005003 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
John McCalld931b082010-08-26 03:08:43 +00005004 VarDecl::StorageClass StorageClass = SC_None;
5005 VarDecl::StorageClass StorageClassAsWritten = SC_None;
Daniel Dunbar33ad0122008-09-03 21:54:21 +00005006 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCalld931b082010-08-26 03:08:43 +00005007 StorageClass = SC_Register;
5008 StorageClassAsWritten = SC_Register;
Daniel Dunbar33ad0122008-09-03 21:54:21 +00005009 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00005010 Diag(DS.getStorageClassSpecLoc(),
5011 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00005012 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00005013 }
Eli Friedman63054b32009-04-19 20:27:55 +00005014
5015 if (D.getDeclSpec().isThreadSpecified())
5016 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
5017
Eli Friedman85a53192009-04-07 19:37:57 +00005018 DiagnoseFunctionSpecifiers(D);
5019
Douglas Gregor402abb52009-05-28 23:31:59 +00005020 TagDecl *OwnedDecl = 0;
John McCallbf1a0282010-06-04 23:28:52 +00005021 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedDecl);
5022 QualType parmDeclType = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005023
Douglas Gregora8bc8c92010-12-23 22:44:42 +00005024 if (getLangOptions().CPlusPlus) {
5025 // Check that there are no default arguments inside the type of this
5026 // parameter.
5027 CheckExtraCXXDefaultArguments(D);
5028
5029 if (OwnedDecl && OwnedDecl->isDefinition()) {
5030 // C++ [dcl.fct]p6:
5031 // Types shall not be defined in return or parameter types.
5032 Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
5033 << Context.getTypeDeclType(OwnedDecl);
5034 }
5035
5036 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
5037 if (D.getCXXScopeSpec().isSet()) {
5038 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
5039 << D.getCXXScopeSpec().getRange();
5040 D.getCXXScopeSpec().clear();
5041 }
Douglas Gregor402abb52009-05-28 23:31:59 +00005042 }
5043
Sean Hunt7533a5b2010-11-03 01:07:06 +00005044 // Ensure we have a valid name
5045 IdentifierInfo *II = 0;
5046 if (D.hasName()) {
5047 II = D.getIdentifier();
5048 if (!II) {
5049 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
5050 << GetNameForDeclarator(D).getName().getAsString();
5051 D.setInvalidType(true);
5052 }
5053 }
5054
Chris Lattnerd84aac12010-02-22 00:40:25 +00005055 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnercf79b012009-01-21 02:38:50 +00005056 if (II) {
John McCall10f28732010-03-18 06:42:38 +00005057 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
5058 ForRedeclaration);
5059 LookupName(R, S);
5060 if (R.isSingleResult()) {
5061 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnercf79b012009-01-21 02:38:50 +00005062 if (PrevDecl->isTemplateParameter()) {
5063 // Maybe we will complain about the shadowed template parameter.
5064 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5065 // Just pretend that we didn't see the previous declaration.
5066 PrevDecl = 0;
John McCalld226f652010-08-21 09:40:31 +00005067 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnercf79b012009-01-21 02:38:50 +00005068 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerd84aac12010-02-22 00:40:25 +00005069 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattner04421082008-04-08 04:40:51 +00005070
Chris Lattnercf79b012009-01-21 02:38:50 +00005071 // Recover by removing the name
5072 II = 0;
5073 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00005074 D.setInvalidType(true);
Chris Lattnercf79b012009-01-21 02:38:50 +00005075 }
Chris Lattner04421082008-04-08 04:40:51 +00005076 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005077 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00005078
John McCall7a9813c2010-01-22 00:28:27 +00005079 // Temporarily put parameter variables in the translation unit, not
5080 // the enclosing context. This prevents them from accidentally
5081 // looking like class members in C++.
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00005082 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
5083 TInfo, parmDeclType, II,
Douglas Gregor16573fa2010-04-19 22:54:31 +00005084 D.getIdentifierLoc(),
5085 StorageClass, StorageClassAsWritten);
Mike Stump1eb44332009-09-09 15:08:12 +00005086
Chris Lattnereaaebc72009-04-25 08:06:05 +00005087 if (D.isInvalidType())
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00005088 New->setInvalidDecl();
5089
Douglas Gregor44b43212008-12-11 16:49:14 +00005090 // Add the parameter declaration into this scope.
John McCalld226f652010-08-21 09:40:31 +00005091 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00005092 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00005093 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00005094
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005095 ProcessDeclAttributes(S, New, D);
Mike Stumpea000bf2009-04-30 00:19:40 +00005096
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005097 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpea000bf2009-04-30 00:19:40 +00005098 Diag(New->getLocation(), diag::err_block_on_nonlocal);
5099 }
John McCalld226f652010-08-21 09:40:31 +00005100 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +00005101}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00005102
John McCall82dc0092010-06-04 11:21:44 +00005103/// \brief Synthesizes a variable for a parameter arising from a
5104/// typedef.
5105ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
5106 SourceLocation Loc,
5107 QualType T) {
5108 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, 0,
5109 T, Context.getTrivialTypeSourceInfo(T, Loc),
John McCalld931b082010-08-26 03:08:43 +00005110 SC_None, SC_None, 0);
John McCall82dc0092010-06-04 11:21:44 +00005111 Param->setImplicit();
5112 return Param;
5113}
5114
John McCallfbce0e12010-08-24 09:05:15 +00005115void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
5116 ParmVarDecl * const *ParamEnd) {
John McCallfbce0e12010-08-24 09:05:15 +00005117 // Don't diagnose unused-parameter errors in template instantiations; we
5118 // will already have done so in the template itself.
5119 if (!ActiveTemplateInstantiations.empty())
5120 return;
5121
5122 for (; Param != ParamEnd; ++Param) {
5123 if (!(*Param)->isUsed() && (*Param)->getDeclName() &&
5124 !(*Param)->hasAttr<UnusedAttr>()) {
5125 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
5126 << (*Param)->getDeclName();
5127 }
5128 }
5129}
5130
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00005131void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
5132 ParmVarDecl * const *ParamEnd,
5133 QualType ReturnTy,
5134 NamedDecl *D) {
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00005135 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00005136 return;
5137
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00005138 // Warn if the return value is pass-by-value and larger than the specified
5139 // threshold.
Argyrios Kyrtzidisf4bed3f2010-11-18 18:51:03 +00005140 if (ReturnTy->isPODType()) {
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00005141 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00005142 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00005143 Diag(D->getLocation(), diag::warn_return_value_size)
5144 << D->getDeclName() << Size;
5145 }
5146
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00005147 // Warn if any parameter is pass-by-value and larger than the specified
5148 // threshold.
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00005149 for (; Param != ParamEnd; ++Param) {
5150 QualType T = (*Param)->getType();
5151 if (!T->isPODType())
5152 continue;
5153 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidis1380a142010-11-18 00:20:36 +00005154 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00005155 Diag((*Param)->getLocation(), diag::warn_parameter_size)
5156 << (*Param)->getDeclName() << Size;
5157 }
5158}
5159
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00005160ParmVarDecl *Sema::CheckParameter(DeclContext *DC,
5161 TypeSourceInfo *TSInfo, QualType T,
5162 IdentifierInfo *Name,
5163 SourceLocation NameLoc,
Douglas Gregor16573fa2010-04-19 22:54:31 +00005164 VarDecl::StorageClass StorageClass,
5165 VarDecl::StorageClass StorageClassAsWritten) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00005166 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, NameLoc, Name,
5167 adjustParameterType(T), TSInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00005168 StorageClass, StorageClassAsWritten,
5169 0);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00005170
5171 // Parameters can not be abstract class types.
5172 // For record types, this is done by the AbstractClassUsageDiagnoser once
5173 // the class has been completely parsed.
5174 if (!CurContext->isRecord() &&
5175 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
5176 AbstractParamType))
5177 New->setInvalidDecl();
5178
5179 // Parameter declarators cannot be interface types. All ObjC objects are
5180 // passed by reference.
John McCallc12c5bb2010-05-15 11:32:37 +00005181 if (T->isObjCObjectType()) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00005182 Diag(NameLoc,
5183 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
5184 New->setInvalidDecl();
5185 }
5186
5187 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
5188 // duration shall not be qualified by an address-space qualifier."
5189 // Since all parameters have automatic store duration, they can not have
5190 // an address space.
5191 if (T.getAddressSpace() != 0) {
5192 Diag(NameLoc, diag::err_arg_with_address_space);
5193 New->setInvalidDecl();
5194 }
5195
5196 return New;
5197}
5198
Douglas Gregora3a83512009-04-01 23:51:29 +00005199void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
5200 SourceLocation LocAfterDecls) {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005201 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner04421082008-04-08 04:40:51 +00005202
Reid Spencer5f016e22007-07-11 17:01:13 +00005203 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
5204 // for a K&R function.
5205 if (!FTI.hasPrototype) {
Douglas Gregor26103482009-04-02 03:14:12 +00005206 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
5207 --i;
Chris Lattner04421082008-04-08 04:40:51 +00005208 if (FTI.ArgInfo[i].Param == 0) {
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00005209 llvm::SmallString<256> Code;
5210 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00005211 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00005212 << ";\n";
Chris Lattner3c73c412008-11-19 08:23:25 +00005213 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregora3a83512009-04-01 23:51:29 +00005214 << FTI.ArgInfo[i].Ident
Douglas Gregor849b2432010-03-31 17:46:05 +00005215 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregora3a83512009-04-01 23:51:29 +00005216
Reid Spencer5f016e22007-07-11 17:01:13 +00005217 // Implicitly declare the argument as type 'int' for lack of a better
5218 // type.
Chris Lattner04421082008-04-08 04:40:51 +00005219 DeclSpec DS;
5220 const char* PrevSpec; // unused
John McCallfec54012009-08-03 20:12:06 +00005221 unsigned DiagID; // unused
Mike Stump1eb44332009-09-09 15:08:12 +00005222 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCallfec54012009-08-03 20:12:06 +00005223 PrevSpec, DiagID);
Chris Lattner04421082008-04-08 04:40:51 +00005224 Declarator ParamD(DS, Declarator::KNRTypeListContext);
5225 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregorbe109b32009-01-23 16:23:13 +00005226 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00005227 }
5228 }
Mike Stump1eb44332009-09-09 15:08:12 +00005229 }
Douglas Gregorbe109b32009-01-23 16:23:13 +00005230}
5231
John McCalld226f652010-08-21 09:40:31 +00005232Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
5233 Declarator &D) {
Douglas Gregorbe109b32009-01-23 16:23:13 +00005234 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005235 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregor584049d2008-12-15 23:53:10 +00005236 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00005237
John McCalld226f652010-08-21 09:40:31 +00005238 Decl *DP = HandleDeclarator(ParentScope, D,
5239 MultiTemplateParamsArg(*this),
5240 /*IsFunctionDefinition=*/true);
Chris Lattner682bf922009-03-29 16:50:03 +00005241 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005242}
5243
Anders Carlsson9f89dd72009-12-09 03:30:09 +00005244static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
5245 // Don't warn about invalid declarations.
5246 if (FD->isInvalidDecl())
5247 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00005248
Anders Carlsson9f89dd72009-12-09 03:30:09 +00005249 // Or declarations that aren't global.
5250 if (!FD->isGlobal())
5251 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00005252
Anders Carlsson9f89dd72009-12-09 03:30:09 +00005253 // Don't warn about C++ member functions.
5254 if (isa<CXXMethodDecl>(FD))
5255 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00005256
Anders Carlsson9f89dd72009-12-09 03:30:09 +00005257 // Don't warn about 'main'.
5258 if (FD->isMain())
5259 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00005260
Anders Carlsson9f89dd72009-12-09 03:30:09 +00005261 // Don't warn about inline functions.
5262 if (FD->isInlineSpecified())
5263 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00005264
5265 // Don't warn about function templates.
5266 if (FD->getDescribedFunctionTemplate())
5267 return false;
5268
5269 // Don't warn about function template specializations.
5270 if (FD->isFunctionTemplateSpecialization())
5271 return false;
5272
Anders Carlsson9f89dd72009-12-09 03:30:09 +00005273 bool MissingPrototype = true;
5274 for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
5275 Prev; Prev = Prev->getPreviousDeclaration()) {
5276 // Ignore any declarations that occur in function or method
5277 // scope, because they aren't visible from the header.
5278 if (Prev->getDeclContext()->isFunctionOrMethod())
5279 continue;
5280
5281 MissingPrototype = !Prev->getType()->isFunctionProtoType();
5282 break;
5283 }
5284
5285 return MissingPrototype;
5286}
5287
John McCalld226f652010-08-21 09:40:31 +00005288Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00005289 // Clear the last template instantiation error context.
5290 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
5291
Douglas Gregor52591bf2009-06-24 00:54:41 +00005292 if (!D)
5293 return D;
Douglas Gregord83d0402009-08-22 00:34:47 +00005294 FunctionDecl *FD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005295
John McCalld226f652010-08-21 09:40:31 +00005296 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregord83d0402009-08-22 00:34:47 +00005297 FD = FunTmpl->getTemplatedDecl();
5298 else
John McCalld226f652010-08-21 09:40:31 +00005299 FD = cast<FunctionDecl>(D);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00005300
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00005301 // Enter a new function scope
5302 PushFunctionScope();
Mike Stump1eb44332009-09-09 15:08:12 +00005303
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00005304 // See if this is a redefinition.
Charles Davisf3f8d2a2010-02-18 02:00:42 +00005305 // But don't complain if we're in GNU89 mode and the previous definition
5306 // was an extern inline function.
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00005307 const FunctionDecl *Definition;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00005308 if (FD->hasBody(Definition) &&
Charles Davisf3f8d2a2010-02-18 02:00:42 +00005309 !canRedefineFunction(Definition, getLangOptions())) {
Douglas Gregorfbc5b492010-09-07 15:51:01 +00005310 if (getLangOptions().GNUMode && Definition->isInlineSpecified() &&
5311 Definition->getStorageClass() == SC_Extern)
5312 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
5313 << FD->getDeclName() << getLangOptions().CPlusPlus;
5314 else
5315 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00005316 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00005317 }
5318
Douglas Gregorcda9c672009-02-16 17:45:42 +00005319 // Builtin functions cannot be defined.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00005320 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor655753a2009-02-17 16:03:01 +00005321 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00005322 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor655753a2009-02-17 16:03:01 +00005323 FD->setInvalidDecl();
5324 }
Douglas Gregorcda9c672009-02-16 17:45:42 +00005325 }
5326
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00005327 // The return type of a function definition must be complete
Douglas Gregore7450f52009-03-24 19:52:54 +00005328 // (C99 6.9.1p3, C++ [dcl.fct]p6).
5329 QualType ResultType = FD->getResultType();
5330 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner65e6a092009-04-29 05:12:23 +00005331 !FD->isInvalidDecl() &&
Douglas Gregore7450f52009-03-24 19:52:54 +00005332 RequireCompleteType(FD->getLocation(), ResultType,
5333 diag::err_func_def_incomplete_result))
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00005334 FD->setInvalidDecl();
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00005335
Douglas Gregor8499f3f2009-03-31 16:35:03 +00005336 // GNU warning -Wmissing-prototypes:
5337 // Warn if a global function is defined without a previous
5338 // prototype declaration. This warning is issued even if the
5339 // definition itself provides a prototype. The aim is to detect
5340 // global functions that fail to be declared in header files.
Anders Carlsson9f89dd72009-12-09 03:30:09 +00005341 if (ShouldWarnAboutMissingPrototype(FD))
5342 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Douglas Gregor8499f3f2009-03-31 16:35:03 +00005343
Douglas Gregore2c31ff2009-05-15 17:59:04 +00005344 if (FnBodyScope)
5345 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00005346
Chris Lattner04421082008-04-08 04:40:51 +00005347 // Check the validity of our function parameters
Douglas Gregor82aa7132010-11-01 18:37:59 +00005348 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
5349 /*CheckParameterNames=*/true);
Chris Lattner04421082008-04-08 04:40:51 +00005350
5351 // Introduce our parameters into the function scope
5352 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
5353 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00005354 Param->setOwningFunction(FD);
5355
Chris Lattner04421082008-04-08 04:40:51 +00005356 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00005357 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005358 CheckShadow(FnBodyScope, Param);
John McCall053f4bd2010-03-22 09:20:08 +00005359
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00005360 PushOnScopeChains(Param, FnBodyScope);
John McCall053f4bd2010-03-22 09:20:08 +00005361 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005362 }
Chris Lattner04421082008-04-08 04:40:51 +00005363
Anton Korobeynikov2f402702008-12-26 00:52:02 +00005364 // Checking attributes of current function definition
5365 // dllimport attribute.
Sean Huntcf807c42010-08-18 23:23:40 +00005366 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
5367 if (DA && (!FD->getAttr<DLLExportAttr>())) {
5368 // dllimport attribute cannot be directly applied to definition.
5369 if (!DA->isInherited()) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00005370 Diag(FD->getLocation(),
5371 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
5372 << "dllimport";
5373 FD->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +00005374 return FD;
Ted Kremenek12911a82010-02-21 05:12:53 +00005375 }
5376
5377 // Visual C++ appears to not think this is an issue, so only issue
5378 // a warning when Microsoft extensions are disabled.
5379 if (!LangOpts.Microsoft) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00005380 // If a symbol previously declared dllimport is later defined, the
5381 // attribute is ignored in subsequent references, and a warning is
5382 // emitted.
5383 Diag(FD->getLocation(),
5384 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Daniel Dunbar4087f272010-08-17 22:39:59 +00005385 << FD->getName() << "dllimport";
Anton Korobeynikov2f402702008-12-26 00:52:02 +00005386 }
5387 }
John McCalld226f652010-08-21 09:40:31 +00005388 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00005389}
5390
Douglas Gregor5077c382010-05-15 06:01:05 +00005391/// \brief Given the set of return statements within a function body,
5392/// compute the variables that are subject to the named return value
5393/// optimization.
5394///
5395/// Each of the variables that is subject to the named return value
5396/// optimization will be marked as NRVO variables in the AST, and any
5397/// return statement that has a marked NRVO variable as its NRVO candidate can
5398/// use the named return value optimization.
5399///
5400/// This function applies a very simplistic algorithm for NRVO: if every return
5401/// statement in the function has the same NRVO candidate, that candidate is
5402/// the NRVO variable.
5403///
5404/// FIXME: Employ a smarter algorithm that accounts for multiple return
5405/// statements and the lifetimes of the NRVO candidates. We should be able to
5406/// find a maximal set of NRVO variables.
John McCall781472f2010-08-25 08:40:02 +00005407static void ComputeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
5408 ReturnStmt **Returns = Scope->Returns.data();
5409
Douglas Gregor5077c382010-05-15 06:01:05 +00005410 const VarDecl *NRVOCandidate = 0;
John McCall781472f2010-08-25 08:40:02 +00005411 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor5077c382010-05-15 06:01:05 +00005412 if (!Returns[I]->getNRVOCandidate())
5413 return;
5414
5415 if (!NRVOCandidate)
5416 NRVOCandidate = Returns[I]->getNRVOCandidate();
5417 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
5418 return;
5419 }
5420
5421 if (NRVOCandidate)
5422 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
5423}
5424
John McCallf312b1e2010-08-26 23:41:50 +00005425Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Douglas Gregore2c31ff2009-05-15 17:59:04 +00005426 return ActOnFinishFunctionBody(D, move(BodyArg), false);
5427}
5428
John McCall9ae2f072010-08-23 23:25:46 +00005429Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
5430 bool IsInstantiation) {
Douglas Gregord83d0402009-08-22 00:34:47 +00005431 FunctionDecl *FD = 0;
5432 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
5433 if (FunTmpl)
5434 FD = FunTmpl->getTemplatedDecl();
5435 else
5436 FD = dyn_cast_or_null<FunctionDecl>(dcl);
5437
Ted Kremenekd064fdc2010-03-23 00:13:23 +00005438 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00005439
Douglas Gregord83d0402009-08-22 00:34:47 +00005440 if (FD) {
Chris Lattnera5251fc2009-04-18 09:36:27 +00005441 FD->setBody(Body);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00005442 if (FD->isMain()) {
Mike Stump5f28a1e2009-07-24 02:49:01 +00005443 // C and C++ allow for main to automagically return 0.
John McCall0cfeb632009-07-28 01:00:58 +00005444 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
5445 FD->setHasImplicitReturnZero(true);
Ted Kremenekd064fdc2010-03-23 00:13:23 +00005446 WP.disableCheckFallThrough();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00005447 }
Mike Stump1eb44332009-09-09 15:08:12 +00005448
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005449 if (!FD->isInvalidDecl()) {
Douglas Gregore0762c92009-06-19 23:52:42 +00005450 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00005451 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
5452 FD->getResultType(), FD);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005453
5454 // If this is a constructor, we need a vtable.
5455 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
5456 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor5077c382010-05-15 06:01:05 +00005457
John McCall781472f2010-08-25 08:40:02 +00005458 ComputeNRVO(Body, getCurFunction());
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005459 }
5460
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00005461 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00005462 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattnerffed1632009-02-16 19:27:54 +00005463 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattnera5251fc2009-04-18 09:36:27 +00005464 MD->setBody(Body);
Argyrios Kyrtzidis0fe53972011-01-03 22:33:06 +00005465 if (Body)
5466 MD->setEndLoc(Body->getLocEnd());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00005467 if (!MD->isInvalidDecl()) {
Douglas Gregore0762c92009-06-19 23:52:42 +00005468 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidis3532fdd2010-11-17 23:11:54 +00005469 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
5470 MD->getResultType(), MD);
5471 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00005472 } else {
John McCalld226f652010-08-21 09:40:31 +00005473 return 0;
Ted Kremenek8189cde2009-02-07 01:47:29 +00005474 }
Douglas Gregore2c31ff2009-05-15 17:59:04 +00005475
Reid Spencer5f016e22007-07-11 17:01:13 +00005476 // Verify and clean out per-function state.
Eli Friedman8f17b662009-02-28 05:41:13 +00005477
Reid Spencer5f016e22007-07-11 17:01:13 +00005478 // Check goto/label use.
John McCall781472f2010-08-25 08:40:02 +00005479 FunctionScopeInfo *CurFn = getCurFunction();
Steve Naroffcaaacec2009-03-13 15:38:40 +00005480 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
John McCall781472f2010-08-25 08:40:02 +00005481 I = CurFn->LabelMap.begin(), E = CurFn->LabelMap.end(); I != E; ++I) {
Chris Lattnere32f74c2009-04-18 19:30:02 +00005482 LabelStmt *L = I->second;
Mike Stump1eb44332009-09-09 15:08:12 +00005483
Reid Spencer5f016e22007-07-11 17:01:13 +00005484 // Verify that we have no forward references left. If so, there was a goto
5485 // or address of a label taken, but no definition of it. Label fwd
5486 // definitions are indicated with a null substmt.
Argyrios Kyrtzidis355a9fe2010-09-19 21:21:25 +00005487 if (L->getSubStmt() != 0) {
5488 if (!L->isUsed())
5489 Diag(L->getIdentLoc(), diag::warn_unused_label) << L->getName();
Chris Lattnere32f74c2009-04-18 19:30:02 +00005490 continue;
Argyrios Kyrtzidis355a9fe2010-09-19 21:21:25 +00005491 }
Mike Stump1eb44332009-09-09 15:08:12 +00005492
Chris Lattnere32f74c2009-04-18 19:30:02 +00005493 // Emit error.
5494 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00005495
Chris Lattnere32f74c2009-04-18 19:30:02 +00005496 // At this point, we have gotos that use the bogus label. Stitch it into
5497 // the function body so that they aren't leaked and that the AST is well
5498 // formed.
5499 if (Body == 0) {
Douglas Gregorff331c12010-07-25 18:17:45 +00005500 // The whole function wasn't parsed correctly.
Chris Lattnere32f74c2009-04-18 19:30:02 +00005501 continue;
Reid Spencer5f016e22007-07-11 17:01:13 +00005502 }
Mike Stump1eb44332009-09-09 15:08:12 +00005503
Chris Lattnere32f74c2009-04-18 19:30:02 +00005504 // Otherwise, the body is valid: we want to stitch the label decl into the
5505 // function somewhere so that it is properly owned and so that the goto
5506 // has a valid target. Do this by creating a new compound stmt with the
5507 // label in it.
Sebastian Redld3a413d2009-04-26 20:35:05 +00005508
Chris Lattnere32f74c2009-04-18 19:30:02 +00005509 // Give the label a sub-statement.
5510 L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
Sebastian Redld3a413d2009-04-26 20:35:05 +00005511
5512 CompoundStmt *Compound = isa<CXXTryStmt>(Body) ?
5513 cast<CXXTryStmt>(Body)->getTryBlock() :
5514 cast<CompoundStmt>(Body);
Ted Kremenek4c9f7092010-03-12 22:22:36 +00005515 llvm::SmallVector<Stmt*, 64> Elements(Compound->body_begin(),
5516 Compound->body_end());
Chris Lattnere32f74c2009-04-18 19:30:02 +00005517 Elements.push_back(L);
Ted Kremenek4c9f7092010-03-12 22:22:36 +00005518 Compound->setStmts(Context, Elements.data(), Elements.size());
Reid Spencer5f016e22007-07-11 17:01:13 +00005519 }
Eli Friedman8f17b662009-02-28 05:41:13 +00005520
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00005521 if (Body) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00005522 // C++ constructors that have function-try-blocks can't have return
5523 // statements in the handlers of that block. (C++ [except.handle]p14)
5524 // Verify this.
5525 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
5526 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
5527
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00005528 // Verify that that gotos and switch cases don't jump into scopes illegally.
5529 // Verify that that gotos and switch cases don't jump into scopes illegally.
John McCall781472f2010-08-25 08:40:02 +00005530 if (getCurFunction()->NeedsScopeChecking() &&
John McCall8a2ca742010-05-20 07:13:26 +00005531 !dcl->isInvalidDecl() &&
John McCalldae69ef2010-05-20 07:05:55 +00005532 !hasAnyErrorsInThisFunction())
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00005533 DiagnoseInvalidJumps(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00005534
John McCall15442822010-08-04 01:04:25 +00005535 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
5536 if (!Destructor->getParent()->isDependentType())
5537 CheckDestructor(Destructor);
5538
John McCallef027fe2010-03-16 21:39:52 +00005539 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
5540 Destructor->getParent());
John McCall15442822010-08-04 01:04:25 +00005541 }
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00005542
5543 // If any errors have occurred, clear out any temporaries that may have
5544 // been leftover. This ensures that these temporaries won't be picked up for
5545 // deletion in some later function.
5546 if (PP.getDiagnostics().hasErrorOccurred())
5547 ExprTemporaries.clear();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00005548 else if (!isa<FunctionTemplateDecl>(dcl)) {
5549 // Since the body is valid, issue any analysis-based warnings that are
5550 // enabled.
5551 QualType ResultType;
5552 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
John McCalle0054f62010-08-25 05:56:39 +00005553 AnalysisWarnings.IssueWarnings(WP, FD);
5554 } else {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00005555 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(dcl);
John McCalle0054f62010-08-25 05:56:39 +00005556 AnalysisWarnings.IssueWarnings(WP, MD);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00005557 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00005558 }
5559
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00005560 assert(ExprTemporaries.empty() && "Leftover temporaries in function");
5561 }
5562
John McCall90f97892010-03-25 22:08:03 +00005563 if (!IsInstantiation)
5564 PopDeclContext();
5565
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00005566 PopFunctionOrBlockScope();
Anders Carlssonf8a9a792009-11-13 19:21:49 +00005567
Douglas Gregord5b57282009-11-15 07:07:58 +00005568 // If any errors have occurred, clear out any temporaries that may have
5569 // been leftover. This ensures that these temporaries won't be picked up for
5570 // deletion in some later function.
Chris Lattner6d97e5e2010-03-01 20:59:53 +00005571 if (getDiagnostics().hasErrorOccurred())
Douglas Gregord5b57282009-11-15 07:07:58 +00005572 ExprTemporaries.clear();
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +00005573
John McCalld226f652010-08-21 09:40:31 +00005574 return dcl;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00005575}
5576
Reid Spencer5f016e22007-07-11 17:01:13 +00005577/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
5578/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump1eb44332009-09-09 15:08:12 +00005579NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005580 IdentifierInfo &II, Scope *S) {
Douglas Gregor63935192009-03-02 00:19:53 +00005581 // Before we produce a declaration for an implicitly defined
5582 // function, see whether there was a locally-scoped declaration of
5583 // this name as a function or variable. If so, use that
5584 // (non-visible) declaration, and complain about it.
5585 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
5586 = LocallyScopedExternalDecls.find(&II);
5587 if (Pos != LocallyScopedExternalDecls.end()) {
5588 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
5589 Diag(Pos->second->getLocation(), diag::note_previous_declaration);
5590 return Pos->second;
5591 }
5592
Chris Lattner37d10842008-05-05 21:18:06 +00005593 // Extension in C99. Legal in C90, but warn about it.
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00005594 if (II.getName().startswith("__builtin_"))
Douglas Gregor9a8c9a22009-09-28 21:14:19 +00005595 Diag(Loc, diag::warn_builtin_unknown) << &II;
5596 else if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00005597 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00005598 else
Chris Lattner3c73c412008-11-19 08:23:25 +00005599 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Mike Stump1eb44332009-09-09 15:08:12 +00005600
Reid Spencer5f016e22007-07-11 17:01:13 +00005601 // Set a Declarator for the implicit definition: int foo();
5602 const char *Dummy;
5603 DeclSpec DS;
John McCallfec54012009-08-03 20:12:06 +00005604 unsigned DiagID;
5605 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00005606 (void)Error; // Silence warning.
Reid Spencer5f016e22007-07-11 17:01:13 +00005607 assert(!Error && "Error setting up implicit decl!");
5608 Declarator D(DS, Declarator::BlockContext);
John McCall7f040a92010-12-24 02:08:15 +00005609 D.AddTypeInfo(DeclaratorChunk::getFunction(ParsedAttributes(),
5610 false, false, SourceLocation(), 0,
Douglas Gregor83f51722011-01-26 03:43:54 +00005611 0, 0, true, SourceLocation(),
5612 false, SourceLocation(),
Argyrios Kyrtzidis82bf0102009-08-19 23:14:54 +00005613 false, 0,0,0, Loc, Loc, D),
Sebastian Redlab197ba2009-02-09 18:23:29 +00005614 SourceLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00005615 D.SetIdentifier(&II, Loc);
Sebastian Redlab197ba2009-02-09 18:23:29 +00005616
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00005617 // Insert this function into translation-unit scope.
5618
5619 DeclContext *PrevDC = CurContext;
5620 CurContext = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00005621
John McCalld226f652010-08-21 09:40:31 +00005622 FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroffe2ef8152008-04-04 14:32:09 +00005623 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00005624
5625 CurContext = PrevDC;
5626
Douglas Gregor3c385e52009-02-14 18:57:46 +00005627 AddKnownFunctionAttributes(FD);
5628
Steve Naroffe2ef8152008-04-04 14:32:09 +00005629 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00005630}
5631
Douglas Gregor3c385e52009-02-14 18:57:46 +00005632/// \brief Adds any function attributes that we know a priori based on
5633/// the declaration of this function.
5634///
5635/// These attributes can apply both to implicitly-declared builtins
5636/// (like __builtin___printf_chk) or to library-declared functions
5637/// like NSLog or printf.
5638void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
5639 if (FD->isInvalidDecl())
5640 return;
5641
5642 // If this is a built-in function, map its builtin attributes to
5643 // actual attributes.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00005644 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00005645 // Handle printf-formatting attributes.
5646 unsigned FormatIdx;
5647 bool HasVAListArg;
5648 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005649 if (!FD->getAttr<FormatAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00005650 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
5651 "printf", FormatIdx+1,
Ted Kremenek3d2c43e2010-02-11 05:28:37 +00005652 HasVAListArg ? 0 : FormatIdx+2));
Douglas Gregor3c385e52009-02-14 18:57:46 +00005653 }
Ted Kremenekbee05c12010-07-16 02:11:15 +00005654 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
5655 HasVAListArg)) {
5656 if (!FD->getAttr<FormatAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00005657 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
5658 "scanf", FormatIdx+1,
Ted Kremenekbee05c12010-07-16 02:11:15 +00005659 HasVAListArg ? 0 : FormatIdx+2));
5660 }
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00005661
5662 // Mark const if we don't care about errno and that is the only
5663 // thing preventing the function from being const. This allows
5664 // IRgen to use LLVM intrinsics for such functions.
5665 if (!getLangOptions().MathErrno &&
5666 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005667 if (!FD->getAttr<ConstAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00005668 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00005669 }
Mike Stump0feecbb2009-07-27 19:14:18 +00005670
Chris Lattner551f7082009-12-30 22:06:22 +00005671 if (Context.BuiltinInfo.isNoThrow(BuiltinID))
Sean Huntcf807c42010-08-18 23:23:40 +00005672 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
Chris Lattner551f7082009-12-30 22:06:22 +00005673 if (Context.BuiltinInfo.isConst(BuiltinID))
Sean Huntcf807c42010-08-18 23:23:40 +00005674 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Douglas Gregor3c385e52009-02-14 18:57:46 +00005675 }
5676
5677 IdentifierInfo *Name = FD->getIdentifier();
5678 if (!Name)
5679 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005680 if ((!getLangOptions().CPlusPlus &&
Douglas Gregor3c385e52009-02-14 18:57:46 +00005681 FD->getDeclContext()->isTranslationUnit()) ||
5682 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00005683 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregor3c385e52009-02-14 18:57:46 +00005684 LinkageSpecDecl::lang_c)) {
5685 // Okay: this could be a libc/libm/Objective-C function we know
5686 // about.
5687 } else
5688 return;
5689
Douglas Gregor21e072b2009-04-22 20:56:09 +00005690 if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
Mike Stump523a8fd2009-07-28 00:07:08 +00005691 // FIXME: NSLog and NSLogv should be target specific
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005692 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00005693 // FIXME: We known better than our headers.
Ted Kremenek3d2c43e2010-02-11 05:28:37 +00005694 const_cast<FormatAttr *>(Format)->setType(Context, "printf");
Mike Stump1eb44332009-09-09 15:08:12 +00005695 } else
Sean Huntcf807c42010-08-18 23:23:40 +00005696 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
5697 "printf", 1,
Eli Friedmand7dad722009-06-10 04:01:38 +00005698 Name->isStr("NSLogv") ? 0 : 2));
Douglas Gregor21e072b2009-04-22 20:56:09 +00005699 } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump523a8fd2009-07-28 00:07:08 +00005700 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump1eb44332009-09-09 15:08:12 +00005701 // target-specific builtins, perhaps?
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005702 if (!FD->getAttr<FormatAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00005703 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
5704 "printf", 2,
Eli Friedmand7dad722009-06-10 04:01:38 +00005705 Name->isStr("vasprintf") ? 0 : 3));
Mike Stump782fa302009-07-28 02:25:19 +00005706 }
Douglas Gregor3c385e52009-02-14 18:57:46 +00005707}
Reid Spencer5f016e22007-07-11 17:01:13 +00005708
John McCallba6a9bd2009-10-24 08:00:42 +00005709TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCalla93c9342009-12-07 02:54:59 +00005710 TypeSourceInfo *TInfo) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005711 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00005712 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump1eb44332009-09-09 15:08:12 +00005713
John McCalla93c9342009-12-07 02:54:59 +00005714 if (!TInfo) {
John McCallba6a9bd2009-10-24 08:00:42 +00005715 assert(D.isInvalidType() && "no declarator info for valid type");
John McCalla93c9342009-12-07 02:54:59 +00005716 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCallba6a9bd2009-10-24 08:00:42 +00005717 }
5718
Reid Spencer5f016e22007-07-11 17:01:13 +00005719 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00005720 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
5721 D.getIdentifierLoc(),
Mike Stump1eb44332009-09-09 15:08:12 +00005722 D.getIdentifier(),
John McCalla93c9342009-12-07 02:54:59 +00005723 TInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00005724
John McCallcde5a402011-02-01 08:20:08 +00005725 // Bail out immediately if we have an invalid declaration.
5726 if (D.isInvalidType()) {
5727 NewTD->setInvalidDecl();
5728 return NewTD;
Anders Carlsson4843e582009-03-10 17:07:44 +00005729 }
5730
John McCallcde5a402011-02-01 08:20:08 +00005731 // C++ [dcl.typedef]p8:
5732 // If the typedef declaration defines an unnamed class (or
5733 // enum), the first typedef-name declared by the declaration
5734 // to be that class type (or enum type) is used to denote the
5735 // class type (or enum type) for linkage purposes only.
5736 // We need to check whether the type was declared in the declaration.
5737 switch (D.getDeclSpec().getTypeSpecType()) {
5738 case TST_enum:
5739 case TST_struct:
5740 case TST_union:
5741 case TST_class: {
5742 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
5743
5744 // Do nothing if the tag is not anonymous or already has an
5745 // associated typedef (from an earlier typedef in this decl group).
5746 if (tagFromDeclSpec->getIdentifier()) break;
5747 if (tagFromDeclSpec->getTypedefForAnonDecl()) break;
5748
5749 // A well-formed anonymous tag must always be a TUK_Definition.
5750 assert(tagFromDeclSpec->isThisDeclarationADefinition());
5751
5752 // The type must match the tag exactly; no qualifiers allowed.
5753 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
5754 break;
5755
5756 // Otherwise, set this is the anon-decl typedef for the tag.
5757 tagFromDeclSpec->setTypedefForAnonDecl(NewTD);
5758 break;
5759 }
5760
5761 default:
5762 break;
5763 }
5764
Steve Naroff5912a352007-08-28 20:14:24 +00005765 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00005766}
5767
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005768
5769/// \brief Determine whether a tag with a given kind is acceptable
5770/// as a redeclaration of the given tag declaration.
5771///
5772/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00005773bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005774 TagTypeKind NewTag,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005775 SourceLocation NewTagLoc,
5776 const IdentifierInfo &Name) {
5777 // C++ [dcl.type.elab]p3:
5778 // The class-key or enum keyword present in the
5779 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005780 // declaration to which the name in the elaborated-type-specifier
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005781 // refers. This rule also applies to the form of
5782 // elaborated-type-specifier that declares a class-name or
5783 // friend class since it can be construed as referring to the
5784 // definition of the class. Thus, in any
5785 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005786 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005787 // used to refer to a union (clause 9), and either the class or
5788 // struct class-key shall be used to refer to a class (clause 9)
5789 // declared using the class or struct class-key.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005790 TagTypeKind OldTag = Previous->getTagKind();
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005791 if (OldTag == NewTag)
5792 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005793
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005794 if ((OldTag == TTK_Struct || OldTag == TTK_Class) &&
5795 (NewTag == TTK_Struct || NewTag == TTK_Class)) {
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005796 // Warn about the struct/class tag mismatch.
5797 bool isTemplate = false;
5798 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
5799 isTemplate = Record->getDescribedClassTemplate();
5800
5801 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005802 << (NewTag == TTK_Class)
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005803 << isTemplate << &Name
Douglas Gregor849b2432010-03-31 17:46:05 +00005804 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005805 OldTag == TTK_Class? "class" : "struct");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005806 Diag(Previous->getLocation(), diag::note_previous_use);
5807 return true;
5808 }
5809 return false;
5810}
5811
Steve Naroff08d92e42007-09-15 18:49:24 +00005812/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00005813/// former case, Name will be non-null. In the later case, Name will be null.
John McCall0f434ec2009-07-31 02:45:11 +00005814/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Reid Spencer5f016e22007-07-11 17:01:13 +00005815/// reference/declaration/definition of a tag.
John McCalld226f652010-08-21 09:40:31 +00005816Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor069ea642010-09-16 23:58:57 +00005817 SourceLocation KWLoc, CXXScopeSpec &SS,
5818 IdentifierInfo *Name, SourceLocation NameLoc,
5819 AttributeList *Attr, AccessSpecifier AS,
5820 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +00005821 bool &OwnedDecl, bool &IsDependent,
5822 bool ScopedEnum, bool ScopedEnumUsesClassTag,
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005823 TypeResult UnderlyingType) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005824 // If this is not a definition, it must have a name.
John McCall0f434ec2009-07-31 02:45:11 +00005825 assert((Name != 0 || TUK == TUK_Definition) &&
Reid Spencer5f016e22007-07-11 17:01:13 +00005826 "Nameless record must be a definition!");
John McCall9a34edb2010-10-19 01:40:49 +00005827 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregoraaba5e32009-02-04 19:02:06 +00005828
Douglas Gregor402abb52009-05-28 23:31:59 +00005829 OwnedDecl = false;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005830 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00005831
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005832 // FIXME: Check explicit specializations more carefully.
5833 bool isExplicitSpecialization = false;
Abramo Bagnara9b934882010-06-12 08:15:14 +00005834 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
Douglas Gregor0167f3c2010-07-14 23:14:12 +00005835 bool Invalid = false;
John McCall9a34edb2010-10-19 01:40:49 +00005836
5837 // We only need to do this matching if we have template parameters
5838 // or a scope specifier, which also conveniently avoids this work
5839 // for non-C++ cases.
5840 if (NumMatchedTemplateParamLists ||
5841 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Douglas Gregor7cdbc582009-07-22 23:48:44 +00005842 if (TemplateParameterList *TemplateParams
5843 = MatchTemplateParametersToScopeSpecifier(KWLoc, SS,
John McCallbe04b6d2010-10-16 07:23:36 +00005844 TemplateParameterLists.get(),
5845 TemplateParameterLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00005846 TUK == TUK_Friend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00005847 isExplicitSpecialization,
5848 Invalid)) {
Abramo Bagnara9b934882010-06-12 08:15:14 +00005849 // All but one template parameter lists have been matching.
5850 --NumMatchedTemplateParamLists;
5851
Douglas Gregord85bea22009-09-26 06:47:28 +00005852 if (TemplateParams->size() > 0) {
Douglas Gregor7cdbc582009-07-22 23:48:44 +00005853 // This is a declaration or definition of a class template (which may
5854 // be a member of another template).
Douglas Gregor0167f3c2010-07-14 23:14:12 +00005855 if (Invalid)
John McCalld226f652010-08-21 09:40:31 +00005856 return 0;
Douglas Gregor0167f3c2010-07-14 23:14:12 +00005857
Douglas Gregor7cdbc582009-07-22 23:48:44 +00005858 OwnedDecl = false;
John McCall0f434ec2009-07-31 02:45:11 +00005859 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00005860 SS, Name, NameLoc, Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00005861 TemplateParams,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00005862 AS);
Douglas Gregor05396e22009-08-25 17:23:04 +00005863 TemplateParameterLists.release();
Douglas Gregor7cdbc582009-07-22 23:48:44 +00005864 return Result.get();
5865 } else {
Douglas Gregorf6b11852009-10-08 15:14:33 +00005866 // The "template<>" header is extraneous.
5867 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005868 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorf6b11852009-10-08 15:14:33 +00005869 isExplicitSpecialization = true;
Douglas Gregor7cdbc582009-07-22 23:48:44 +00005870 }
Mike Stump1eb44332009-09-09 15:08:12 +00005871 }
5872 }
5873
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005874 // Figure out the underlying type if this a enum declaration. We need to do
5875 // this early, because it's needed to detect if this is an incompatible
5876 // redeclaration.
5877 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
5878
5879 if (Kind == TTK_Enum) {
5880 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
5881 // No underlying type explicitly specified, or we failed to parse the
5882 // type, default to int.
5883 EnumUnderlying = Context.IntTy.getTypePtr();
5884 else if (UnderlyingType.get()) {
5885 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
5886 // integral type; any cv-qualification is ignored.
5887 TypeSourceInfo *TI = 0;
5888 QualType T = GetTypeFromParser(UnderlyingType.get(), &TI);
5889 EnumUnderlying = TI;
5890
5891 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
5892
5893 if (!T->isDependentType() && !T->isIntegralType(Context)) {
5894 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
5895 << T;
5896 // Recover by falling back to int.
5897 EnumUnderlying = Context.IntTy.getTypePtr();
5898 }
Douglas Gregor0c9e4792010-12-16 00:24:44 +00005899
5900 if (DiagnoseUnexpandedParameterPack(UnderlyingLoc, TI,
5901 UPPC_FixedUnderlyingType))
5902 EnumUnderlying = Context.IntTy.getTypePtr();
5903
Francois Pichet842e7a22010-10-18 15:01:13 +00005904 } else if (getLangOptions().Microsoft)
5905 // Microsoft enums are always of int type.
5906 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005907 }
5908
Douglas Gregor4920f1f2009-01-12 22:49:06 +00005909 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00005910 DeclContext *DC = CurContext;
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005911 bool isStdBadAlloc = false;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00005912
Chandler Carruth7bf36002010-03-01 21:17:36 +00005913 RedeclarationKind Redecl = ForRedeclaration;
5914 if (TUK == TUK_Friend || TUK == TUK_Reference)
5915 Redecl = NotForRedeclaration;
John McCall68263142009-11-18 22:49:29 +00005916
5917 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
John McCall6e247262009-10-10 05:48:19 +00005918
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00005919 if (Name && SS.isNotEmpty()) {
5920 // We have a nested-name tag ('struct foo::bar').
5921
5922 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00005923 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00005924 Name = 0;
5925 goto CreateNewDecl;
5926 }
5927
John McCallc4e70192009-09-11 04:59:25 +00005928 // If this is a friend or a reference to a class in a dependent
5929 // context, don't try to make a decl for it.
5930 if (TUK == TUK_Friend || TUK == TUK_Reference) {
5931 DC = computeDeclContext(SS, false);
5932 if (!DC) {
5933 IsDependent = true;
John McCalld226f652010-08-21 09:40:31 +00005934 return 0;
John McCallc4e70192009-09-11 04:59:25 +00005935 }
John McCall77bb1aa2010-05-01 00:40:08 +00005936 } else {
5937 DC = computeDeclContext(SS, true);
5938 if (!DC) {
5939 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
5940 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005941 return 0;
John McCall77bb1aa2010-05-01 00:40:08 +00005942 }
John McCallc4e70192009-09-11 04:59:25 +00005943 }
5944
John McCall77bb1aa2010-05-01 00:40:08 +00005945 if (RequireCompleteDeclContext(SS, DC))
John McCalld226f652010-08-21 09:40:31 +00005946 return 0;
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005947
Douglas Gregor1931b442009-02-03 00:34:39 +00005948 SearchDC = DC;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00005949 // Look-up name inside 'foo::'.
John McCall68263142009-11-18 22:49:29 +00005950 LookupQualifiedName(Previous, DC);
John McCall6e247262009-10-10 05:48:19 +00005951
John McCall68263142009-11-18 22:49:29 +00005952 if (Previous.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005953 return 0;
John McCall6e247262009-10-10 05:48:19 +00005954
John McCall68263142009-11-18 22:49:29 +00005955 if (Previous.empty()) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +00005956 // Name lookup did not find anything. However, if the
5957 // nested-name-specifier refers to the current instantiation,
5958 // and that current instantiation has any dependent base
5959 // classes, we might find something at instantiation time: treat
5960 // this as a dependent elaborated-type-specifier.
John McCall9a34edb2010-10-19 01:40:49 +00005961 // But this only makes any sense for reference-like lookups.
5962 if (Previous.wasNotFoundInCurrentInstantiation() &&
5963 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +00005964 IsDependent = true;
John McCalld226f652010-08-21 09:40:31 +00005965 return 0;
Douglas Gregor9edad9b2010-01-14 17:47:39 +00005966 }
5967
5968 // A tag 'foo::bar' must already exist.
Douglas Gregor1eabb7d2010-03-31 23:17:41 +00005969 Diag(NameLoc, diag::err_not_tag_in_scope)
5970 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00005971 Name = 0;
Douglas Gregord0c87372009-05-27 17:30:49 +00005972 Invalid = true;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00005973 goto CreateNewDecl;
5974 }
Chris Lattnercf79b012009-01-21 02:38:50 +00005975 } else if (Name) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00005976 // If this is a named struct, check to see if there was a previous forward
5977 // declaration or definition.
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005978 // FIXME: We're looking into outer scopes here, even when we
5979 // shouldn't be. Doing so can result in ambiguities that we
5980 // shouldn't be diagnosing.
John McCall68263142009-11-18 22:49:29 +00005981 LookupName(Previous, S);
5982
5983 // Note: there used to be some attempt at recovery here.
5984 if (Previous.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005985 return 0;
Douglas Gregor72de6672009-01-08 20:45:30 +00005986
John McCall0f434ec2009-07-31 02:45:11 +00005987 if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor72de6672009-01-08 20:45:30 +00005988 // FIXME: This makes sure that we ignore the contexts associated
5989 // with C structs, unions, and enums when looking for a matching
5990 // tag declaration or definition. See the similar lookup tweak
Douglas Gregor4c921ae2009-01-30 01:04:22 +00005991 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregor4920f1f2009-01-12 22:49:06 +00005992 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
5993 SearchDC = SearchDC->getParent();
Douglas Gregor72de6672009-01-08 20:45:30 +00005994 }
Douglas Gregor069ea642010-09-16 23:58:57 +00005995 } else if (S->isFunctionPrototypeScope()) {
5996 // If this is an enum declaration in function prototype scope, set its
5997 // initial context to the translation unit.
5998 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00005999 }
6000
John McCall68263142009-11-18 22:49:29 +00006001 if (Previous.isSingleResult() &&
6002 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00006003 // Maybe we will complain about the shadowed template parameter.
John McCall68263142009-11-18 22:49:29 +00006004 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor72c3f312008-12-05 18:15:24 +00006005 // Just pretend that we didn't see the previous declaration.
John McCall68263142009-11-18 22:49:29 +00006006 Previous.clear();
Douglas Gregor72c3f312008-12-05 18:15:24 +00006007 }
6008
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006009 if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006010 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006011 // This is a declaration of or a reference to "std::bad_alloc".
6012 isStdBadAlloc = true;
6013
John McCall68263142009-11-18 22:49:29 +00006014 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006015 // std::bad_alloc has been implicitly declared (but made invisible to
6016 // name lookup). Fill in this implicit declaration as the previous
6017 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006018 Previous.addDecl(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006019 }
6020 }
John McCall68263142009-11-18 22:49:29 +00006021
John McCall9c86b512010-03-25 21:28:06 +00006022 // If we didn't find a previous declaration, and this is a reference
6023 // (or friend reference), move to the correct scope. In C++, we
6024 // also need to do a redeclaration lookup there, just in case
6025 // there's a shadow friend decl.
6026 if (Name && Previous.empty() &&
6027 (TUK == TUK_Reference || TUK == TUK_Friend)) {
6028 if (Invalid) goto CreateNewDecl;
6029 assert(SS.isEmpty());
6030
6031 if (TUK == TUK_Reference) {
6032 // C++ [basic.scope.pdecl]p5:
6033 // -- for an elaborated-type-specifier of the form
6034 //
6035 // class-key identifier
6036 //
6037 // if the elaborated-type-specifier is used in the
6038 // decl-specifier-seq or parameter-declaration-clause of a
6039 // function defined in namespace scope, the identifier is
6040 // declared as a class-name in the namespace that contains
6041 // the declaration; otherwise, except as a friend
6042 // declaration, the identifier is declared in the smallest
6043 // non-class, non-function-prototype scope that contains the
6044 // declaration.
6045 //
6046 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
6047 // C structs and unions.
6048 //
6049 // It is an error in C++ to declare (rather than define) an enum
6050 // type, including via an elaborated type specifier. We'll
6051 // diagnose that later; for now, declare the enum in the same
6052 // scope as we would have picked for any other tag type.
6053 //
6054 // GNU C also supports this behavior as part of its incomplete
6055 // enum types extension, while GNU C++ does not.
6056 //
6057 // Find the context where we'll be declaring the tag.
6058 // FIXME: We would like to maintain the current DeclContext as the
6059 // lexical context,
Rafael Espindola706df2f2011-01-20 02:26:24 +00006060 while (SearchDC->isRecord() || SearchDC->isTransparentContext())
John McCall9c86b512010-03-25 21:28:06 +00006061 SearchDC = SearchDC->getParent();
6062
6063 // Find the scope where we'll be declaring the tag.
6064 while (S->isClassScope() ||
6065 (getLangOptions().CPlusPlus &&
6066 S->isFunctionPrototypeScope()) ||
6067 ((S->getFlags() & Scope::DeclScope) == 0) ||
6068 (S->getEntity() &&
6069 ((DeclContext *)S->getEntity())->isTransparentContext()))
6070 S = S->getParent();
6071 } else {
6072 assert(TUK == TUK_Friend);
6073 // C++ [namespace.memdef]p3:
6074 // If a friend declaration in a non-local class first declares a
6075 // class or function, the friend class or function is a member of
6076 // the innermost enclosing namespace.
6077 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCall9c86b512010-03-25 21:28:06 +00006078 }
6079
John McCall0d6b1642010-04-23 18:46:30 +00006080 // In C++, we need to do a redeclaration lookup to properly
6081 // diagnose some problems.
John McCall9c86b512010-03-25 21:28:06 +00006082 if (getLangOptions().CPlusPlus) {
6083 Previous.setRedeclarationKind(ForRedeclaration);
6084 LookupQualifiedName(Previous, SearchDC);
6085 }
6086 }
6087
John McCall68263142009-11-18 22:49:29 +00006088 if (!Previous.empty()) {
Douglas Gregor57265e32010-04-12 16:00:01 +00006089 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
John McCall0d6b1642010-04-23 18:46:30 +00006090
6091 // It's okay to have a tag decl in the same scope as a typedef
6092 // which hides a tag decl in the same scope. Finding this
6093 // insanity with a redeclaration lookup can only actually happen
6094 // in C++.
6095 //
6096 // This is also okay for elaborated-type-specifiers, which is
6097 // technically forbidden by the current standard but which is
6098 // okay according to the likely resolution of an open issue;
6099 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
6100 if (getLangOptions().CPlusPlus) {
6101 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(PrevDecl)) {
6102 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
6103 TagDecl *Tag = TT->getDecl();
6104 if (Tag->getDeclName() == Name &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006105 Tag->getDeclContext()->getRedeclContext()
6106 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCall0d6b1642010-04-23 18:46:30 +00006107 PrevDecl = Tag;
6108 Previous.clear();
6109 Previous.addDecl(Tag);
Douglas Gregor757c6002010-08-27 22:55:10 +00006110 Previous.resolveKind();
John McCall0d6b1642010-04-23 18:46:30 +00006111 }
6112 }
6113 }
6114 }
6115
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006116 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00006117 // If this is a use of a previous tag, or if the tag is already declared
6118 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006119 // rementions the tag), reuse the decl.
John McCall67d1a672009-08-06 02:15:43 +00006120 if (TUK == TUK_Reference || TUK == TUK_Friend ||
6121 isDeclInScope(PrevDecl, SearchDC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00006122 // Make sure that this wasn't declared as an enum and now used as a
6123 // struct or something similar.
Douglas Gregor501c5ce2009-05-14 16:41:31 +00006124 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006125 bool SafeToContinue
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006126 = (PrevTagDecl->getTagKind() != TTK_Enum &&
6127 Kind != TTK_Enum);
Douglas Gregora3a83512009-04-01 23:51:29 +00006128 if (SafeToContinue)
Mike Stump1eb44332009-09-09 15:08:12 +00006129 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00006130 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +00006131 << FixItHint::CreateReplacement(SourceRange(KWLoc),
6132 PrevTagDecl->getKindName());
Douglas Gregora3a83512009-04-01 23:51:29 +00006133 else
6134 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall68263142009-11-18 22:49:29 +00006135 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +00006136
Mike Stump1eb44332009-09-09 15:08:12 +00006137 if (SafeToContinue)
Douglas Gregora3a83512009-04-01 23:51:29 +00006138 Kind = PrevTagDecl->getTagKind();
6139 else {
6140 // Recover by making this an anonymous redefinition.
6141 Name = 0;
John McCall68263142009-11-18 22:49:29 +00006142 Previous.clear();
Douglas Gregora3a83512009-04-01 23:51:29 +00006143 Invalid = true;
6144 }
6145 }
6146
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006147 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
6148 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
6149
6150 // All conflicts with previous declarations are recovered by
6151 // returning the previous declaration.
6152 if (ScopedEnum != PrevEnum->isScoped()) {
6153 Diag(KWLoc, diag::err_enum_redeclare_scoped_mismatch)
6154 << PrevEnum->isScoped();
6155 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
6156 return PrevTagDecl;
6157 }
6158 else if (EnumUnderlying && PrevEnum->isFixed()) {
6159 QualType T;
6160 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
6161 T = TI->getType();
6162 else
6163 T = QualType(EnumUnderlying.get<const Type*>(), 0);
6164
6165 if (!Context.hasSameUnqualifiedType(T, PrevEnum->getIntegerType())) {
Douglas Gregord11617f2010-12-01 16:10:38 +00006166 Diag(NameLoc.isValid() ? NameLoc : KWLoc,
6167 diag::err_enum_redeclare_type_mismatch)
6168 << T
6169 << PrevEnum->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006170 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
6171 return PrevTagDecl;
6172 }
6173 }
6174 else if (!EnumUnderlying.isNull() != PrevEnum->isFixed()) {
6175 Diag(KWLoc, diag::err_enum_redeclare_fixed_mismatch)
6176 << PrevEnum->isFixed();
6177 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
6178 return PrevTagDecl;
6179 }
6180 }
6181
Douglas Gregora3a83512009-04-01 23:51:29 +00006182 if (!Invalid) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00006183 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +00006184
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00006185 // FIXME: In the future, return a variant or some other clue
6186 // for the consumer of this Decl to know it doesn't own it.
6187 // For our current ASTs this shouldn't be a problem, but will
6188 // need to be changed with DeclGroups.
Douglas Gregore1aa9f32010-06-08 21:27:36 +00006189 if ((TUK == TUK_Reference && !PrevTagDecl->getFriendObjectKind()) ||
6190 TUK == TUK_Friend)
John McCalld226f652010-08-21 09:40:31 +00006191 return PrevTagDecl;
Douglas Gregoraaba5e32009-02-04 19:02:06 +00006192
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00006193 // Diagnose attempts to redefine a tag.
John McCall0f434ec2009-07-31 02:45:11 +00006194 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00006195 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006196 // If we're defining a specialization and the previous definition
6197 // is from an implicit instantiation, don't emit an error
6198 // here; we'll catch this in the general case below.
6199 if (!isExplicitSpecialization ||
6200 !isa<CXXRecordDecl>(Def) ||
6201 cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
6202 == TSK_ExplicitSpecialization) {
6203 Diag(NameLoc, diag::err_redefinition) << Name;
6204 Diag(Def->getLocation(), diag::note_previous_definition);
6205 // If this is a redefinition, recover by making this
6206 // struct be anonymous, which will make any later
6207 // references get the previous definition.
6208 Name = 0;
John McCall68263142009-11-18 22:49:29 +00006209 Previous.clear();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00006210 Invalid = true;
6211 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +00006212 } else {
6213 // If the type is currently being defined, complain
6214 // about a nested redefinition.
John McCallf4c73712011-01-19 06:33:43 +00006215 const TagType *Tag
6216 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregor0b7a1582009-01-17 00:42:38 +00006217 if (Tag->isBeingDefined()) {
6218 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump1eb44332009-09-09 15:08:12 +00006219 Diag(PrevTagDecl->getLocation(),
Douglas Gregor0b7a1582009-01-17 00:42:38 +00006220 diag::note_previous_definition);
6221 Name = 0;
John McCall68263142009-11-18 22:49:29 +00006222 Previous.clear();
Douglas Gregor0b7a1582009-01-17 00:42:38 +00006223 Invalid = true;
6224 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00006225 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +00006226
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00006227 // Okay, this is definition of a previously declared or referenced
6228 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00006229 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006230 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00006231 // If we get here we have (another) forward declaration or we
John McCall67d1a672009-08-06 02:15:43 +00006232 // have a definition. Just create a new decl.
6233
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00006234 } else {
6235 // If we get here, this is a definition of a new tag type in a nested
Mike Stump1eb44332009-09-09 15:08:12 +00006236 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00006237 // new decl/type. We set PrevDecl to NULL so that the entities
6238 // have distinct types.
John McCall68263142009-11-18 22:49:29 +00006239 Previous.clear();
Reid Spencer5f016e22007-07-11 17:01:13 +00006240 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00006241 // If we get here, we're going to create a new Decl. If PrevDecl
6242 // is non-NULL, it's a definition of the tag declared by
6243 // PrevDecl. If it's NULL, we have a new definition.
John McCall0d6b1642010-04-23 18:46:30 +00006244
6245
6246 // Otherwise, PrevDecl is not a tag, but was found with tag
6247 // lookup. This is only actually possible in C++, where a few
6248 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006249 } else {
John McCall0d6b1642010-04-23 18:46:30 +00006250 assert(getLangOptions().CPlusPlus);
6251
6252 // Use a better diagnostic if an elaborated-type-specifier
6253 // found the wrong kind of type on the first
6254 // (non-redeclaration) lookup.
6255 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
6256 !Previous.isForRedeclaration()) {
6257 unsigned Kind = 0;
6258 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
6259 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 2;
6260 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
6261 Diag(PrevDecl->getLocation(), diag::note_declared_at);
6262 Invalid = true;
6263
6264 // Otherwise, only diagnose if the declaration is in scope.
6265 } else if (!isDeclInScope(PrevDecl, SearchDC, S)) {
6266 // do nothing
6267
6268 // Diagnose implicit declarations introduced by elaborated types.
6269 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
6270 unsigned Kind = 0;
6271 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
6272 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 2;
6273 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
6274 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
6275 Invalid = true;
6276
6277 // Otherwise it's a declaration. Call out a particularly common
6278 // case here.
6279 } else if (isa<TypedefDecl>(PrevDecl)) {
6280 Diag(NameLoc, diag::err_tag_definition_of_typedef)
6281 << Name
6282 << cast<TypedefDecl>(PrevDecl)->getUnderlyingType();
6283 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
6284 Invalid = true;
6285
6286 // Otherwise, diagnose.
6287 } else {
6288 // The tag name clashes with something else in the target scope,
6289 // issue an error and recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00006290 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00006291 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00006292 Name = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00006293 Invalid = true;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00006294 }
John McCall0d6b1642010-04-23 18:46:30 +00006295
6296 // The existing declaration isn't relevant to us; we're in a
6297 // new scope, so clear out the previous declaration.
6298 Previous.clear();
Reid Spencer5f016e22007-07-11 17:01:13 +00006299 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006300 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00006301
Chris Lattnercc98eac2008-12-17 07:13:27 +00006302CreateNewDecl:
Mike Stump1eb44332009-09-09 15:08:12 +00006303
John McCall68263142009-11-18 22:49:29 +00006304 TagDecl *PrevDecl = 0;
6305 if (Previous.isSingleResult())
6306 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
6307
Reid Spencer5f016e22007-07-11 17:01:13 +00006308 // If there is an identifier, use the location of the identifier as the
6309 // location of the decl, otherwise use the location of the struct/union
6310 // keyword.
6311 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00006312
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00006313 // Otherwise, create a new declaration. If there is a previous
6314 // declaration of the same entity, the two will be linked via
6315 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +00006316 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00006317
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006318 bool IsForwardReference = false;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00006319 if (Kind == TTK_Enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006320 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
6321 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor741dd9a2009-07-21 14:46:17 +00006322 New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc,
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006323 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +00006324 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Reid Spencer5f016e22007-07-11 17:01:13 +00006325 // If this is an undefined enum, warn.
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +00006326 if (TUK != TUK_Definition && !Invalid) {
6327 TagDecl *Def;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006328 if (getLangOptions().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) {
6329 // C++0x: 7.2p2: opaque-enum-declaration.
6330 // Conflicts are diagnosed above. Do nothing.
6331 }
6332 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +00006333 Diag(Loc, diag::ext_forward_ref_enum_def)
6334 << New;
6335 Diag(Def->getLocation(), diag::note_previous_definition);
6336 } else {
Francois Pichet8dc3abc2010-09-12 05:06:55 +00006337 unsigned DiagID = diag::ext_forward_ref_enum;
6338 if (getLangOptions().Microsoft)
6339 DiagID = diag::ext_ms_forward_ref_enum;
6340 else if (getLangOptions().CPlusPlus)
6341 DiagID = diag::err_forward_ref_enum;
6342 Diag(Loc, DiagID);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006343
6344 // If this is a forward-declared reference to an enumeration, make a
6345 // note of it; we won't actually be introducing the declaration into
6346 // the declaration context.
6347 if (TUK == TUK_Reference)
6348 IsForwardReference = true;
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +00006349 }
Douglas Gregor80711a22009-03-06 18:34:03 +00006350 }
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006351
6352 if (EnumUnderlying) {
6353 EnumDecl *ED = cast<EnumDecl>(New);
6354 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
6355 ED->setIntegerTypeSourceInfo(TI);
6356 else
6357 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
6358 ED->setPromotionType(ED->getIntegerType());
6359 }
6360
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00006361 } else {
6362 // struct/union/class
6363
Reid Spencer5f016e22007-07-11 17:01:13 +00006364 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
6365 // struct X { int A; } D; D should chain to X.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006366 if (getLangOptions().CPlusPlus) {
Ted Kremenek2b345eb2008-09-05 17:39:33 +00006367 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor741dd9a2009-07-21 14:46:17 +00006368 New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00006369 cast_or_null<CXXRecordDecl>(PrevDecl));
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006370
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006371 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006372 StdBadAlloc = cast<CXXRecordDecl>(New);
6373 } else
Douglas Gregor741dd9a2009-07-21 14:46:17 +00006374 New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00006375 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00006376 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00006377
John McCallb6217662010-03-15 10:12:16 +00006378 // Maybe add qualifier info.
6379 if (SS.isNotEmpty()) {
Fariborz Jahanian4fb20532010-05-14 21:35:02 +00006380 if (SS.isSet()) {
6381 NestedNameSpecifier *NNS
6382 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6383 New->setQualifierInfo(NNS, SS.getRange());
Abramo Bagnara9b934882010-06-12 08:15:14 +00006384 if (NumMatchedTemplateParamLists > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00006385 New->setTemplateParameterListsInfo(Context,
6386 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00006387 (TemplateParameterList**) TemplateParameterLists.release());
6388 }
Fariborz Jahanian4fb20532010-05-14 21:35:02 +00006389 }
6390 else
6391 Invalid = true;
John McCallb6217662010-03-15 10:12:16 +00006392 }
6393
Daniel Dunbar9f21f892010-05-27 01:53:40 +00006394 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
6395 // Add alignment attributes if necessary; these attributes are checked when
6396 // the ASTContext lays out the structure.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00006397 //
6398 // It is important for implementing the correct semantics that this
6399 // happen here (in act on tag decl). The #pragma pack stack is
6400 // maintained as a result of parser callbacks which can occur at
6401 // many points during the parsing of a struct declaration (because
6402 // the #pragma tokens are effectively skipped over during the
6403 // parsing of the struct).
Daniel Dunbar9f21f892010-05-27 01:53:40 +00006404 AddAlignmentAttributesForRecord(RD);
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00006405 }
6406
Douglas Gregorf6b11852009-10-08 15:14:33 +00006407 // If this is a specialization of a member class (of a class template),
6408 // check the specialization.
John McCall68263142009-11-18 22:49:29 +00006409 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorf6b11852009-10-08 15:14:33 +00006410 Invalid = true;
Daniel Dunbar9f21f892010-05-27 01:53:40 +00006411
Douglas Gregor0b7a1582009-01-17 00:42:38 +00006412 if (Invalid)
6413 New->setInvalidDecl();
6414
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00006415 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006416 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00006417
Douglas Gregor0b7a1582009-01-17 00:42:38 +00006418 // If we're declaring or defining a tag in function prototype scope
6419 // in C, note that this type can only be used within the function.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00006420 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
6421 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
6422
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00006423 // Set the lexical context. If the tag has a C++ scope specifier, the
6424 // lexical context will be different from the semantic context.
Douglas Gregor1931b442009-02-03 00:34:39 +00006425 New->setLexicalDeclContext(CurContext);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00006426
John McCall02cace72009-08-28 07:59:38 +00006427 // Mark this as a friend decl if applicable.
6428 if (TUK == TUK_Friend)
John McCall68263142009-11-18 22:49:29 +00006429 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty());
John McCall02cace72009-08-28 07:59:38 +00006430
Anders Carlsson0cf88302009-03-26 01:19:02 +00006431 // Set the access specifier.
John McCall9c86b512010-03-25 21:28:06 +00006432 if (!Invalid && SearchDC->isRecord())
Douglas Gregord0c87372009-05-27 17:30:49 +00006433 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor06c0fec2009-03-25 22:00:53 +00006434
John McCall0f434ec2009-07-31 02:45:11 +00006435 if (TUK == TUK_Definition)
Douglas Gregor0b7a1582009-01-17 00:42:38 +00006436 New->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00006437
Reid Spencer5f016e22007-07-11 17:01:13 +00006438 // If this has an identifier, add it to the scope stack.
John McCalld7eff682009-09-02 00:55:30 +00006439 if (TUK == TUK_Friend) {
John McCall82b9fb82009-09-02 19:32:14 +00006440 // We might be replacing an existing declaration in the lookup tables;
6441 // if so, borrow its access specifier.
6442 if (PrevDecl)
6443 New->setAccess(PrevDecl->getAccess());
6444
Sebastian Redl7a126a42010-08-31 00:36:30 +00006445 DeclContext *DC = New->getDeclContext()->getRedeclContext();
John McCall9c86b512010-03-25 21:28:06 +00006446 DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
6447 if (Name) // can be null along some error paths
John McCalld7eff682009-09-02 00:55:30 +00006448 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
6449 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCalld7eff682009-09-02 00:55:30 +00006450 } else if (Name) {
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00006451 S = getNonFieldDeclScope(S);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006452 PushOnScopeChains(New, S, !IsForwardReference);
6453 if (IsForwardReference)
6454 SearchDC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
6455
Douglas Gregor4920f1f2009-01-12 22:49:06 +00006456 } else {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006457 CurContext->addDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00006458 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00006459
Douglas Gregorc29f77b2009-07-07 16:35:42 +00006460 // If this is the C FILE type, notify the AST context.
6461 if (IdentifierInfo *II = New->getIdentifier())
6462 if (!New->isInvalidDecl() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006463 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregorc29f77b2009-07-07 16:35:42 +00006464 II->isStr("FILE"))
6465 Context.setFILEDecl(New);
Mike Stump1eb44332009-09-09 15:08:12 +00006466
Douglas Gregor402abb52009-05-28 23:31:59 +00006467 OwnedDecl = true;
John McCalld226f652010-08-21 09:40:31 +00006468 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +00006469}
6470
John McCalld226f652010-08-21 09:40:31 +00006471void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +00006472 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +00006473 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor48c89f42010-04-24 16:38:41 +00006474
Douglas Gregor72de6672009-01-08 20:45:30 +00006475 // Enter the tag context.
6476 PushDeclContext(S, Tag);
John McCallf9368152009-12-20 07:58:13 +00006477}
Douglas Gregor72de6672009-01-08 20:45:30 +00006478
John McCalld226f652010-08-21 09:40:31 +00006479void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlssondfc2f102011-01-22 17:51:53 +00006480 ClassVirtSpecifiers &CVS,
John McCallf9368152009-12-20 07:58:13 +00006481 SourceLocation LBraceLoc) {
6482 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +00006483 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor72de6672009-01-08 20:45:30 +00006484
John McCallf9368152009-12-20 07:58:13 +00006485 FieldCollector->StartClass();
6486
6487 if (!Record->getIdentifier())
6488 return;
6489
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00006490 if (CVS.isFinalSpecified())
6491 Record->addAttr(new (Context) FinalAttr(CVS.getFinalLoc(), Context));
6492 if (CVS.isExplicitSpecified())
6493 Record->addAttr(new (Context) ExplicitAttr(CVS.getExplicitLoc(), Context));
Anders Carlssondfc2f102011-01-22 17:51:53 +00006494
John McCallf9368152009-12-20 07:58:13 +00006495 // C++ [class]p2:
6496 // [...] The class-name is also inserted into the scope of the
6497 // class itself; this is known as the injected-class-name. For
6498 // purposes of access checking, the injected-class-name is treated
6499 // as if it were a public member name.
6500 CXXRecordDecl *InjectedClassName
6501 = CXXRecordDecl::Create(Context, Record->getTagKind(),
6502 CurContext, Record->getLocation(),
6503 Record->getIdentifier(),
6504 Record->getTagKeywordLoc(),
Argyrios Kyrtzidis3b8f6102010-10-14 20:14:21 +00006505 /*PrevDecl=*/0,
6506 /*DelayTypeCreation=*/true);
6507 Context.getTypeDeclType(InjectedClassName, Record);
John McCallf9368152009-12-20 07:58:13 +00006508 InjectedClassName->setImplicit();
6509 InjectedClassName->setAccess(AS_public);
6510 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
6511 InjectedClassName->setDescribedClassTemplate(Template);
6512 PushOnScopeChains(InjectedClassName, S);
6513 assert(InjectedClassName->isInjectedClassName() &&
6514 "Broken injected-class-name");
Douglas Gregor72de6672009-01-08 20:45:30 +00006515}
6516
John McCalld226f652010-08-21 09:40:31 +00006517void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +00006518 SourceLocation RBraceLoc) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +00006519 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +00006520 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +00006521 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor72de6672009-01-08 20:45:30 +00006522
6523 if (isa<CXXRecordDecl>(Tag))
6524 FieldCollector->FinishClass();
6525
6526 // Exit this scope of this tag's definition.
6527 PopDeclContext();
Douglas Gregoradda8462010-01-06 17:00:51 +00006528
Douglas Gregor72de6672009-01-08 20:45:30 +00006529 // Notify the consumer that we've defined a tag.
6530 Consumer.HandleTagDeclDefinition(Tag);
6531}
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00006532
John McCalld226f652010-08-21 09:40:31 +00006533void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCalldb7bb4a2010-03-17 00:38:33 +00006534 AdjustDeclIfTemplate(TagD);
John McCalld226f652010-08-21 09:40:31 +00006535 TagDecl *Tag = cast<TagDecl>(TagD);
John McCalldb7bb4a2010-03-17 00:38:33 +00006536 Tag->setInvalidDecl();
6537
John McCalla8cab012010-03-17 19:25:57 +00006538 // We're undoing ActOnTagStartDefinition here, not
6539 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
6540 // the FieldCollector.
John McCalldb7bb4a2010-03-17 00:38:33 +00006541
6542 PopDeclContext();
6543}
6544
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00006545// Note that FieldName may be null for anonymous bitfields.
Mike Stump1eb44332009-09-09 15:08:12 +00006546bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Eli Friedman1d954f62009-08-15 21:55:26 +00006547 QualType FieldTy, const Expr *BitWidth,
6548 bool *ZeroWidth) {
6549 // Default to true; that shouldn't confuse checks for emptiness
6550 if (ZeroWidth)
6551 *ZeroWidth = true;
6552
Chris Lattner24793662009-03-05 22:45:59 +00006553 // C99 6.7.2.1p4 - verify the field type.
Chris Lattner8b963ef2009-03-05 23:01:03 +00006554 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006555 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner24793662009-03-05 22:45:59 +00006556 // Handle incomplete types with specific error.
Douglas Gregora03aca82009-03-10 21:58:27 +00006557 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
6558 return true;
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00006559 if (FieldName)
6560 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
6561 << FieldName << FieldTy << BitWidth->getSourceRange();
6562 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
6563 << FieldTy << BitWidth->getSourceRange();
Douglas Gregore1862692010-12-15 23:18:36 +00006564 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
6565 UPPC_BitFieldWidth))
6566 return true;
Douglas Gregor3cf538d2009-03-11 18:59:21 +00006567
6568 // If the bit-width is type- or value-dependent, don't try to check
6569 // it now.
6570 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
6571 return false;
6572
Anders Carlsson9f1e5722008-12-06 20:33:04 +00006573 llvm::APSInt Value;
6574 if (VerifyIntegerConstantExpression(BitWidth, &Value))
6575 return true;
6576
Eli Friedman1d954f62009-08-15 21:55:26 +00006577 if (Value != 0 && ZeroWidth)
6578 *ZeroWidth = false;
6579
Chris Lattnercd087072008-12-12 04:56:04 +00006580 // Zero-width bitfield is ok for anonymous field.
6581 if (Value == 0 && FieldName)
6582 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00006583
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00006584 if (Value.isSigned() && Value.isNegative()) {
6585 if (FieldName)
Mike Stump1eb44332009-09-09 15:08:12 +00006586 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00006587 << FieldName << Value.toString(10);
6588 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
6589 << Value.toString(10);
6590 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00006591
Douglas Gregor3cf538d2009-03-11 18:59:21 +00006592 if (!FieldTy->isDependentType()) {
6593 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00006594 if (Value.getZExtValue() > TypeSize) {
Anders Carlsson72468ec2010-04-16 15:16:32 +00006595 if (!getLangOptions().CPlusPlus) {
6596 if (FieldName)
6597 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
6598 << FieldName << (unsigned)Value.getZExtValue()
6599 << (unsigned)TypeSize;
6600
6601 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
6602 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
6603 }
6604
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00006605 if (FieldName)
Anders Carlsson72468ec2010-04-16 15:16:32 +00006606 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
6607 << FieldName << (unsigned)Value.getZExtValue()
6608 << (unsigned)TypeSize;
6609 else
6610 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
6611 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00006612 }
Douglas Gregor3cf538d2009-03-11 18:59:21 +00006613 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00006614
6615 return false;
6616}
6617
Steve Naroff08d92e42007-09-15 18:49:24 +00006618/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00006619/// to create a FieldDecl object for it.
John McCalld226f652010-08-21 09:40:31 +00006620Decl *Sema::ActOnField(Scope *S, Decl *TagD,
Mike Stump1eb44332009-09-09 15:08:12 +00006621 SourceLocation DeclStart,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006622 Declarator &D, ExprTy *BitfieldWidth) {
John McCalld226f652010-08-21 09:40:31 +00006623 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattnerb28317a2009-03-28 19:18:32 +00006624 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
6625 AS_public);
John McCalld226f652010-08-21 09:40:31 +00006626 return Res;
Chris Lattner24793662009-03-05 22:45:59 +00006627}
6628
6629/// HandleField - Analyze a field of a C struct or a C++ data member.
6630///
6631FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
6632 SourceLocation DeclStart,
Douglas Gregor4dd55f52009-03-11 20:50:30 +00006633 Declarator &D, Expr *BitWidth,
6634 AccessSpecifier AS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006635 IdentifierInfo *II = D.getIdentifier();
Reid Spencer5f016e22007-07-11 17:01:13 +00006636 SourceLocation Loc = DeclStart;
6637 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00006638
John McCallbf1a0282010-06-04 23:28:52 +00006639 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6640 QualType T = TInfo->getType();
Douglas Gregore1862692010-12-15 23:18:36 +00006641 if (getLangOptions().CPlusPlus) {
Douglas Gregor3cf538d2009-03-11 18:59:21 +00006642 CheckExtraCXXDefaultArguments(D);
Douglas Gregor021c3b32009-03-11 23:00:04 +00006643
Douglas Gregore1862692010-12-15 23:18:36 +00006644 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6645 UPPC_DataMemberType)) {
6646 D.setInvalidType();
6647 T = Context.IntTy;
6648 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
6649 }
6650 }
6651
Eli Friedman85a53192009-04-07 19:37:57 +00006652 DiagnoseFunctionSpecifiers(D);
6653
Eli Friedman63054b32009-04-19 20:27:55 +00006654 if (D.getDeclSpec().isThreadSpecified())
6655 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
Douglas Gregor7f6ff022010-08-30 14:32:14 +00006656
6657 // Check to see if this name was declared as a member previously
6658 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
6659 LookupName(Previous, S);
6660 assert((Previous.empty() || Previous.isOverloadedResult() ||
6661 Previous.isSingleResult())
6662 && "Lookup of member name should be either overloaded, single or null");
Eli Friedman63054b32009-04-19 20:27:55 +00006663
Douglas Gregor7f6ff022010-08-30 14:32:14 +00006664 // If the name is overloaded then get any declaration else get the single result
6665 NamedDecl *PrevDecl = Previous.isOverloadedResult() ?
6666 Previous.getRepresentativeDecl() : Previous.getAsSingle<NamedDecl>();
Douglas Gregorc19ee3e2009-06-17 23:37:01 +00006667
6668 if (PrevDecl && PrevDecl->isTemplateParameter()) {
6669 // Maybe we will complain about the shadowed template parameter.
6670 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
6671 // Just pretend that we didn't see the previous declaration.
6672 PrevDecl = 0;
6673 }
6674
Douglas Gregor3cf538d2009-03-11 18:59:21 +00006675 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
6676 PrevDecl = 0;
6677
Steve Naroffea218b82009-07-14 14:58:18 +00006678 bool Mutable
6679 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
6680 SourceLocation TSSL = D.getSourceRange().getBegin();
6681 FieldDecl *NewFD
John McCalla93c9342009-12-07 02:54:59 +00006682 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, TSSL,
Steve Naroffea218b82009-07-14 14:58:18 +00006683 AS, PrevDecl, &D);
Rafael Espindola01620702010-03-21 22:56:43 +00006684
6685 if (NewFD->isInvalidDecl())
6686 Record->setInvalidDecl();
6687
Douglas Gregor3cf538d2009-03-11 18:59:21 +00006688 if (NewFD->isInvalidDecl() && PrevDecl) {
6689 // Don't introduce NewFD into scope; there's already something
6690 // with the same name in the same scope.
6691 } else if (II) {
6692 PushOnScopeChains(NewFD, S);
6693 } else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006694 Record->addDecl(NewFD);
Douglas Gregor3cf538d2009-03-11 18:59:21 +00006695
6696 return NewFD;
6697}
6698
6699/// \brief Build a new FieldDecl and check its well-formedness.
6700///
6701/// This routine builds a new FieldDecl given the fields name, type,
6702/// record, etc. \p PrevDecl should refer to any previous declaration
6703/// with the same name and in the same scope as the field to be
6704/// created.
6705///
6706/// \returns a new FieldDecl.
6707///
Mike Stump1eb44332009-09-09 15:08:12 +00006708/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00006709FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCalla93c9342009-12-07 02:54:59 +00006710 TypeSourceInfo *TInfo,
Douglas Gregor3cf538d2009-03-11 18:59:21 +00006711 RecordDecl *Record, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00006712 bool Mutable, Expr *BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +00006713 SourceLocation TSSL,
Douglas Gregor4dd55f52009-03-11 20:50:30 +00006714 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor3cf538d2009-03-11 18:59:21 +00006715 Declarator *D) {
6716 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Naroff5912a352007-08-28 20:14:24 +00006717 bool InvalidDecl = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +00006718 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redl64b45f72009-01-05 20:52:13 +00006719
Douglas Gregor3cf538d2009-03-11 18:59:21 +00006720 // If we receive a broken type, recover by assuming 'int' and
6721 // marking this declaration as invalid.
6722 if (T.isNull()) {
6723 InvalidDecl = true;
6724 T = Context.IntTy;
6725 }
6726
Eli Friedman721e77d2009-12-07 00:22:08 +00006727 QualType EltTy = Context.getBaseElementType(T);
6728 if (!EltTy->isDependentType() &&
John McCall2d7d2d92010-08-16 23:42:35 +00006729 RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
6730 // Fields of incomplete type force their record to be invalid.
6731 Record->setInvalidDecl();
Eli Friedman721e77d2009-12-07 00:22:08 +00006732 InvalidDecl = true;
John McCall2d7d2d92010-08-16 23:42:35 +00006733 }
Eli Friedman721e77d2009-12-07 00:22:08 +00006734
Reid Spencer5f016e22007-07-11 17:01:13 +00006735 // C99 6.7.2.1p8: A member of a structure or union may have any type other
6736 // than a variably modified type.
Eli Friedman721e77d2009-12-07 00:22:08 +00006737 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedman1ca48132009-02-21 00:44:51 +00006738 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +00006739 llvm::APSInt Oversized;
Eli Friedman1ca48132009-02-21 00:44:51 +00006740 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
Douglas Gregor2767ce22010-08-18 00:39:00 +00006741 SizeIsNegative,
6742 Oversized);
Eli Friedman1ca48132009-02-21 00:44:51 +00006743 if (!FixedTy.isNull()) {
6744 Diag(Loc, diag::warn_illegal_constant_array_size);
6745 T = FixedTy;
6746 } else {
6747 if (SizeIsNegative)
6748 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregor2767ce22010-08-18 00:39:00 +00006749 else if (Oversized.getBoolValue())
6750 Diag(Loc, diag::err_array_too_large)
6751 << Oversized.toString(10);
Eli Friedman1ca48132009-02-21 00:44:51 +00006752 else
6753 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedman1ca48132009-02-21 00:44:51 +00006754 InvalidDecl = true;
6755 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006756 }
Mike Stump1eb44332009-09-09 15:08:12 +00006757
Anders Carlsson4681ebd2009-03-22 20:18:17 +00006758 // Fields can not have abstract class types
Eli Friedman721e77d2009-12-07 00:22:08 +00006759 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
6760 diag::err_abstract_type_in_decl,
6761 AbstractFieldType))
Anders Carlsson4681ebd2009-03-22 20:18:17 +00006762 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +00006763
Eli Friedman1d954f62009-08-15 21:55:26 +00006764 bool ZeroWidth = false;
Douglas Gregor3cf538d2009-03-11 18:59:21 +00006765 // If this is declared as a bit-field, check the bit-field.
Eli Friedman721e77d2009-12-07 00:22:08 +00006766 if (!InvalidDecl && BitWidth &&
6767 VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
Douglas Gregor3cf538d2009-03-11 18:59:21 +00006768 InvalidDecl = true;
Douglas Gregor3cf538d2009-03-11 18:59:21 +00006769 BitWidth = 0;
Eli Friedman1d954f62009-08-15 21:55:26 +00006770 ZeroWidth = false;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00006771 }
Mike Stump1eb44332009-09-09 15:08:12 +00006772
John McCall4bde1e12010-06-04 08:34:12 +00006773 // Check that 'mutable' is consistent with the type of the declaration.
6774 if (!InvalidDecl && Mutable) {
6775 unsigned DiagID = 0;
6776 if (T->isReferenceType())
6777 DiagID = diag::err_mutable_reference;
6778 else if (T.isConstQualified())
6779 DiagID = diag::err_mutable_const;
6780
6781 if (DiagID) {
6782 SourceLocation ErrLoc = Loc;
6783 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
6784 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
6785 Diag(ErrLoc, DiagID);
6786 Mutable = false;
6787 InvalidDecl = true;
6788 }
6789 }
6790
John McCalla93c9342009-12-07 02:54:59 +00006791 FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, TInfo,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00006792 BitWidth, Mutable);
Chris Lattnereaaebc72009-04-25 08:06:05 +00006793 if (InvalidDecl)
6794 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00006795
Douglas Gregor3cf538d2009-03-11 18:59:21 +00006796 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
6797 Diag(Loc, diag::err_duplicate_member) << II;
6798 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
6799 NewFD->setInvalidDecl();
Douglas Gregor72de6672009-01-08 20:45:30 +00006800 }
6801
John McCall86ff3082010-02-04 22:26:26 +00006802 if (!InvalidDecl && getLangOptions().CPlusPlus) {
Anders Carlssondfdfc582010-11-07 19:13:55 +00006803 if (Record->isUnion()) {
6804 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
6805 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
6806 if (RDecl->getDefinition()) {
6807 // C++ [class.union]p1: An object of a class with a non-trivial
6808 // constructor, a non-trivial copy constructor, a non-trivial
6809 // destructor, or a non-trivial copy assignment operator
6810 // cannot be a member of a union, nor can an array of such
6811 // objects.
6812 // TODO: C++0x alters this restriction significantly.
6813 if (CheckNontrivialField(NewFD))
6814 NewFD->setInvalidDecl();
6815 }
6816 }
6817
6818 // C++ [class.union]p1: If a union contains a member of reference type,
6819 // the program is ill-formed.
6820 if (EltTy->isReferenceType()) {
6821 Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
6822 << NewFD->getDeclName() << EltTy;
6823 NewFD->setInvalidDecl();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006824 }
6825 }
6826 }
6827
Douglas Gregor3cf538d2009-03-11 18:59:21 +00006828 // FIXME: We need to pass in the attributes given an AST
6829 // representation, not a parser representation.
6830 if (D)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006831 // FIXME: What to pass instead of TUScope?
6832 ProcessDeclAttributes(TUScope, NewFD, *D);
Douglas Gregor3cf538d2009-03-11 18:59:21 +00006833
Fariborz Jahanianf6123ca2009-02-19 00:22:47 +00006834 if (T.isObjCGCWeak())
Fariborz Jahanianed7e9ef2009-02-18 18:14:41 +00006835 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlssonad148062008-02-16 00:29:18 +00006836
Douglas Gregor4dd55f52009-03-11 20:50:30 +00006837 NewFD->setAccess(AS);
Steve Naroff5912a352007-08-28 20:14:24 +00006838 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00006839}
6840
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +00006841bool Sema::CheckNontrivialField(FieldDecl *FD) {
6842 assert(FD);
6843 assert(getLangOptions().CPlusPlus && "valid check only for C++");
6844
6845 if (FD->isInvalidDecl())
6846 return true;
6847
6848 QualType EltTy = Context.getBaseElementType(FD->getType());
6849 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
6850 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
6851 if (RDecl->getDefinition()) {
6852 // We check for copy constructors before constructors
6853 // because otherwise we'll never get complaints about
6854 // copy constructors.
6855
6856 CXXSpecialMember member = CXXInvalid;
6857 if (!RDecl->hasTrivialCopyConstructor())
6858 member = CXXCopyConstructor;
6859 else if (!RDecl->hasTrivialConstructor())
6860 member = CXXConstructor;
6861 else if (!RDecl->hasTrivialCopyAssignment())
6862 member = CXXCopyAssignment;
6863 else if (!RDecl->hasTrivialDestructor())
6864 member = CXXDestructor;
6865
6866 if (member != CXXInvalid) {
6867 Diag(FD->getLocation(), diag::err_illegal_union_or_anon_struct_member)
6868 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
6869 DiagnoseNontrivial(RT, member);
6870 return true;
6871 }
6872 }
6873 }
6874
6875 return false;
6876}
6877
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006878/// DiagnoseNontrivial - Given that a class has a non-trivial
6879/// special member, figure out why.
6880void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
6881 QualType QT(T, 0U);
6882 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
6883
6884 // Check whether the member was user-declared.
6885 switch (member) {
Douglas Gregor66dd9392010-04-22 14:36:26 +00006886 case CXXInvalid:
6887 break;
6888
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00006889 case CXXConstructor:
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006890 if (RD->hasUserDeclaredConstructor()) {
6891 typedef CXXRecordDecl::ctor_iterator ctor_iter;
Sebastian Redl38fd4d02009-10-25 22:31:45 +00006892 for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
6893 const FunctionDecl *body = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00006894 ci->hasBody(body);
Anders Carlsson10dc0f82010-04-20 23:32:58 +00006895 if (!body || !cast<CXXConstructorDecl>(body)->isImplicitlyDefined()) {
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006896 SourceLocation CtorLoc = ci->getLocation();
6897 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
6898 return;
6899 }
Sebastian Redl38fd4d02009-10-25 22:31:45 +00006900 }
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006901
6902 assert(0 && "found no user-declared constructors");
6903 return;
6904 }
6905 break;
6906
6907 case CXXCopyConstructor:
6908 if (RD->hasUserDeclaredCopyConstructor()) {
6909 SourceLocation CtorLoc =
6910 RD->getCopyConstructor(Context, 0)->getLocation();
6911 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
6912 return;
6913 }
6914 break;
6915
6916 case CXXCopyAssignment:
6917 if (RD->hasUserDeclaredCopyAssignment()) {
6918 // FIXME: this should use the location of the copy
6919 // assignment, not the type.
6920 SourceLocation TyLoc = RD->getSourceRange().getBegin();
6921 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
6922 return;
6923 }
6924 break;
6925
6926 case CXXDestructor:
6927 if (RD->hasUserDeclaredDestructor()) {
Douglas Gregordb89f282010-07-01 22:47:18 +00006928 SourceLocation DtorLoc = LookupDestructor(RD)->getLocation();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006929 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
6930 return;
6931 }
6932 break;
6933 }
6934
6935 typedef CXXRecordDecl::base_class_iterator base_iter;
6936
6937 // Virtual bases and members inhibit trivial copying/construction,
6938 // but not trivial destruction.
6939 if (member != CXXDestructor) {
6940 // Check for virtual bases. vbases includes indirect virtual bases,
6941 // so we just iterate through the direct bases.
6942 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
6943 if (bi->isVirtual()) {
6944 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
6945 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
6946 return;
6947 }
6948
6949 // Check for virtual methods.
6950 typedef CXXRecordDecl::method_iterator meth_iter;
6951 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
6952 ++mi) {
6953 if (mi->isVirtual()) {
6954 SourceLocation MLoc = mi->getSourceRange().getBegin();
6955 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
6956 return;
6957 }
6958 }
6959 }
Mike Stump1eb44332009-09-09 15:08:12 +00006960
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006961 bool (CXXRecordDecl::*hasTrivial)() const;
6962 switch (member) {
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00006963 case CXXConstructor:
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006964 hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break;
6965 case CXXCopyConstructor:
6966 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
6967 case CXXCopyAssignment:
6968 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
6969 case CXXDestructor:
6970 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
6971 default:
6972 assert(0 && "unexpected special member"); return;
6973 }
6974
6975 // Check for nontrivial bases (and recurse).
6976 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
Ted Kremenek6217b802009-07-29 21:53:49 +00006977 const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
Sebastian Redl9994a342009-10-25 17:03:50 +00006978 assert(BaseRT && "Don't know how to handle dependent bases");
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006979 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
6980 if (!(BaseRecTy->*hasTrivial)()) {
6981 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
6982 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
6983 DiagnoseNontrivial(BaseRT, member);
6984 return;
6985 }
6986 }
Mike Stump1eb44332009-09-09 15:08:12 +00006987
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006988 // Check for nontrivial members (and recurse).
6989 typedef RecordDecl::field_iterator field_iter;
6990 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
6991 ++fi) {
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00006992 QualType EltTy = Context.getBaseElementType((*fi)->getType());
Ted Kremenek6217b802009-07-29 21:53:49 +00006993 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006994 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
6995
6996 if (!(EltRD->*hasTrivial)()) {
6997 SourceLocation FLoc = (*fi)->getLocation();
6998 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
6999 DiagnoseNontrivial(EltRT, member);
7000 return;
7001 }
7002 }
7003 }
7004
7005 assert(0 && "found no explanation for non-trivial member");
7006}
7007
Mike Stump1eb44332009-09-09 15:08:12 +00007008/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanian89204a12007-10-01 16:53:59 +00007009/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00007010static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00007011TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00007012 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00007013 default: assert(0 && "Unknown visitibility kind");
7014 case tok::objc_private: return ObjCIvarDecl::Private;
7015 case tok::objc_public: return ObjCIvarDecl::Public;
7016 case tok::objc_protected: return ObjCIvarDecl::Protected;
7017 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00007018 }
7019}
7020
Mike Stump1eb44332009-09-09 15:08:12 +00007021/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00007022/// in order to create an IvarDecl object for it.
John McCalld226f652010-08-21 09:40:31 +00007023Decl *Sema::ActOnIvar(Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00007024 SourceLocation DeclStart,
John McCalld226f652010-08-21 09:40:31 +00007025 Decl *IntfDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007026 Declarator &D, ExprTy *BitfieldWidth,
7027 tok::ObjCKeywordKind Visibility) {
Mike Stump1eb44332009-09-09 15:08:12 +00007028
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00007029 IdentifierInfo *II = D.getIdentifier();
7030 Expr *BitWidth = (Expr*)BitfieldWidth;
7031 SourceLocation Loc = DeclStart;
7032 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00007033
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00007034 // FIXME: Unnamed fields can be handled in various different ways, for
7035 // example, unnamed unions inject all members into the struct namespace!
Mike Stump1eb44332009-09-09 15:08:12 +00007036
John McCallbf1a0282010-06-04 23:28:52 +00007037 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
7038 QualType T = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00007039
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00007040 if (BitWidth) {
Steve Naroff63359c82009-02-20 17:57:11 +00007041 // 6.7.2.1p3, 6.7.2.1p4
Chris Lattner24793662009-03-05 22:45:59 +00007042 if (VerifyBitField(Loc, II, T, BitWidth)) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00007043 D.setInvalidType();
Chris Lattner24793662009-03-05 22:45:59 +00007044 BitWidth = 0;
7045 }
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00007046 } else {
7047 // Not a bitfield.
Mike Stump1eb44332009-09-09 15:08:12 +00007048
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00007049 // validate II.
Mike Stump1eb44332009-09-09 15:08:12 +00007050
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00007051 }
Fariborz Jahanian0b7bc8e2010-04-26 22:07:03 +00007052 if (T->isReferenceType()) {
7053 Diag(Loc, diag::err_ivar_reference_type);
7054 D.setInvalidType();
7055 }
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00007056 // C99 6.7.2.1p8: A member of a structure or union may have any type other
7057 // than a variably modified type.
Fariborz Jahanian0b7bc8e2010-04-26 22:07:03 +00007058 else if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00007059 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnereaaebc72009-04-25 08:06:05 +00007060 D.setInvalidType();
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00007061 }
Mike Stump1eb44332009-09-09 15:08:12 +00007062
Ted Kremenekb8db21d2008-07-23 18:04:17 +00007063 // Get the visibility (access control) for this ivar.
Mike Stump1eb44332009-09-09 15:08:12 +00007064 ObjCIvarDecl::AccessControl ac =
Ted Kremenekb8db21d2008-07-23 18:04:17 +00007065 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
7066 : ObjCIvarDecl::None;
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00007067 // Must set ivar's DeclContext to its enclosing interface.
John McCalld226f652010-08-21 09:40:31 +00007068 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(IntfDecl);
Daniel Dunbara19331f2010-04-02 18:29:09 +00007069 ObjCContainerDecl *EnclosingContext;
Mike Stump1eb44332009-09-09 15:08:12 +00007070 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00007071 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Fariborz Jahanian000835d2010-08-23 18:51:39 +00007072 if (!LangOpts.ObjCNonFragileABI2) {
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00007073 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanian000835d2010-08-23 18:51:39 +00007074 EnclosingContext = IMPDecl->getClassInterface();
7075 assert(EnclosingContext && "Implementation has no class interface!");
7076 }
7077 else
7078 EnclosingContext = EnclosingDecl;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +00007079 } else {
7080 if (ObjCCategoryDecl *CDecl =
7081 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
7082 if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) {
7083 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCalld226f652010-08-21 09:40:31 +00007084 return 0;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +00007085 }
7086 }
Daniel Dunbara19331f2010-04-02 18:29:09 +00007087 EnclosingContext = EnclosingDecl;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +00007088 }
Mike Stump1eb44332009-09-09 15:08:12 +00007089
Ted Kremenekb8db21d2008-07-23 18:04:17 +00007090 // Construct the decl.
Mike Stump1eb44332009-09-09 15:08:12 +00007091 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00007092 EnclosingContext, Loc, II, T,
John McCalla93c9342009-12-07 02:54:59 +00007093 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump1eb44332009-09-09 15:08:12 +00007094
Douglas Gregor72de6672009-01-08 20:45:30 +00007095 if (II) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00007096 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall7d384dd2009-11-18 07:57:50 +00007097 ForRedeclaration);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00007098 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor72de6672009-01-08 20:45:30 +00007099 && !isa<TagDecl>(PrevDecl)) {
7100 Diag(Loc, diag::err_duplicate_member) << II;
7101 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
7102 NewID->setInvalidDecl();
7103 }
7104 }
7105
Ted Kremenekb8db21d2008-07-23 18:04:17 +00007106 // Process attributes attached to the ivar.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00007107 ProcessDeclAttributes(S, NewID, D);
Mike Stump1eb44332009-09-09 15:08:12 +00007108
Chris Lattnereaaebc72009-04-25 08:06:05 +00007109 if (D.isInvalidType())
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00007110 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00007111
Douglas Gregor72de6672009-01-08 20:45:30 +00007112 if (II) {
7113 // FIXME: When interfaces are DeclContexts, we'll need to add
7114 // these to the interface.
John McCalld226f652010-08-21 09:40:31 +00007115 S->AddDecl(NewID);
Douglas Gregor72de6672009-01-08 20:45:30 +00007116 IdResolver.AddDecl(NewID);
7117 }
7118
John McCalld226f652010-08-21 09:40:31 +00007119 return NewID;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00007120}
7121
Fariborz Jahaniand097be82010-08-23 22:46:52 +00007122/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
7123/// class and class extensions. For every class @interface and class
7124/// extension @interface, if the last ivar is a bitfield of any type,
7125/// then add an implicit `char :0` ivar to the end of that interface.
7126void Sema::ActOnLastBitfield(SourceLocation DeclLoc, Decl *EnclosingDecl,
7127 llvm::SmallVectorImpl<Decl *> &AllIvarDecls) {
7128 if (!LangOpts.ObjCNonFragileABI2 || AllIvarDecls.empty())
7129 return;
7130
7131 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
7132 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
7133
7134 if (!Ivar->isBitField())
7135 return;
7136 uint64_t BitFieldSize =
7137 Ivar->getBitWidth()->EvaluateAsInt(Context).getZExtValue();
7138 if (BitFieldSize == 0)
7139 return;
7140 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl);
7141 if (!ID) {
7142 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
7143 if (!CD->IsClassExtension())
7144 return;
7145 }
7146 // No need to add this to end of @implementation.
7147 else
7148 return;
7149 }
7150 // All conditions are met. Add a new bitfield to the tail end of ivars.
7151 llvm::APInt Zero(Context.getTypeSize(Context.CharTy), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007152 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.CharTy, DeclLoc);
Fariborz Jahaniand097be82010-08-23 22:46:52 +00007153
7154 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(EnclosingDecl),
7155 DeclLoc, 0,
7156 Context.CharTy,
7157 Context.CreateTypeSourceInfo(Context.CharTy),
7158 ObjCIvarDecl::Private, BW,
7159 true);
7160 AllIvarDecls.push_back(Ivar);
7161}
7162
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00007163void Sema::ActOnFields(Scope* S,
John McCalld226f652010-08-21 09:40:31 +00007164 SourceLocation RecLoc, Decl *EnclosingDecl,
7165 Decl **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00007166 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00007167 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00007168 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump1eb44332009-09-09 15:08:12 +00007169
Chris Lattner1829a6d2009-02-23 22:00:08 +00007170 // If the decl this is being inserted into is invalid, then it may be a
7171 // redeclaration or some other bogus case. Don't try to add fields to it.
7172 if (EnclosingDecl->isInvalidDecl()) {
7173 // FIXME: Deallocate fields?
7174 return;
7175 }
7176
Mike Stump1eb44332009-09-09 15:08:12 +00007177
Reid Spencer5f016e22007-07-11 17:01:13 +00007178 // Verify that all the fields are okay.
7179 unsigned NumNamedMembers = 0;
7180 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00007181
Chris Lattner1829a6d2009-02-23 22:00:08 +00007182 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00007183 for (unsigned i = 0; i != NumFields; ++i) {
John McCalld226f652010-08-21 09:40:31 +00007184 FieldDecl *FD = cast<FieldDecl>(Fields[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00007185
Reid Spencer5f016e22007-07-11 17:01:13 +00007186 // Get the type for the field.
John McCallf4c73712011-01-19 06:33:43 +00007187 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00007188
Douglas Gregor72de6672009-01-08 20:45:30 +00007189 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00007190 // Remember all fields written by the user.
7191 RecFields.push_back(FD);
7192 }
Mike Stump1eb44332009-09-09 15:08:12 +00007193
Chris Lattner24793662009-03-05 22:45:59 +00007194 // If the field is already invalid for some reason, don't emit more
7195 // diagnostics about it.
Eli Friedman721e77d2009-12-07 00:22:08 +00007196 if (FD->isInvalidDecl()) {
7197 EnclosingDecl->setInvalidDecl();
Chris Lattner24793662009-03-05 22:45:59 +00007198 continue;
Eli Friedman721e77d2009-12-07 00:22:08 +00007199 }
Mike Stump1eb44332009-09-09 15:08:12 +00007200
Douglas Gregore7450f52009-03-24 19:52:54 +00007201 // C99 6.7.2.1p2:
7202 // A structure or union shall not contain a member with
7203 // incomplete or function type (hence, a structure shall not
7204 // contain an instance of itself, but may contain a pointer to
7205 // an instance of itself), except that the last member of a
7206 // structure with more than one named member may have incomplete
7207 // array type; such a structure (and any union containing,
7208 // possibly recursively, a member that is such a structure)
7209 // shall not be a member of a structure or an element of an
7210 // array.
Chris Lattner02c642e2007-07-31 21:33:24 +00007211 if (FDTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00007212 // Field declared as a function.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00007213 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007214 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00007215 FD->setInvalidDecl();
7216 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007217 continue;
Francois Pichet09246182010-09-15 00:14:08 +00007218 } else if (FDTy->isIncompleteArrayType() && Record &&
7219 ((i == NumFields - 1 && !Record->isUnion()) ||
7220 (getLangOptions().Microsoft &&
7221 (i == NumFields - 1 || Record->isUnion())))) {
Douglas Gregore7450f52009-03-24 19:52:54 +00007222 // Flexible array member.
Francois Pichet09246182010-09-15 00:14:08 +00007223 // Microsoft is more permissive regarding flexible array.
7224 // It will accept flexible array in union and also
Anders Carlsson4d09e842010-10-17 23:36:12 +00007225 // as the sole element of a struct/class.
Francois Pichet09246182010-09-15 00:14:08 +00007226 if (getLangOptions().Microsoft) {
7227 if (Record->isUnion())
7228 Diag(FD->getLocation(), diag::ext_flexible_array_union)
7229 << FD->getDeclName();
7230 else if (NumFields == 1)
7231 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate)
7232 << FD->getDeclName() << Record->getTagKind();
7233 } else if (NumNamedMembers < 1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00007234 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00007235 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00007236 FD->setInvalidDecl();
7237 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00007238 continue;
7239 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00007240 if (!FD->getType()->isDependentType() &&
7241 !Context.getBaseElementType(FD->getType())->isPODType()) {
7242 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
Fariborz Jahanian2c0a5402010-05-26 20:46:24 +00007243 << FD->getDeclName() << FD->getType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00007244 FD->setInvalidDecl();
7245 EnclosingDecl->setInvalidDecl();
7246 continue;
7247 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007248 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00007249 if (Record)
7250 Record->setHasFlexibleArrayMember(true);
Douglas Gregore7450f52009-03-24 19:52:54 +00007251 } else if (!FDTy->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00007252 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregore7450f52009-03-24 19:52:54 +00007253 diag::err_field_incomplete)) {
7254 // Incomplete type
7255 FD->setInvalidDecl();
7256 EnclosingDecl->setInvalidDecl();
7257 continue;
Ted Kremenek6217b802009-07-29 21:53:49 +00007258 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007259 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
7260 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00007261 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007262 Record->setHasFlexibleArrayMember(true);
7263 } else {
7264 // If this is a struct/class and this is not the last element, reject
7265 // it. Note that GCC supports variable sized arrays in the middle of
7266 // structures.
Douglas Gregore4f3e062009-03-06 23:41:27 +00007267 if (i != NumFields-1)
7268 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattner740782a2009-04-25 18:52:45 +00007269 << FD->getDeclName() << FD->getType();
Douglas Gregore4f3e062009-03-06 23:41:27 +00007270 else {
7271 // We support flexible arrays at the end of structs in
7272 // other structs as an extension.
7273 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
7274 << FD->getDeclName();
7275 if (Record)
7276 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00007277 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007278 }
7279 }
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00007280 if (Record && FDTTy->getDecl()->hasObjectMember())
7281 Record->setHasObjectMember(true);
John McCallc12c5bb2010-05-15 11:32:37 +00007282 } else if (FDTy->isObjCObjectType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00007283 /// A field cannot be an Objective-c object
Steve Naroffccef3712009-02-20 22:59:16 +00007284 Diag(FD->getLocation(), diag::err_statically_allocated_object);
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00007285 FD->setInvalidDecl();
7286 EnclosingDecl->setInvalidDecl();
7287 continue;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00007288 } else if (getLangOptions().ObjC1 &&
7289 getLangOptions().getGCMode() != LangOptions::NonGC &&
7290 Record &&
7291 (FD->getType()->isObjCObjectPointerType() ||
7292 FD->getType().isObjCGCStrong()))
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00007293 Record->setHasObjectMember(true);
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007294 else if (Context.getAsArrayType(FD->getType())) {
7295 QualType BaseType = Context.getBaseElementType(FD->getType());
7296 if (Record && BaseType->isRecordType() &&
7297 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
7298 Record->setHasObjectMember(true);
7299 }
Reid Spencer5f016e22007-07-11 17:01:13 +00007300 // Keep track of the number of named members.
Douglas Gregor72de6672009-01-08 20:45:30 +00007301 if (FD->getIdentifier())
Reid Spencer5f016e22007-07-11 17:01:13 +00007302 ++NumNamedMembers;
Reid Spencer5f016e22007-07-11 17:01:13 +00007303 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00007304
Reid Spencer5f016e22007-07-11 17:01:13 +00007305 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00007306 if (Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00007307 bool Completed = false;
7308 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
7309 if (!CXXRecord->isInvalidDecl()) {
7310 // Set access bits correctly on the directly-declared conversions.
7311 UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions();
7312 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end();
7313 I != E; ++I)
7314 Convs->setAccess(I, (*I)->getAccess());
7315
7316 if (!CXXRecord->isDependentType()) {
7317 // Add any implicitly-declared members to this class.
7318 AddImplicitlyDeclaredMembersToClass(CXXRecord);
7319
7320 // If we have virtual base classes, we may end up finding multiple
7321 // final overriders for a given virtual function. Check for this
7322 // problem now.
7323 if (CXXRecord->getNumVBases()) {
7324 CXXFinalOverriderMap FinalOverriders;
7325 CXXRecord->getFinalOverriders(FinalOverriders);
7326
7327 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
7328 MEnd = FinalOverriders.end();
7329 M != MEnd; ++M) {
7330 for (OverridingMethods::iterator SO = M->second.begin(),
7331 SOEnd = M->second.end();
7332 SO != SOEnd; ++SO) {
7333 assert(SO->second.size() > 0 &&
7334 "Virtual function without overridding functions?");
7335 if (SO->second.size() == 1)
7336 continue;
7337
7338 // C++ [class.virtual]p2:
7339 // In a derived class, if a virtual member function of a base
7340 // class subobject has more than one final overrider the
7341 // program is ill-formed.
7342 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
7343 << (NamedDecl *)M->first << Record;
7344 Diag(M->first->getLocation(),
7345 diag::note_overridden_virtual_function);
7346 for (OverridingMethods::overriding_iterator
7347 OM = SO->second.begin(),
7348 OMEnd = SO->second.end();
7349 OM != OMEnd; ++OM)
7350 Diag(OM->Method->getLocation(), diag::note_final_overrider)
7351 << (NamedDecl *)M->first << OM->Method->getParent();
7352
7353 Record->setInvalidDecl();
7354 }
7355 }
7356 CXXRecord->completeDefinition(&FinalOverriders);
7357 Completed = true;
7358 }
7359 }
7360 }
7361 }
7362
7363 if (!Completed)
7364 Record->completeDefinition();
Chris Lattnere1e79852008-02-06 00:51:33 +00007365 } else {
Jay Foadbeaaccd2009-05-21 09:52:38 +00007366 ObjCIvarDecl **ClsFields =
7367 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00007368 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattner38af2de2009-02-20 21:35:13 +00007369 ID->setLocEnd(RBrac);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00007370 // Add ivar's to class's DeclContext.
7371 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
7372 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00007373 ID->addDecl(ClsFields[i]);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00007374 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00007375 // Must enforce the rule that ivars in the base classes may not be
7376 // duplicates.
Fariborz Jahanianf914b972010-02-23 23:41:11 +00007377 if (ID->getSuperClass())
7378 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump1eb44332009-09-09 15:08:12 +00007379 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattner1829a6d2009-02-23 22:00:08 +00007380 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00007381 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00007382 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
7383 // Ivar declared in @implementation never belongs to the implementation.
7384 // Only it is in implementation's lexical context.
Douglas Gregor8f36aba2009-04-23 03:23:08 +00007385 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00007386 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian83c481a2010-02-22 23:04:20 +00007387 } else if (ObjCCategoryDecl *CDecl =
7388 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian0bd04592010-04-06 22:43:48 +00007389 // case of ivars in class extension; all other cases have been
7390 // reported as errors elsewhere.
7391 // FIXME. Class extension does not have a LocEnd field.
7392 // CDecl->setLocEnd(RBrac);
7393 // Add ivar's to class extension's DeclContext.
7394 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
7395 ClsFields[i]->setLexicalDeclContext(CDecl);
7396 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian83c481a2010-02-22 23:04:20 +00007397 }
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00007398 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00007399 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00007400
7401 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00007402 ProcessDeclAttributeList(S, Record, Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00007403
7404 // If there's a #pragma GCC visibility in scope, and this isn't a subclass,
7405 // set the visibility of this record.
7406 if (Record && !Record->getDeclContext()->isRecord())
7407 AddPushedVisibilityAttribute(Record);
Reid Spencer5f016e22007-07-11 17:01:13 +00007408}
7409
Douglas Gregor677e4fe2010-02-01 23:36:03 +00007410/// \brief Determine whether the given integral value is representable within
7411/// the given type T.
7412static bool isRepresentableIntegerValue(ASTContext &Context,
7413 llvm::APSInt &Value,
7414 QualType T) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00007415 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregoraf68d4e2010-04-15 15:53:31 +00007416 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor677e4fe2010-02-01 23:36:03 +00007417
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007418 if (Value.isUnsigned() || Value.isNonNegative()) {
7419 if (T->isSignedIntegerType())
7420 --BitWidth;
7421 return Value.getActiveBits() <= BitWidth;
7422 }
Douglas Gregor677e4fe2010-02-01 23:36:03 +00007423 return Value.getMinSignedBits() <= BitWidth;
7424}
7425
7426// \brief Given an integral type, return the next larger integral type
7427// (or a NULL type of no such type exists).
7428static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
7429 // FIXME: Int128/UInt128 support, which also needs to be introduced into
7430 // enum checking below.
Douglas Gregor9d3347a2010-06-16 00:35:25 +00007431 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor677e4fe2010-02-01 23:36:03 +00007432 const unsigned NumTypes = 4;
7433 QualType SignedIntegralTypes[NumTypes] = {
7434 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
7435 };
7436 QualType UnsignedIntegralTypes[NumTypes] = {
7437 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
7438 Context.UnsignedLongLongTy
7439 };
7440
7441 unsigned BitWidth = Context.getTypeSize(T);
7442 QualType *Types = T->isSignedIntegerType()? SignedIntegralTypes
7443 : UnsignedIntegralTypes;
7444 for (unsigned I = 0; I != NumTypes; ++I)
7445 if (Context.getTypeSize(Types[I]) > BitWidth)
7446 return Types[I];
7447
7448 return QualType();
7449}
7450
Douglas Gregor879fd492009-03-17 19:05:46 +00007451EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
7452 EnumConstantDecl *LastEnumConst,
7453 SourceLocation IdLoc,
7454 IdentifierInfo *Id,
John McCall9ae2f072010-08-23 23:25:46 +00007455 Expr *Val) {
Douglas Gregor677e4fe2010-02-01 23:36:03 +00007456 unsigned IntWidth = Context.Target.getIntWidth();
7457 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor879fd492009-03-17 19:05:46 +00007458 QualType EltTy;
Douglas Gregor0c9e4792010-12-16 00:24:44 +00007459
7460 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
7461 Val = 0;
7462
Douglas Gregor4912c342009-11-06 00:03:12 +00007463 if (Val) {
Douglas Gregor9b9edd62010-03-02 17:53:14 +00007464 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregor4912c342009-11-06 00:03:12 +00007465 EltTy = Context.DependentTy;
7466 else {
Douglas Gregor4912c342009-11-06 00:03:12 +00007467 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
7468 SourceLocation ExpLoc;
Douglas Gregor9b9edd62010-03-02 17:53:14 +00007469 if (!Val->isValueDependent() &&
7470 VerifyIntegerConstantExpression(Val, &EnumVal)) {
Douglas Gregor4912c342009-11-06 00:03:12 +00007471 Val = 0;
Douglas Gregor677e4fe2010-02-01 23:36:03 +00007472 } else {
7473 if (!getLangOptions().CPlusPlus) {
7474 // C99 6.7.2.2p2:
7475 // The expression that defines the value of an enumeration constant
7476 // shall be an integer constant expression that has a value
7477 // representable as an int.
7478
7479 // Complain if the value is not representable in an int.
7480 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
7481 Diag(IdLoc, diag::ext_enum_value_not_int)
7482 << EnumVal.toString(10) << Val->getSourceRange()
Douglas Gregor19c15252010-02-17 22:40:11 +00007483 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
Douglas Gregor677e4fe2010-02-01 23:36:03 +00007484 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
7485 // Force the type of the expression to 'int'.
John McCall2de56d12010-08-25 11:45:40 +00007486 ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast);
Douglas Gregor677e4fe2010-02-01 23:36:03 +00007487 }
7488 }
7489
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007490 if (Enum->isFixed()) {
7491 EltTy = Enum->getIntegerType();
7492
7493 // C++0x [dcl.enum]p5:
7494 // ... if the initializing value of an enumerator cannot be
7495 // represented by the underlying type, the program is ill-formed.
Francois Pichet842e7a22010-10-18 15:01:13 +00007496 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
7497 if (getLangOptions().Microsoft) {
7498 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
7499 ImpCastExprToType(Val, EltTy, CK_IntegralCast);
7500 } else
7501 Diag(IdLoc, diag::err_enumerator_too_large)
7502 << EltTy;
7503 } else
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007504 ImpCastExprToType(Val, EltTy, CK_IntegralCast);
7505 }
7506 else {
7507 // C++0x [dcl.enum]p5:
7508 // If the underlying type is not fixed, the type of each enumerator
7509 // is the type of its initializing value:
7510 // - If an initializer is specified for an enumerator, the
7511 // initializing value has the same type as the expression.
7512 EltTy = Val->getType();
7513 }
Douglas Gregor4912c342009-11-06 00:03:12 +00007514 }
Douglas Gregor879fd492009-03-17 19:05:46 +00007515 }
7516 }
Mike Stump1eb44332009-09-09 15:08:12 +00007517
Douglas Gregor879fd492009-03-17 19:05:46 +00007518 if (!Val) {
Eli Friedmaned0716b2009-12-11 01:34:50 +00007519 if (Enum->isDependentType())
7520 EltTy = Context.DependentTy;
Douglas Gregor677e4fe2010-02-01 23:36:03 +00007521 else if (!LastEnumConst) {
7522 // C++0x [dcl.enum]p5:
7523 // If the underlying type is not fixed, the type of each enumerator
7524 // is the type of its initializing value:
7525 // - If no initializer is specified for the first enumerator, the
7526 // initializing value has an unspecified integral type.
7527 //
7528 // GCC uses 'int' for its unspecified integral type, as does
7529 // C99 6.7.2.2p3.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007530 if (Enum->isFixed()) {
7531 EltTy = Enum->getIntegerType();
7532 }
7533 else {
7534 EltTy = Context.IntTy;
7535 }
Douglas Gregor677e4fe2010-02-01 23:36:03 +00007536 } else {
Douglas Gregor879fd492009-03-17 19:05:46 +00007537 // Assign the last value + 1.
7538 EnumVal = LastEnumConst->getInitVal();
7539 ++EnumVal;
Douglas Gregor677e4fe2010-02-01 23:36:03 +00007540 EltTy = LastEnumConst->getType();
Douglas Gregor879fd492009-03-17 19:05:46 +00007541
7542 // Check for overflow on increment.
Douglas Gregor677e4fe2010-02-01 23:36:03 +00007543 if (EnumVal < LastEnumConst->getInitVal()) {
7544 // C++0x [dcl.enum]p5:
7545 // If the underlying type is not fixed, the type of each enumerator
7546 // is the type of its initializing value:
7547 //
7548 // - Otherwise the type of the initializing value is the same as
7549 // the type of the initializing value of the preceding enumerator
7550 // unless the incremented value is not representable in that type,
7551 // in which case the type is an unspecified integral type
7552 // sufficient to contain the incremented value. If no such type
7553 // exists, the program is ill-formed.
7554 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007555 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor677e4fe2010-02-01 23:36:03 +00007556 // There is no integral type larger enough to represent this
7557 // value. Complain, then allow the value to wrap around.
7558 EnumVal = LastEnumConst->getInitVal();
Jay Foad9f71a8f2010-12-07 08:25:34 +00007559 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007560 ++EnumVal;
7561 if (Enum->isFixed())
7562 // When the underlying type is fixed, this is ill-formed.
7563 Diag(IdLoc, diag::err_enumerator_wrapped)
7564 << EnumVal.toString(10)
7565 << EltTy;
7566 else
7567 Diag(IdLoc, diag::warn_enumerator_too_large)
7568 << EnumVal.toString(10);
Douglas Gregor677e4fe2010-02-01 23:36:03 +00007569 } else {
7570 EltTy = T;
7571 }
7572
7573 // Retrieve the last enumerator's value, extent that type to the
7574 // type that is supposed to be large enough to represent the incremented
7575 // value, then increment.
7576 EnumVal = LastEnumConst->getInitVal();
7577 EnumVal.setIsSigned(EltTy->isSignedIntegerType());
Jay Foad9f71a8f2010-12-07 08:25:34 +00007578 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor677e4fe2010-02-01 23:36:03 +00007579 ++EnumVal;
7580
7581 // If we're not in C++, diagnose the overflow of enumerator values,
7582 // which in C99 means that the enumerator value is not representable in
7583 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
7584 // permits enumerator values that are representable in some larger
7585 // integral type.
7586 if (!getLangOptions().CPlusPlus && !T.isNull())
7587 Diag(IdLoc, diag::warn_enum_value_overflow);
7588 } else if (!getLangOptions().CPlusPlus &&
7589 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
7590 // Enforce C99 6.7.2.2p2 even when we compute the next value.
7591 Diag(IdLoc, diag::ext_enum_value_not_int)
7592 << EnumVal.toString(10) << 1;
7593 }
Douglas Gregor879fd492009-03-17 19:05:46 +00007594 }
7595 }
Mike Stump1eb44332009-09-09 15:08:12 +00007596
Douglas Gregor9b9edd62010-03-02 17:53:14 +00007597 if (!EltTy->isDependentType()) {
Douglas Gregor677e4fe2010-02-01 23:36:03 +00007598 // Make the enumerator value match the signedness and size of the
7599 // enumerator's type.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007600 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor677e4fe2010-02-01 23:36:03 +00007601 EnumVal.setIsSigned(EltTy->isSignedIntegerType());
7602 }
Douglas Gregor4912c342009-11-06 00:03:12 +00007603
Douglas Gregor879fd492009-03-17 19:05:46 +00007604 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump1eb44332009-09-09 15:08:12 +00007605 Val, EnumVal);
Douglas Gregor879fd492009-03-17 19:05:46 +00007606}
7607
7608
John McCall5b629aa2010-10-22 23:36:17 +00007609Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
7610 SourceLocation IdLoc, IdentifierInfo *Id,
7611 AttributeList *Attr,
7612 SourceLocation EqualLoc, ExprTy *val) {
John McCalld226f652010-08-21 09:40:31 +00007613 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00007614 EnumConstantDecl *LastEnumConst =
John McCalld226f652010-08-21 09:40:31 +00007615 cast_or_null<EnumConstantDecl>(lastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00007616 Expr *Val = static_cast<Expr*>(val);
7617
Chris Lattner31e05722007-08-26 06:24:45 +00007618 // The scope passed in may not be a decl scope. Zip up the scope tree until
7619 // we find one that is.
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00007620 S = getNonFieldDeclScope(S);
Mike Stump1eb44332009-09-09 15:08:12 +00007621
Reid Spencer5f016e22007-07-11 17:01:13 +00007622 // Verify that there isn't already something declared with this name in this
7623 // scope.
Douglas Gregorc83c6872010-04-15 22:33:43 +00007624 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregore39fe722010-01-19 06:06:57 +00007625 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +00007626 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00007627 // Maybe we will complain about the shadowed template parameter.
7628 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
7629 // Just pretend that we didn't see the previous declaration.
7630 PrevDecl = 0;
7631 }
7632
7633 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00007634 // When in C++, we may get a TagDecl with the same name; in this case the
7635 // enum constant will 'hide' the tag.
7636 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
7637 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00007638 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00007639 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00007640 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00007641 else
Chris Lattner3c73c412008-11-19 08:23:25 +00007642 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00007643 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007644 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00007645 }
7646 }
7647
Douglas Gregora6e937c2010-10-15 13:21:21 +00007648 // C++ [class.mem]p13:
7649 // If T is the name of a class, then each of the following shall have a
7650 // name different from T:
7651 // - every enumerator of every member of class T that is an enumerated
7652 // type
7653 if (CXXRecordDecl *Record
7654 = dyn_cast<CXXRecordDecl>(
7655 TheEnumDecl->getDeclContext()->getRedeclContext()))
7656 if (Record->getIdentifier() && Record->getIdentifier() == Id)
7657 Diag(IdLoc, diag::err_member_name_of_class) << Id;
7658
John McCall5b629aa2010-10-22 23:36:17 +00007659 EnumConstantDecl *New =
7660 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner421a23d2007-08-27 21:16:18 +00007661
John McCall92f88312010-01-23 00:46:32 +00007662 if (New) {
John McCall5b629aa2010-10-22 23:36:17 +00007663 // Process attributes.
7664 if (Attr) ProcessDeclAttributeList(S, New, Attr);
7665
7666 // Register this decl in the current scope stack.
John McCall92f88312010-01-23 00:46:32 +00007667 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor879fd492009-03-17 19:05:46 +00007668 PushOnScopeChains(New, S);
John McCall92f88312010-01-23 00:46:32 +00007669 }
Douglas Gregor45579f52008-12-17 02:04:30 +00007670
John McCalld226f652010-08-21 09:40:31 +00007671 return New;
Reid Spencer5f016e22007-07-11 17:01:13 +00007672}
7673
Mike Stumpc6e35aa2009-05-16 07:06:02 +00007674void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCalld226f652010-08-21 09:40:31 +00007675 SourceLocation RBraceLoc, Decl *EnumDeclX,
7676 Decl **Elements, unsigned NumElements,
Edward O'Callaghanfee13812009-08-08 14:36:57 +00007677 Scope *S, AttributeList *Attr) {
John McCalld226f652010-08-21 09:40:31 +00007678 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor074149e2009-01-05 19:45:36 +00007679 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanfee13812009-08-08 14:36:57 +00007680
7681 if (Attr)
7682 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump1eb44332009-09-09 15:08:12 +00007683
Eli Friedmaned0716b2009-12-11 01:34:50 +00007684 if (Enum->isDependentType()) {
7685 for (unsigned i = 0; i != NumElements; ++i) {
7686 EnumConstantDecl *ECD =
John McCalld226f652010-08-21 09:40:31 +00007687 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmaned0716b2009-12-11 01:34:50 +00007688 if (!ECD) continue;
7689
7690 ECD->setType(EnumType);
7691 }
7692
John McCall1b5a6182010-05-06 08:49:23 +00007693 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmaned0716b2009-12-11 01:34:50 +00007694 return;
7695 }
7696
Chris Lattnere37f0be2007-08-28 05:10:31 +00007697 // TODO: If the result value doesn't fit in an int, it must be a long or long
7698 // long value. ISO C does not support this, but GCC does as an extension,
7699 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00007700 unsigned IntWidth = Context.Target.getIntWidth();
Edward O'Callaghanfee13812009-08-08 14:36:57 +00007701 unsigned CharWidth = Context.Target.getCharWidth();
7702 unsigned ShortWidth = Context.Target.getShortWidth();
Mike Stump1eb44332009-09-09 15:08:12 +00007703
Chris Lattnerac609682007-08-28 06:15:15 +00007704 // Verify that all the values are okay, compute the size of the values, and
7705 // reverse the list.
7706 unsigned NumNegativeBits = 0;
7707 unsigned NumPositiveBits = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007708
Chris Lattnerac609682007-08-28 06:15:15 +00007709 // Keep track of whether all elements have type int.
7710 bool AllElementsInt = true;
Mike Stump1eb44332009-09-09 15:08:12 +00007711
Reid Spencer5f016e22007-07-11 17:01:13 +00007712 for (unsigned i = 0; i != NumElements; ++i) {
7713 EnumConstantDecl *ECD =
John McCalld226f652010-08-21 09:40:31 +00007714 cast_or_null<EnumConstantDecl>(Elements[i]);
Reid Spencer5f016e22007-07-11 17:01:13 +00007715 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump1eb44332009-09-09 15:08:12 +00007716
Chris Lattner211a30e2007-08-28 05:27:00 +00007717 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump1eb44332009-09-09 15:08:12 +00007718
Chris Lattnerac609682007-08-28 06:15:15 +00007719 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00007720 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00007721 NumPositiveBits = std::max(NumPositiveBits,
7722 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00007723 else
Chris Lattner21dd8212008-01-14 21:47:29 +00007724 NumNegativeBits = std::max(NumNegativeBits,
7725 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00007726
Chris Lattnerac609682007-08-28 06:15:15 +00007727 // Keep track of whether every enum element has type int (very commmon).
7728 if (AllElementsInt)
Mike Stump1eb44332009-09-09 15:08:12 +00007729 AllElementsInt = ECD->getType() == Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00007730 }
Mike Stump1eb44332009-09-09 15:08:12 +00007731
Chris Lattnerac609682007-08-28 06:15:15 +00007732 // Figure out the type that should be used for this enum.
Chris Lattnerac609682007-08-28 06:15:15 +00007733 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00007734 unsigned BestWidth;
Edward O'Callaghanfee13812009-08-08 14:36:57 +00007735
John McCall842aef82009-12-09 09:09:27 +00007736 // C++0x N3000 [conv.prom]p3:
7737 // An rvalue of an unscoped enumeration type whose underlying
7738 // type is not fixed can be converted to an rvalue of the first
7739 // of the following types that can represent all the values of
7740 // the enumeration: int, unsigned int, long int, unsigned long
7741 // int, long long int, or unsigned long long int.
7742 // C99 6.4.4.3p2:
7743 // An identifier declared as an enumeration constant has type int.
7744 // The C99 rule is modified by a gcc extension
7745 QualType BestPromotionType;
7746
Edward O'Callaghanfee13812009-08-08 14:36:57 +00007747 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
Argyrios Kyrtzidis9a2b9d72010-10-08 00:25:19 +00007748 // -fshort-enums is the equivalent to specifying the packed attribute on all
7749 // enum definitions.
7750 if (LangOpts.ShortEnums)
7751 Packed = true;
Edward O'Callaghanfee13812009-08-08 14:36:57 +00007752
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007753 if (Enum->isFixed()) {
7754 BestType = BestPromotionType = Enum->getIntegerType();
Duncan Sands240a0202010-10-12 14:07:59 +00007755 // We don't need to set BestWidth, because BestType is going to be the type
7756 // of the enumerators, but we do anyway because otherwise some compilers
7757 // warn that it might be used uninitialized.
7758 BestWidth = CharWidth;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00007759 }
7760 else if (NumNegativeBits) {
Mike Stump1eb44332009-09-09 15:08:12 +00007761 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerac609682007-08-28 06:15:15 +00007762 // int/long/longlong) that fits.
Edward O'Callaghanfee13812009-08-08 14:36:57 +00007763 // If it's packed, check also if it fits a char or a short.
7764 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall842aef82009-12-09 09:09:27 +00007765 BestType = Context.SignedCharTy;
7766 BestWidth = CharWidth;
Mike Stump1eb44332009-09-09 15:08:12 +00007767 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanfee13812009-08-08 14:36:57 +00007768 NumPositiveBits < ShortWidth) {
John McCall842aef82009-12-09 09:09:27 +00007769 BestType = Context.ShortTy;
7770 BestWidth = ShortWidth;
7771 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00007772 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00007773 BestWidth = IntWidth;
7774 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00007775 BestWidth = Context.Target.getLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +00007776
John McCall842aef82009-12-09 09:09:27 +00007777 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00007778 BestType = Context.LongTy;
John McCall842aef82009-12-09 09:09:27 +00007779 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00007780 BestWidth = Context.Target.getLongLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +00007781
Chris Lattnerb7f6e082007-08-29 17:31:48 +00007782 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00007783 Diag(Enum->getLocation(), diag::warn_enum_too_large);
7784 BestType = Context.LongLongTy;
7785 }
7786 }
John McCall842aef82009-12-09 09:09:27 +00007787 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerac609682007-08-28 06:15:15 +00007788 } else {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00007789 // If there is no negative value, figure out the smallest type that fits
7790 // all of the enumerator values.
Edward O'Callaghanfee13812009-08-08 14:36:57 +00007791 // If it's packed, check also if it fits a char or a short.
7792 if (Packed && NumPositiveBits <= CharWidth) {
John McCall842aef82009-12-09 09:09:27 +00007793 BestType = Context.UnsignedCharTy;
7794 BestPromotionType = Context.IntTy;
7795 BestWidth = CharWidth;
Edward O'Callaghanfee13812009-08-08 14:36:57 +00007796 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall842aef82009-12-09 09:09:27 +00007797 BestType = Context.UnsignedShortTy;
7798 BestPromotionType = Context.IntTy;
7799 BestWidth = ShortWidth;
7800 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00007801 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00007802 BestWidth = IntWidth;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00007803 BestPromotionType
7804 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
7805 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00007806 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00007807 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00007808 BestType = Context.UnsignedLongTy;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00007809 BestPromotionType
7810 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
7811 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00007812 } else {
7813 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00007814 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00007815 "How could an initializer get larger than ULL?");
7816 BestType = Context.UnsignedLongLongTy;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00007817 BestPromotionType
7818 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
7819 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerac609682007-08-28 06:15:15 +00007820 }
7821 }
Mike Stump1eb44332009-09-09 15:08:12 +00007822
Chris Lattnerb7f6e082007-08-29 17:31:48 +00007823 // Loop over all of the enumerator constants, changing their types to match
7824 // the type of the enum if needed.
7825 for (unsigned i = 0; i != NumElements; ++i) {
John McCalld226f652010-08-21 09:40:31 +00007826 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00007827 if (!ECD) continue; // Already issued a diagnostic.
7828
7829 // Standard C says the enumerators have int type, but we allow, as an
7830 // extension, the enumerators to be larger than int size. If each
7831 // enumerator value fits in an int, type it as an int, otherwise type it the
7832 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
7833 // that X has type 'int', not 'unsigned'.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00007834
7835 // Determine whether the value fits into an int.
7836 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00007837
7838 // If it fits into an integer type, force it. Otherwise force it to match
7839 // the enum decl type.
7840 QualType NewTy;
7841 unsigned NewWidth;
7842 bool NewSign;
Douglas Gregor677e4fe2010-02-01 23:36:03 +00007843 if (!getLangOptions().CPlusPlus &&
7844 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00007845 NewTy = Context.IntTy;
7846 NewWidth = IntWidth;
7847 NewSign = true;
7848 } else if (ECD->getType() == BestType) {
7849 // Already the right type!
Douglas Gregorc9467cf2008-12-12 02:00:36 +00007850 if (getLangOptions().CPlusPlus)
7851 // C++ [dcl.enum]p4: Following the closing brace of an
7852 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +00007853 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +00007854 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00007855 continue;
7856 } else {
7857 NewTy = BestType;
7858 NewWidth = BestWidth;
7859 NewSign = BestType->isSignedIntegerType();
7860 }
7861
7862 // Adjust the APSInt value.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007863 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00007864 InitVal.setIsSigned(NewSign);
7865 ECD->setInitVal(InitVal);
Mike Stump1eb44332009-09-09 15:08:12 +00007866
Chris Lattnerb7f6e082007-08-29 17:31:48 +00007867 // Adjust the Expr initializer and type.
Abramo Bagnara320e1532010-12-17 15:49:53 +00007868 if (ECD->getInitExpr() &&
7869 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallf871d0c2010-08-07 06:22:56 +00007870 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCall2de56d12010-08-25 11:45:40 +00007871 CK_IntegralCast,
John McCallf871d0c2010-08-07 06:22:56 +00007872 ECD->getInitExpr(),
7873 /*base paths*/ 0,
John McCall5baba9d2010-08-25 10:28:54 +00007874 VK_RValue));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00007875 if (getLangOptions().CPlusPlus)
7876 // C++ [dcl.enum]p4: Following the closing brace of an
7877 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +00007878 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +00007879 ECD->setType(EnumType);
7880 else
7881 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00007882 }
Mike Stump1eb44332009-09-09 15:08:12 +00007883
John McCall1b5a6182010-05-06 08:49:23 +00007884 Enum->completeDefinition(BestType, BestPromotionType,
7885 NumPositiveBits, NumNegativeBits);
Reid Spencer5f016e22007-07-11 17:01:13 +00007886}
7887
John McCall9ae2f072010-08-23 23:25:46 +00007888Decl *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc, Expr *expr) {
7889 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redl798d1192008-12-13 16:23:55 +00007890
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +00007891 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
7892 Loc, AsmString);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00007893 CurContext->addDecl(New);
John McCalld226f652010-08-21 09:40:31 +00007894 return New;
Anders Carlssondfab6cb2008-02-08 00:33:21 +00007895}
Eli Friedmanc49f19b2009-06-05 02:44:36 +00007896
7897void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
7898 SourceLocation PragmaLoc,
7899 SourceLocation NameLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00007900 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedmanc49f19b2009-06-05 02:44:36 +00007901
Eli Friedmanc49f19b2009-06-05 02:44:36 +00007902 if (PrevDecl) {
Sean Huntcf807c42010-08-18 23:23:40 +00007903 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
Ryan Flynne25ff832009-07-30 03:15:39 +00007904 } else {
7905 (void)WeakUndeclaredIdentifiers.insert(
7906 std::pair<IdentifierInfo*,WeakInfo>
7907 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedmanc49f19b2009-06-05 02:44:36 +00007908 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +00007909}
7910
7911void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
7912 IdentifierInfo* AliasName,
7913 SourceLocation PragmaLoc,
7914 SourceLocation NameLoc,
7915 SourceLocation AliasNameLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00007916 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
7917 LookupOrdinaryName);
Ryan Flynne25ff832009-07-30 03:15:39 +00007918 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedmanc49f19b2009-06-05 02:44:36 +00007919
Eli Friedmanc49f19b2009-06-05 02:44:36 +00007920 if (PrevDecl) {
Ryan Flynne25ff832009-07-30 03:15:39 +00007921 if (!PrevDecl->hasAttr<AliasAttr>())
7922 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynn7b1fdbd2009-07-31 02:52:19 +00007923 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynne25ff832009-07-30 03:15:39 +00007924 } else {
7925 (void)WeakUndeclaredIdentifiers.insert(
7926 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedmanc49f19b2009-06-05 02:44:36 +00007927 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +00007928}