blob: 339cb6632de1c0b6efcc7deffb14244a070b0b5f [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
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
15#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000017#include "clang/AST/APValue.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000018#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000021#include "clang/AST/DeclTemplate.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000022#include "clang/AST/ExprCXX.h"
Sebastian Redld3a413d2009-04-26 20:35:05 +000023#include "clang/AST/StmtCXX.h"
John McCall19510852010-08-20 18:27:03 +000024#include "clang/Sema/DeclSpec.h"
25#include "clang/Sema/ParsedTemplate.h"
Douglas Gregora786fdb2009-10-13 23:27:22 +000026#include "clang/Parse/ParseDiagnostic.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000028#include "clang/Basic/SourceManager.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000029#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000030// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000031#include "clang/Lex/Preprocessor.h"
Mike Stump1eb44332009-09-09 15:08:12 +000032#include "clang/Lex/HeaderSearch.h"
John McCall66755862009-12-24 09:58:38 +000033#include "llvm/ADT/Triple.h"
Douglas Gregor6ed40e32008-12-23 21:05:05 +000034#include <algorithm>
Douglas Gregor9a8c9a22009-09-28 21:14:19 +000035#include <cstring>
Douglas Gregor6ed40e32008-12-23 21:05:05 +000036#include <functional>
Reid Spencer5f016e22007-07-11 17:01:13 +000037using namespace clang;
38
Chris Lattner21ff9c92009-03-05 01:25:28 +000039/// getDeclName - Return a pretty name for the specified decl if possible, or
Mike Stump1eb44332009-09-09 15:08:12 +000040/// an empty string if not. This is used for pretty crash reporting.
Chris Lattnerb28317a2009-03-28 19:18:32 +000041std::string Sema::getDeclName(DeclPtrTy d) {
42 Decl *D = d.getAs<Decl>();
Chris Lattner21ff9c92009-03-05 01:25:28 +000043 if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(D))
44 return DN->getQualifiedNameAsString();
45 return "";
46}
47
Chris Lattner682bf922009-03-29 16:50:03 +000048Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(DeclPtrTy Ptr) {
49 return DeclGroupPtrTy::make(DeclGroupRef(Ptr.getAs<Decl>()));
50}
51
Douglas Gregord6efafa2009-02-04 19:16:12 +000052/// \brief If the identifier refers to a type name within this scope,
53/// return the declaration of that type.
54///
55/// This routine performs ordinary name lookup of the identifier II
56/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor1a51b4a2009-02-09 15:09:02 +000057/// determine whether the name refers to a type. If so, returns an
58/// opaque pointer (actually a QualType) corresponding to that
59/// type. Otherwise, returns NULL.
Douglas Gregord6efafa2009-02-04 19:16:12 +000060///
61/// If name lookup results in an ambiguity, this routine will complain
62/// and then return NULL.
Douglas Gregor1a51b4a2009-02-09 15:09:02 +000063Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +000064 Scope *S, CXXScopeSpec *SS,
Douglas Gregorf6e6fc82009-11-20 22:03:38 +000065 bool isClassName,
66 TypeTy *ObjectTypePtr) {
67 // Determine where we will perform name lookup.
68 DeclContext *LookupCtx = 0;
69 if (ObjectTypePtr) {
70 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
71 if (ObjectType->isRecordType())
72 LookupCtx = computeDeclContext(ObjectType);
Jeffrey Yasskinedc28772010-04-07 23:29:58 +000073 } else if (SS && SS->isNotEmpty()) {
Douglas Gregorf6e6fc82009-11-20 22:03:38 +000074 LookupCtx = computeDeclContext(*SS, false);
75
76 if (!LookupCtx) {
77 if (isDependentScopeSpecifier(*SS)) {
78 // C++ [temp.res]p3:
79 // A qualified-id that refers to a type and in which the
80 // nested-name-specifier depends on a template-parameter (14.6.2)
81 // shall be prefixed by the keyword typename to indicate that the
82 // qualified-id denotes a type, forming an
83 // elaborated-type-specifier (7.1.5.3).
84 //
85 // We therefore do not perform any name lookup if the result would
86 // refer to a member of an unknown specialization.
87 if (!isClassName)
88 return 0;
89
John McCall33500952010-06-11 00:33:02 +000090 // We know from the grammar that this name refers to a type,
91 // so build a dependent node to describe the type.
Douglas Gregor107de902010-04-24 15:35:55 +000092 return CheckTypenameType(ETK_None,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +000093 (NestedNameSpecifier *)SS->getScopeRep(), II,
94 SourceLocation(), SS->getRange(), NameLoc
95 ).getAsOpaquePtr();
Douglas Gregorf6e6fc82009-11-20 22:03:38 +000096 }
97
Douglas Gregor42c39f32009-08-26 18:27:52 +000098 return 0;
Douglas Gregorf6e6fc82009-11-20 22:03:38 +000099 }
100
John McCall77bb1aa2010-05-01 00:40:08 +0000101 if (!LookupCtx->isDependentContext() &&
102 RequireCompleteDeclContext(*SS, LookupCtx))
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000103 return 0;
Douglas Gregor42c39f32009-08-26 18:27:52 +0000104 }
Eli Friedman0f0615b2009-12-21 01:42:38 +0000105
106 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
107 // lookup for class-names.
108 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
109 LookupOrdinaryName;
110 LookupResult Result(*this, &II, NameLoc, Kind);
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000111 if (LookupCtx) {
112 // Perform "qualified" name lookup into the declaration context we
113 // computed, which is either the type of the base of a member access
114 // expression or the declaration context associated with a prior
115 // nested-name-specifier.
116 LookupQualifiedName(Result, LookupCtx);
Douglas Gregor42af25f2009-05-11 19:58:34 +0000117
Douglas Gregorf6e6fc82009-11-20 22:03:38 +0000118 if (ObjectTypePtr && Result.empty()) {
119 // C++ [basic.lookup.classref]p3:
120 // If the unqualified-id is ~type-name, the type-name is looked up
121 // in the context of the entire postfix-expression. If the type T of
122 // the object expression is of a class type C, the type-name is also
123 // looked up in the scope of class C. At least one of the lookups shall
124 // find a name that refers to (possibly cv-qualified) T.
125 LookupName(Result, S);
126 }
127 } else {
128 // Perform unqualified name lookup.
129 LookupName(Result, S);
130 }
131
Chris Lattner22bd9052009-02-16 22:07:16 +0000132 NamedDecl *IIDecl = 0;
John McCalla24dc2e2009-11-17 02:14:36 +0000133 switch (Result.getResultKind()) {
Chris Lattner22bd9052009-02-16 22:07:16 +0000134 case LookupResult::NotFound:
Douglas Gregor7d3f5762010-01-15 01:44:47 +0000135 case LookupResult::NotFoundInCurrentInstantiation:
Chris Lattner22bd9052009-02-16 22:07:16 +0000136 case LookupResult::FoundOverloaded:
John McCall7ba107a2009-11-18 02:36:19 +0000137 case LookupResult::FoundUnresolvedValue:
John McCallc373d482010-01-27 01:50:18 +0000138 Result.suppressDiagnostics();
Chris Lattner22bd9052009-02-16 22:07:16 +0000139 return 0;
Douglas Gregorb696ea32009-02-04 17:00:24 +0000140
Chris Lattnera64ef0a2009-10-25 22:09:09 +0000141 case LookupResult::Ambiguous:
John McCall6e247262009-10-10 05:48:19 +0000142 // Recover from type-hiding ambiguities by hiding the type. We'll
143 // do the lookup again when looking for an object, and we can
144 // diagnose the error then. If we don't do this, then the error
145 // about hiding the type will be immediately followed by an error
146 // that only makes sense if the identifier was treated like a type.
John McCalla24dc2e2009-11-17 02:14:36 +0000147 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
148 Result.suppressDiagnostics();
John McCall6e247262009-10-10 05:48:19 +0000149 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +0000150 }
John McCall6e247262009-10-10 05:48:19 +0000151
Douglas Gregor31a19b62009-04-01 21:51:26 +0000152 // Look to see if we have a type anywhere in the list of results.
153 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
154 Res != ResEnd; ++Res) {
155 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000156 if (!IIDecl ||
157 (*Res)->getLocation().getRawEncoding() <
Douglas Gregor841b53c2009-04-13 15:14:38 +0000158 IIDecl->getLocation().getRawEncoding())
159 IIDecl = *Res;
Douglas Gregor31a19b62009-04-01 21:51:26 +0000160 }
161 }
162
163 if (!IIDecl) {
164 // None of the entities we found is a type, so there is no way
165 // to even assume that the result is a type. In this case, don't
166 // complain about the ambiguity. The parser will either try to
167 // perform this lookup again (e.g., as an object name), which
168 // will produce the ambiguity, or will complain that it expected
169 // a type name.
John McCalla24dc2e2009-11-17 02:14:36 +0000170 Result.suppressDiagnostics();
Douglas Gregor31a19b62009-04-01 21:51:26 +0000171 return 0;
172 }
173
174 // We found a type within the ambiguous lookup; diagnose the
175 // ambiguity and then return that type. This might be the right
176 // answer, or it might not be, but it suppresses any attempt to
177 // perform the name lookup again.
Douglas Gregor31a19b62009-04-01 21:51:26 +0000178 break;
Douglas Gregorb696ea32009-02-04 17:00:24 +0000179
Chris Lattner22bd9052009-02-16 22:07:16 +0000180 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +0000181 IIDecl = Result.getFoundDecl();
Chris Lattner22bd9052009-02-16 22:07:16 +0000182 break;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000183 }
184
Chris Lattner10ca3372009-10-25 17:16:46 +0000185 assert(IIDecl && "Didn't find decl");
John McCall54abf7d2009-11-04 02:18:39 +0000186
Chris Lattner10ca3372009-10-25 17:16:46 +0000187 QualType T;
188 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
John McCall54abf7d2009-11-04 02:18:39 +0000189 DiagnoseUseOfDecl(IIDecl, NameLoc);
John McCalla24dc2e2009-11-17 02:14:36 +0000190
Chris Lattner10ca3372009-10-25 17:16:46 +0000191 if (T.isNull())
192 T = Context.getTypeDeclType(TD);
193
Douglas Gregore6258932009-03-19 00:39:20 +0000194 if (SS)
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000195 T = getElaboratedType(ETK_None, *SS, T);
Chris Lattner10ca3372009-10-25 17:16:46 +0000196
197 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
Chris Lattner10ca3372009-10-25 17:16:46 +0000198 T = Context.getObjCInterfaceType(IDecl);
John McCalla24dc2e2009-11-17 02:14:36 +0000199 } else {
200 // If it's not plausibly a type, suppress diagnostics.
201 Result.suppressDiagnostics();
Chris Lattner10ca3372009-10-25 17:16:46 +0000202 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +0000203 }
Douglas Gregore4e5b052009-03-19 00:18:19 +0000204
Chris Lattner10ca3372009-10-25 17:16:46 +0000205 return T.getAsOpaquePtr();
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,
Douglas Gregora786fdb2009-10-13 23:27:22 +0000236 TypeTy *&SuggestedType) {
237 // We don't have anything to suggest (yet).
238 SuggestedType = 0;
239
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,
286 Name, 0, 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) {
465 if (S->isDeclScope(DeclPtrTy::make(*I)) && D->declarationReplaces(*I)) {
466 S->RemoveDecl(DeclPtrTy::make(*I));
467 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 McCallf36e02d2009-10-09 21:13:30 +0000474 S->AddDecl(DeclPtrTy::make(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 McCall68263142009-11-18 22:49:29 +0000482static bool isOutOfScopePreviousDeclaration(NamedDecl *,
483 DeclContext*,
484 ASTContext&);
485
486/// Filters out lookup results that don't fall within the given scope
487/// as determined by isDeclInScope.
488static void FilterLookupForScope(Sema &SemaRef, LookupResult &R,
489 DeclContext *Ctx, Scope *S,
490 bool ConsiderLinkage) {
491 LookupResult::Filter F = R.makeFilter();
492 while (F.hasNext()) {
493 NamedDecl *D = F.next();
494
495 if (SemaRef.isDeclInScope(D, Ctx, S))
496 continue;
497
498 if (ConsiderLinkage &&
499 isOutOfScopePreviousDeclaration(D, Ctx, SemaRef.Context))
500 continue;
501
502 F.erase();
503 }
504
505 F.done();
506}
507
508static bool isUsingDecl(NamedDecl *D) {
509 return isa<UsingShadowDecl>(D) ||
510 isa<UnresolvedUsingTypenameDecl>(D) ||
511 isa<UnresolvedUsingValueDecl>(D);
512}
513
514/// Removes using shadow declarations from the lookup results.
515static void RemoveUsingDecls(LookupResult &R) {
516 LookupResult::Filter F = R.makeFilter();
517 while (F.hasNext())
518 if (isUsingDecl(F.next()))
519 F.erase();
520
521 F.done();
522}
523
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +0000524/// \brief Check for this common pattern:
525/// @code
526/// class S {
527/// S(const S&); // DO NOT IMPLEMENT
528/// void operator=(const S&); // DO NOT IMPLEMENT
529/// };
530/// @endcode
531static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
532 // FIXME: Should check for private access too but access is set after we get
533 // the decl here.
534 if (D->isThisDeclarationADefinition())
535 return false;
536
537 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
538 return CD->isCopyConstructor();
539 return D->isCopyAssignment();
540}
541
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000542bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
543 assert(D);
Argyrios Kyrtzidisf6d1d432010-08-13 18:42:29 +0000544
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000545 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
546 return false;
547
548 // Ignore class templates.
549 if (D->getDeclContext()->isDependentContext())
550 return false;
551
552 // We warn for unused decls internal to the translation unit.
553 if (D->getLinkage() == ExternalLinkage)
554 return false;
555
556 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +0000557 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
558 return false;
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000559
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +0000560 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
561 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
562 return false;
563 } else {
564 // 'static inline' functions are used in headers; don't warn.
565 if (FD->getStorageClass() == FunctionDecl::Static &&
566 FD->isInlineSpecified())
567 return false;
568 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000569
570 if (FD->isThisDeclarationADefinition())
571 return !Context.DeclMustBeEmitted(FD);
572 return true;
Argyrios Kyrtzidis06999f82010-08-15 10:17:33 +0000573 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000574
575 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
576 if (VD->isStaticDataMember() &&
577 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
578 return false;
579
580 if ( VD->isFileVarDecl() &&
581 !VD->getType().isConstant(Context))
582 return !Context.DeclMustBeEmitted(VD);
583 }
584
585 return false;
586 }
587
588 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
589 if (!D)
590 return;
591
592 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
593 const FunctionDecl *First = FD->getFirstDeclaration();
594 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
595 return; // First should already be in the vector.
596 }
597
598 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
599 const VarDecl *First = VD->getFirstDeclaration();
600 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
601 return; // First should already be in the vector.
602 }
603
604 if (ShouldWarnIfUnusedFileScopedDecl(D))
605 UnusedFileScopedDecls.push_back(D);
606 }
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +0000607
Anders Carlsson99a000e2009-11-07 07:18:14 +0000608static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall86ff3082010-02-04 22:26:26 +0000609 if (D->isInvalidDecl())
610 return false;
611
Anders Carlssonf7613d52009-11-07 07:26:56 +0000612 if (D->isUsed() || D->hasAttr<UnusedAttr>())
613 return false;
John McCall86ff3082010-02-04 22:26:26 +0000614
615 // White-list anything that isn't a local variable.
616 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
617 !D->getDeclContext()->isFunctionOrMethod())
618 return false;
619
620 // Types of valid local variables should be complete, so this should succeed.
Anders Carlssonf7613d52009-11-07 07:26:56 +0000621 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
John McCallaec58602010-03-31 02:47:45 +0000622
623 // White-list anything with an __attribute__((unused)) type.
624 QualType Ty = VD->getType();
625
626 // Only look at the outermost level of typedef.
627 if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) {
628 if (TT->getDecl()->hasAttr<UnusedAttr>())
629 return false;
630 }
631
Douglas Gregor5764f612010-05-08 23:05:03 +0000632 // If we failed to complete the type for some reason, or if the type is
633 // dependent, don't diagnose the variable.
634 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregora6a292b2010-04-27 16:20:13 +0000635 return false;
636
John McCallaec58602010-03-31 02:47:45 +0000637 if (const TagType *TT = Ty->getAs<TagType>()) {
638 const TagDecl *Tag = TT->getDecl();
639 if (Tag->hasAttr<UnusedAttr>())
640 return false;
641
642 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Douglas Gregor5764f612010-05-08 23:05:03 +0000643 // FIXME: Checking for the presence of a user-declared constructor
644 // isn't completely accurate; we'd prefer to check that the initializer
645 // has no side effects.
646 if (RD->hasUserDeclaredConstructor() || !RD->hasTrivialDestructor())
Anders Carlssonf7613d52009-11-07 07:26:56 +0000647 return false;
648 }
649 }
John McCallaec58602010-03-31 02:47:45 +0000650
651 // TODO: __attribute__((unused)) templates?
Anders Carlssonf7613d52009-11-07 07:26:56 +0000652 }
653
John McCall86ff3082010-02-04 22:26:26 +0000654 return true;
Anders Carlsson99a000e2009-11-07 07:18:14 +0000655}
656
Douglas Gregor5764f612010-05-08 23:05:03 +0000657void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
658 if (!ShouldDiagnoseUnusedDecl(D))
659 return;
660
661 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
662 Diag(D->getLocation(), diag::warn_unused_exception_param)
663 << D->getDeclName();
664 else
665 Diag(D->getLocation(), diag::warn_unused_variable)
666 << D->getDeclName();
667}
668
Steve Naroffb216c882007-10-09 22:01:59 +0000669void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000670 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000671 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump1eb44332009-09-09 15:08:12 +0000672 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000673
Reid Spencer5f016e22007-07-11 17:01:13 +0000674 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
675 I != E; ++I) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000676 Decl *TmpD = (*I).getAs<Decl>();
Steve Naroffc752d042007-09-13 18:10:37 +0000677 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000678
Douglas Gregor44b43212008-12-11 16:49:14 +0000679 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
680 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000681
Douglas Gregor44b43212008-12-11 16:49:14 +0000682 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000683
Douglas Gregorb5352cf2009-10-08 21:35:42 +0000684 // Diagnose unused variables in this scope.
Douglas Gregor5764f612010-05-08 23:05:03 +0000685 if (S->getNumErrorsAtStart() == getDiagnostics().getNumErrors())
686 DiagnoseUnusedDecl(D);
687
Douglas Gregor44b43212008-12-11 16:49:14 +0000688 // Remove this name from our lexical scope.
689 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000690 }
691}
692
Douglas Gregordeacbdc2010-08-11 12:19:30 +0000693/// \brief Look for an Objective-C class in the translation unit.
694///
695/// \param Id The name of the Objective-C class we're looking for. If
696/// typo-correction fixes this name, the Id will be updated
697/// to the fixed name.
698///
699/// \param IdLoc The location of the name in the translation unit.
700///
701/// \param TypoCorrection If true, this routine will attempt typo correction
702/// if there is no class with the given name.
703///
704/// \returns The declaration of the named Objective-C class, or NULL if the
705/// class could not be found.
706ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
707 SourceLocation IdLoc,
708 bool TypoCorrection) {
709 // The third "scope" argument is 0 since we aren't enabling lazy built-in
710 // creation from this context.
711 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
712
713 if (!IDecl && TypoCorrection) {
714 // Perform typo correction at the given location, but only if we
715 // find an Objective-C class name.
716 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName);
717 if (CorrectTypo(R, TUScope, 0, 0, false, CTC_NoKeywords) &&
718 (IDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
719 Diag(IdLoc, diag::err_undef_interface_suggest)
720 << Id << IDecl->getDeclName()
721 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
722 Diag(IDecl->getLocation(), diag::note_previous_decl)
723 << IDecl->getDeclName();
724
725 Id = IDecl->getIdentifier();
726 }
727 }
728
729 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
730}
731
Douglas Gregor1a0d31a2009-01-12 18:45:55 +0000732/// getNonFieldDeclScope - Retrieves the innermost scope, starting
733/// from S, where a non-field would be declared. This routine copes
734/// with the difference between C and C++ scoping rules in structs and
735/// unions. For example, the following code is well-formed in C but
736/// ill-formed in C++:
737/// @code
738/// struct S6 {
739/// enum { BAR } e;
740/// };
Mike Stump1eb44332009-09-09 15:08:12 +0000741///
Douglas Gregor1a0d31a2009-01-12 18:45:55 +0000742/// void test_S6() {
743/// struct S6 a;
744/// a.e = BAR;
745/// }
746/// @endcode
747/// For the declaration of BAR, this routine will return a different
748/// scope. The scope S will be the scope of the unnamed enumeration
749/// within S6. In C++, this routine will return the scope associated
750/// with S6, because the enumeration's scope is a transparent
751/// context but structures can contain non-field names. In C, this
752/// routine will return the translation unit scope, since the
753/// enumeration's scope is a transparent context and structures cannot
754/// contain non-field names.
755Scope *Sema::getNonFieldDeclScope(Scope *S) {
756 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000757 (S->getEntity() &&
Douglas Gregor1a0d31a2009-01-12 18:45:55 +0000758 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
759 (S->isClassScope() && !getLangOptions().CPlusPlus))
760 S = S->getParent();
761 return S;
762}
763
Chris Lattner95e2c712008-05-05 22:18:14 +0000764void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000765 if (!Context.getBuiltinVaListType().isNull())
766 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000768 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Douglas Gregorc83c6872010-04-15 22:33:43 +0000769 NamedDecl *VaDecl = LookupSingleName(TUScope, VaIdent, SourceLocation(),
770 LookupOrdinaryName, ForRedeclaration);
Steve Naroff733002f2007-10-18 22:17:45 +0000771 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000772 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
773}
774
Douglas Gregor3e41d602009-02-13 23:20:09 +0000775/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
776/// file scope. lazily create a decl for it. ForRedeclaration is true
777/// if we're creating this built-in in anticipation of redeclaring the
778/// built-in.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000779NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregor3e41d602009-02-13 23:20:09 +0000780 Scope *S, bool ForRedeclaration,
781 SourceLocation Loc) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000782 Builtin::ID BID = (Builtin::ID)bid;
783
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000784 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000785 InitBuiltinVaListType();
Douglas Gregor3e41d602009-02-13 23:20:09 +0000786
Chris Lattner86df27b2009-06-14 00:45:47 +0000787 ASTContext::GetBuiltinTypeError Error;
Mike Stump1eb44332009-09-09 15:08:12 +0000788 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor370ab3f2009-02-14 01:52:53 +0000789 switch (Error) {
Chris Lattner86df27b2009-06-14 00:45:47 +0000790 case ASTContext::GE_None:
Douglas Gregor370ab3f2009-02-14 01:52:53 +0000791 // Okay
792 break;
793
Mike Stumpf711c412009-07-28 23:57:15 +0000794 case ASTContext::GE_Missing_stdio:
Douglas Gregor370ab3f2009-02-14 01:52:53 +0000795 if (ForRedeclaration)
796 Diag(Loc, diag::err_implicit_decl_requires_stdio)
797 << Context.BuiltinInfo.GetName(BID);
798 return 0;
Mike Stump782fa302009-07-28 02:25:19 +0000799
Mike Stumpf711c412009-07-28 23:57:15 +0000800 case ASTContext::GE_Missing_setjmp:
Mike Stump782fa302009-07-28 02:25:19 +0000801 if (ForRedeclaration)
802 Diag(Loc, diag::err_implicit_decl_requires_setjmp)
803 << Context.BuiltinInfo.GetName(BID);
804 return 0;
Douglas Gregor370ab3f2009-02-14 01:52:53 +0000805 }
Douglas Gregor3e41d602009-02-13 23:20:09 +0000806
807 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
808 Diag(Loc, diag::ext_implicit_lib_function_decl)
809 << Context.BuiltinInfo.GetName(BID)
810 << R;
Douglas Gregorb1152d82009-02-16 21:58:21 +0000811 if (Context.BuiltinInfo.getHeaderName(BID) &&
Chris Lattner6a7334d2009-04-16 03:59:32 +0000812 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl)
813 != Diagnostic::Ignored)
Douglas Gregor3e41d602009-02-13 23:20:09 +0000814 Diag(Loc, diag::note_please_include_header)
815 << Context.BuiltinInfo.getHeaderName(BID)
816 << Context.BuiltinInfo.GetName(BID);
817 }
818
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000819 FunctionDecl *New = FunctionDecl::Create(Context,
820 Context.getTranslationUnitDecl(),
John McCalla93c9342009-12-07 02:54:59 +0000821 Loc, II, R, /*TInfo=*/0,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000822 FunctionDecl::Extern,
823 FunctionDecl::None, false,
Douglas Gregor2224f842009-02-25 16:33:18 +0000824 /*hasPrototype=*/true);
Douglas Gregor3e41d602009-02-13 23:20:09 +0000825 New->setImplicit();
826
Chris Lattner95e2c712008-05-05 22:18:14 +0000827 // Create Decl objects for each parameter, adding them to the
828 // FunctionDecl.
Douglas Gregor72564e72009-02-26 23:50:07 +0000829 if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner95e2c712008-05-05 22:18:14 +0000830 llvm::SmallVector<ParmVarDecl*, 16> Params;
831 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
832 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +0000833 FT->getArgType(i), /*TInfo=*/0,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000834 VarDecl::None, VarDecl::None, 0));
Douglas Gregor838db382010-02-11 01:19:42 +0000835 New->setParams(Params.data(), Params.size());
Chris Lattner95e2c712008-05-05 22:18:14 +0000836 }
Mike Stump1eb44332009-09-09 15:08:12 +0000837
838 AddKnownFunctionAttributes(New);
839
Chris Lattner7f925cc2008-04-11 07:00:53 +0000840 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000841 // FIXME: This is hideous. We need to teach PushOnScopeChains to
842 // relate Scopes to DeclContexts, and probably eliminate CurContext
843 // entirely, but we're not there yet.
844 DeclContext *SavedContext = CurContext;
845 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000846 PushOnScopeChains(New, TUScope);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000847 CurContext = SavedContext;
Reid Spencer5f016e22007-07-11 17:01:13 +0000848 return New;
849}
850
Douglas Gregorcda9c672009-02-16 17:45:42 +0000851/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
852/// same name and scope as a previous declaration 'Old'. Figure out
853/// how to resolve this situation, merging decls or emitting
Chris Lattnereaaebc72009-04-25 08:06:05 +0000854/// diagnostics as appropriate. If there was an error, set New to be invalid.
Reid Spencer5f016e22007-07-11 17:01:13 +0000855///
John McCall68263142009-11-18 22:49:29 +0000856void Sema::MergeTypeDefDecl(TypedefDecl *New, LookupResult &OldDecls) {
857 // If the new decl is known invalid already, don't bother doing any
858 // merging checks.
859 if (New->isInvalidDecl()) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000860
Steve Naroff2b255c42008-09-09 14:32:20 +0000861 // Allow multiple definitions for ObjC built-in typedefs.
862 // FIXME: Verify the underlying types are equivalent!
863 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000864 const IdentifierInfo *TypeID = New->getIdentifier();
865 switch (TypeID->getLength()) {
866 default: break;
Mike Stump1eb44332009-09-09 15:08:12 +0000867 case 2:
Chris Lattner2bac0f62008-11-20 05:41:43 +0000868 if (!TypeID->isStr("id"))
869 break;
David Chisnall0f436562009-08-17 16:35:33 +0000870 Context.ObjCIdRedefinitionType = New->getUnderlyingType();
Steve Naroff14108da2009-07-10 23:34:53 +0000871 // Install the built-in type for 'id', ignoring the current definition.
872 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
873 return;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000874 case 5:
875 if (!TypeID->isStr("Class"))
876 break;
David Chisnall0f436562009-08-17 16:35:33 +0000877 Context.ObjCClassRedefinitionType = New->getUnderlyingType();
Steve Naroff14108da2009-07-10 23:34:53 +0000878 // Install the built-in type for 'Class', ignoring the current definition.
879 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnereaaebc72009-04-25 08:06:05 +0000880 return;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000881 case 3:
882 if (!TypeID->isStr("SEL"))
883 break;
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +0000884 Context.ObjCSelRedefinitionType = New->getUnderlyingType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000885 // Install the built-in type for 'SEL', ignoring the current definition.
886 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnereaaebc72009-04-25 08:06:05 +0000887 return;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000888 case 8:
889 if (!TypeID->isStr("Protocol"))
890 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000891 Context.setObjCProtoType(New->getUnderlyingType());
Chris Lattnereaaebc72009-04-25 08:06:05 +0000892 return;
Steve Naroff2b255c42008-09-09 14:32:20 +0000893 }
894 // Fall through - the typedef name was not a builtin type.
895 }
John McCall68263142009-11-18 22:49:29 +0000896
Douglas Gregor66973122009-01-28 17:15:10 +0000897 // Verify the old decl was also a type.
John McCall5126fd02009-12-30 00:31:22 +0000898 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
899 if (!Old) {
Mike Stump1eb44332009-09-09 15:08:12 +0000900 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000901 << New->getDeclName();
John McCall68263142009-11-18 22:49:29 +0000902
903 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000904 if (OldD->getLocation().isValid())
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000905 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall68263142009-11-18 22:49:29 +0000906
Chris Lattnereaaebc72009-04-25 08:06:05 +0000907 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000908 }
Douglas Gregor66973122009-01-28 17:15:10 +0000909
John McCall68263142009-11-18 22:49:29 +0000910 // If the old declaration is invalid, just give up here.
911 if (Old->isInvalidDecl())
912 return New->setInvalidDecl();
913
Mike Stump1eb44332009-09-09 15:08:12 +0000914 // Determine the "old" type we'll use for checking and diagnostics.
Douglas Gregor66973122009-01-28 17:15:10 +0000915 QualType OldType;
916 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
917 OldType = OldTypedef->getUnderlyingType();
918 else
919 OldType = Context.getTypeDeclType(Old);
920
Chris Lattner99cb9972008-07-25 18:44:27 +0000921 // If the typedef types are not identical, reject them in all languages and
922 // with any extensions enabled.
Douglas Gregor66973122009-01-28 17:15:10 +0000923
Mike Stump1eb44332009-09-09 15:08:12 +0000924 if (OldType != New->getUnderlyingType() &&
925 Context.getCanonicalType(OldType) !=
Chris Lattner99cb9972008-07-25 18:44:27 +0000926 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000927 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Douglas Gregor66973122009-01-28 17:15:10 +0000928 << New->getUnderlyingType() << OldType;
Chris Lattnereaaebc72009-04-25 08:06:05 +0000929 if (Old->getLocation().isValid())
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000930 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000931 return New->setInvalidDecl();
Chris Lattner99cb9972008-07-25 18:44:27 +0000932 }
Mike Stump1eb44332009-09-09 15:08:12 +0000933
John McCall5126fd02009-12-30 00:31:22 +0000934 // The types match. Link up the redeclaration chain if the old
935 // declaration was a typedef.
936 // FIXME: this is a potential source of wierdness if the type
937 // spellings don't match exactly.
938 if (isa<TypedefDecl>(Old))
939 New->setPreviousDeclaration(cast<TypedefDecl>(Old));
940
Steve Naroff14108da2009-07-10 23:34:53 +0000941 if (getLangOptions().Microsoft)
Chris Lattnereaaebc72009-04-25 08:06:05 +0000942 return;
Eli Friedman54ecfce2008-06-11 06:20:39 +0000943
Chris Lattner32b06752009-04-17 22:04:20 +0000944 if (getLangOptions().CPlusPlus) {
Douglas Gregor93dda722010-01-11 21:54:40 +0000945 // C++ [dcl.typedef]p2:
946 // In a given non-class scope, a typedef specifier can be used to
947 // redefine the name of any type declared in that scope to refer
948 // to the type to which it already refers.
Chris Lattner32b06752009-04-17 22:04:20 +0000949 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnereaaebc72009-04-25 08:06:05 +0000950 return;
Douglas Gregor93dda722010-01-11 21:54:40 +0000951
952 // C++0x [dcl.typedef]p4:
953 // In a given class scope, a typedef specifier can be used to redefine
954 // any class-name declared in that scope that is not also a typedef-name
955 // to refer to the type to which it already refers.
956 //
957 // This wording came in via DR424, which was a correction to the
958 // wording in DR56, which accidentally banned code like:
959 //
960 // struct S {
961 // typedef struct A { } A;
962 // };
963 //
964 // in the C++03 standard. We implement the C++0x semantics, which
965 // allow the above but disallow
966 //
967 // struct S {
968 // typedef int I;
969 // typedef int I;
970 // };
971 //
972 // since that was the intent of DR56.
Douglas Gregor05f65002010-01-11 22:30:10 +0000973 if (!isa<TypedefDecl >(Old))
Douglas Gregor93dda722010-01-11 21:54:40 +0000974 return;
975
Chris Lattner32b06752009-04-17 22:04:20 +0000976 Diag(New->getLocation(), diag::err_redefinition)
977 << New->getDeclName();
978 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000979 return New->setInvalidDecl();
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000980 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000981
Chris Lattner32b06752009-04-17 22:04:20 +0000982 // If we have a redefinition of a typedef in C, emit a warning. This warning
983 // is normally mapped to an error, but can be controlled with
Eli Friedman340a4e52009-06-04 23:03:07 +0000984 // -Wtypedef-redefinition. If either the original or the redefinition is
985 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner6d97e5e2010-03-01 20:59:53 +0000986 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman340a4e52009-06-04 23:03:07 +0000987 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
988 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattnerd0359af2009-04-27 01:46:12 +0000989 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000990
Chris Lattner32b06752009-04-17 22:04:20 +0000991 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
992 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000993 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000994 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000995}
996
Chris Lattner6b6b5372008-06-26 18:38:35 +0000997/// DeclhasAttr - returns true if decl Declaration already has the target
998/// attribute.
Mike Stump1eb44332009-09-09 15:08:12 +0000999static bool
Sean Huntcf807c42010-08-18 23:23:40 +00001000DeclHasAttr(const Decl *D, const Attr *A) {
1001 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1002 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1003 if ((*i)->getKind() == A->getKind()) {
1004 // FIXME: Don't hardcode this check
1005 if (OA && isa<OwnershipAttr>(*i))
1006 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
Chris Lattnerddee4232008-03-03 03:28:21 +00001007 return true;
Sean Huntcf807c42010-08-18 23:23:40 +00001008 }
Chris Lattnerddee4232008-03-03 03:28:21 +00001009
1010 return false;
1011}
1012
Sean Huntcf807c42010-08-18 23:23:40 +00001013/// MergeDeclAttributes - append attributes from the Old decl to the New one.
1014static void MergeDeclAttributes(Decl *New, Decl *Old, ASTContext &C) {
1015 if (!Old->hasAttrs())
1016 return;
1017 // Ensure that any moving of objects within the allocated map is done before
1018 // we process them.
1019 if (!New->hasAttrs())
1020 New->setAttrs(AttrVec());
1021 for (Decl::attr_iterator i = Old->attr_begin(), e = Old->attr_end(); i != e;
1022 ++i) {
1023 // FIXME: Make this more general than just checking for Overloadable.
1024 if (!DeclHasAttr(New, *i) && (*i)->getKind() != attr::Overloadable) {
1025 Attr *NewAttr = (*i)->clone(C);
Douglas Gregor9f9bf252009-04-28 06:37:30 +00001026 NewAttr->setInherited(true);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001027 New->addAttr(NewAttr);
Chris Lattnerddee4232008-03-03 03:28:21 +00001028 }
1029 }
1030}
1031
Dan Gohman3c46e8d2010-07-26 21:25:24 +00001032namespace {
1033
Douglas Gregorc8376562009-03-06 22:43:54 +00001034/// Used in MergeFunctionDecl to keep track of function parameters in
1035/// C.
1036struct GNUCompatibleParamWarning {
1037 ParmVarDecl *OldParm;
1038 ParmVarDecl *NewParm;
1039 QualType PromotedType;
1040};
1041
Dan Gohman3c46e8d2010-07-26 21:25:24 +00001042}
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001043
1044/// getSpecialMember - get the special member enum for a method.
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00001045Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001046 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Douglas Gregor9e9199d2009-12-22 00:34:07 +00001047 if (Ctor->isCopyConstructor())
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001048 return Sema::CXXCopyConstructor;
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00001049
1050 return Sema::CXXConstructor;
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001051 }
1052
1053 if (isa<CXXDestructorDecl>(MD))
1054 return Sema::CXXDestructor;
1055
1056 assert(MD->isCopyAssignment() && "Must have copy assignment operator");
1057 return Sema::CXXCopyAssignment;
1058}
1059
Sebastian Redl515ddd82010-06-09 21:17:41 +00001060/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisf3f8d2a2010-02-18 02:00:42 +00001061/// only extern inline functions can be redefined, and even then only in
1062/// GNU89 mode.
1063static bool canRedefineFunction(const FunctionDecl *FD,
1064 const LangOptions& LangOpts) {
1065 return (LangOpts.GNUMode && !LangOpts.C99 && !LangOpts.CPlusPlus &&
1066 FD->isInlineSpecified() &&
1067 FD->getStorageClass() == FunctionDecl::Extern);
1068}
1069
Chris Lattner04421082008-04-08 04:40:51 +00001070/// MergeFunctionDecl - We just parsed a function 'New' from
1071/// declarator D which has the same name and scope as a previous
1072/// declaration 'Old'. Figure out how to resolve this situation,
1073/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001074///
1075/// In C++, New and Old must be declarations that are not
1076/// overloaded. Use IsOverload to determine whether New and Old are
1077/// overloaded, and to select the Old declaration that New should be
1078/// merged with.
Douglas Gregorcda9c672009-02-16 17:45:42 +00001079///
1080/// Returns true if there was an error, false otherwise.
1081bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001082 // Verify the old decl was also a function.
Douglas Gregore53060f2009-06-25 22:08:12 +00001083 FunctionDecl *Old = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001084 if (FunctionTemplateDecl *OldFunctionTemplate
Douglas Gregore53060f2009-06-25 22:08:12 +00001085 = dyn_cast<FunctionTemplateDecl>(OldD))
1086 Old = OldFunctionTemplate->getTemplatedDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001087 else
Douglas Gregore53060f2009-06-25 22:08:12 +00001088 Old = dyn_cast<FunctionDecl>(OldD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001089 if (!Old) {
John McCall41ce66f2009-12-10 19:51:03 +00001090 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
1091 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
1092 Diag(Shadow->getTargetDecl()->getLocation(),
1093 diag::note_using_decl_target);
1094 Diag(Shadow->getUsingDecl()->getLocation(),
1095 diag::note_using_decl) << 0;
1096 return true;
1097 }
1098
Chris Lattner5dc266a2008-11-20 06:13:02 +00001099 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00001100 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001101 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +00001102 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001103 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001104
1105 // Determine whether the previous declaration was a definition,
1106 // implicit declaration, or a declaration.
1107 diag::kind PrevDiag;
1108 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +00001109 PrevDiag = diag::note_previous_definition;
Douglas Gregorcda9c672009-02-16 17:45:42 +00001110 else if (Old->isImplicit())
1111 PrevDiag = diag::note_previous_implicit_declaration;
Mike Stump1eb44332009-09-09 15:08:12 +00001112 else
Chris Lattner5f4a6822008-11-23 23:12:31 +00001113 PrevDiag = diag::note_previous_declaration;
Mike Stump1eb44332009-09-09 15:08:12 +00001114
Chris Lattner8bcfc5b2008-04-06 23:10:54 +00001115 QualType OldQType = Context.getCanonicalType(Old->getType());
1116 QualType NewQType = Context.getCanonicalType(New->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001117
Charles Davisf3f8d2a2010-02-18 02:00:42 +00001118 // Don't complain about this if we're in GNU89 mode and the old function
1119 // is an extern inline function.
Douglas Gregor04495c82009-02-24 01:23:02 +00001120 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
1121 New->getStorageClass() == FunctionDecl::Static &&
Charles Davisf3f8d2a2010-02-18 02:00:42 +00001122 Old->getStorageClass() != FunctionDecl::Static &&
1123 !canRedefineFunction(Old, getLangOptions())) {
Douglas Gregor04495c82009-02-24 01:23:02 +00001124 Diag(New->getLocation(), diag::err_static_non_static)
1125 << New;
1126 Diag(Old->getLocation(), PrevDiag);
1127 return true;
1128 }
1129
John McCallf82b4e82010-02-04 05:44:44 +00001130 // If a function is first declared with a calling convention, but is
1131 // later declared or defined without one, the second decl assumes the
1132 // calling convention of the first.
1133 //
1134 // For the new decl, we have to look at the NON-canonical type to tell the
1135 // difference between a function that really doesn't have a calling
1136 // convention and one that is declared cdecl. That's because in
1137 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
1138 // because it is the default calling convention.
1139 //
1140 // Note also that we DO NOT return at this point, because we still have
1141 // other tests to run.
1142 const FunctionType *OldType = OldQType->getAs<FunctionType>();
1143 const FunctionType *NewType = New->getType()->getAs<FunctionType>();
Rafael Espindola264ba482010-03-30 20:24:48 +00001144 const FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
1145 const FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
1146 if (OldTypeInfo.getCC() != CC_Default &&
1147 NewTypeInfo.getCC() == CC_Default) {
1148 NewQType = Context.getCallConvType(NewQType, OldTypeInfo.getCC());
John McCallf82b4e82010-02-04 05:44:44 +00001149 New->setType(NewQType);
1150 NewQType = Context.getCanonicalType(NewQType);
Rafael Espindola264ba482010-03-30 20:24:48 +00001151 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
1152 NewTypeInfo.getCC())) {
John McCallf82b4e82010-02-04 05:44:44 +00001153 // Calling conventions really aren't compatible, so complain.
John McCall04a67a62010-02-05 21:31:56 +00001154 Diag(New->getLocation(), diag::err_cconv_change)
Rafael Espindola264ba482010-03-30 20:24:48 +00001155 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
1156 << (OldTypeInfo.getCC() == CC_Default)
1157 << (OldTypeInfo.getCC() == CC_Default ? "" :
1158 FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
John McCall04a67a62010-02-05 21:31:56 +00001159 Diag(Old->getLocation(), diag::note_previous_declaration);
John McCallf82b4e82010-02-04 05:44:44 +00001160 return true;
1161 }
1162
John McCall04a67a62010-02-05 21:31:56 +00001163 // FIXME: diagnose the other way around?
Douglas Gregord2c64902010-06-18 21:30:25 +00001164 if (OldType->getNoReturnAttr() && !NewType->getNoReturnAttr()) {
John McCall04a67a62010-02-05 21:31:56 +00001165 NewQType = Context.getNoReturnType(NewQType);
1166 New->setType(NewQType);
1167 assert(NewQType.isCanonical());
1168 }
1169
Douglas Gregord2c64902010-06-18 21:30:25 +00001170 // Merge regparm attribute.
1171 if (OldType->getRegParmType() != NewType->getRegParmType()) {
1172 if (NewType->getRegParmType()) {
1173 Diag(New->getLocation(), diag::err_regparm_mismatch)
1174 << NewType->getRegParmType()
1175 << OldType->getRegParmType();
1176 Diag(Old->getLocation(), diag::note_previous_declaration);
1177 return true;
1178 }
1179
1180 NewQType = Context.getRegParmType(NewQType, OldType->getRegParmType());
1181 New->setType(NewQType);
1182 assert(NewQType.isCanonical());
1183 }
1184
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001185 if (getLangOptions().CPlusPlus) {
1186 // (C++98 13.1p2):
1187 // Certain function declarations cannot be overloaded:
Mike Stump1eb44332009-09-09 15:08:12 +00001188 // -- Function declarations that differ only in the return type
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001189 // cannot be overloaded.
Mike Stump1eb44332009-09-09 15:08:12 +00001190 QualType OldReturnType
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001191 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001192 QualType NewReturnType
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001193 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
Fariborz Jahanian2390a722010-05-19 21:37:30 +00001194 QualType ResQT;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001195 if (OldReturnType != NewReturnType) {
Fariborz Jahanian2390a722010-05-19 21:37:30 +00001196 if (NewReturnType->isObjCObjectPointerType()
1197 && OldReturnType->isObjCObjectPointerType())
1198 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
1199 if (ResQT.isNull()) {
1200 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
1201 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1202 return true;
1203 }
1204 else
1205 NewQType = ResQT;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001206 }
1207
1208 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
John McCall3d043362010-04-13 07:45:41 +00001209 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001210 if (OldMethod && NewMethod) {
John McCall3d043362010-04-13 07:45:41 +00001211 // Preserve triviality.
1212 NewMethod->setTrivial(OldMethod->isTrivial());
1213
1214 bool isFriend = NewMethod->getFriendObjectKind();
1215
1216 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord()) {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001217 // -- Member function declarations with the same name and the
1218 // same parameter types cannot be overloaded if any of them
1219 // is a static member function declaration.
1220 if (OldMethod->isStatic() || NewMethod->isStatic()) {
1221 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
1222 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1223 return true;
1224 }
1225
1226 // C++ [class.mem]p1:
1227 // [...] A member shall not be declared twice in the
1228 // member-specification, except that a nested class or member
1229 // class template can be declared and then later defined.
1230 unsigned NewDiag;
1231 if (isa<CXXConstructorDecl>(OldMethod))
1232 NewDiag = diag::err_constructor_redeclared;
1233 else if (isa<CXXDestructorDecl>(NewMethod))
1234 NewDiag = diag::err_destructor_redeclared;
1235 else if (isa<CXXConversionDecl>(NewMethod))
1236 NewDiag = diag::err_conv_function_redeclared;
1237 else
1238 NewDiag = diag::err_member_redeclared;
1239
1240 Diag(New->getLocation(), NewDiag);
Douglas Gregor3e41d602009-02-13 23:20:09 +00001241 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
John McCall3d043362010-04-13 07:45:41 +00001242
1243 // Complain if this is an explicit declaration of a special
1244 // member that was initially declared implicitly.
1245 //
1246 // As an exception, it's okay to befriend such methods in order
1247 // to permit the implicit constructor/destructor/operator calls.
1248 } else if (OldMethod->isImplicit()) {
1249 if (isFriend) {
1250 NewMethod->setImplicit();
1251 } else {
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001252 Diag(NewMethod->getLocation(),
1253 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00001254 << New << getSpecialMember(OldMethod);
Anders Carlsson5c478cf2009-12-04 22:33:25 +00001255 return true;
1256 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001257 }
1258 }
1259
1260 // (C++98 8.3.5p3):
1261 // All declarations for a function shall agree exactly in both the
1262 // return type and the parameter-type-list.
Nuno Lopesf75b8302009-12-23 23:40:33 +00001263 // attributes should be ignored when comparing.
1264 if (Context.getNoReturnType(OldQType, false) ==
1265 Context.getNoReturnType(NewQType, false))
Douglas Gregor04495c82009-02-24 01:23:02 +00001266 return MergeCompatibleFunctionDecls(New, Old);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001267
1268 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +00001269 }
Chris Lattner04421082008-04-08 04:40:51 +00001270
1271 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001272 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +00001273 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +00001274 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall183700f2009-09-21 23:43:11 +00001275 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
1276 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001277 const FunctionProtoType *OldProto = 0;
1278 if (isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregorc8376562009-03-06 22:43:54 +00001279 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregor68719812009-02-16 18:20:44 +00001280 // The old declaration provided a function prototype, but the
1281 // new declaration does not. Merge in the prototype.
Sebastian Redl465226e2009-05-27 22:11:52 +00001282 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Douglas Gregor68719812009-02-16 18:20:44 +00001283 llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
1284 OldProto->arg_type_end());
1285 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001286 ParamTypes.data(), ParamTypes.size(),
Douglas Gregor68719812009-02-16 18:20:44 +00001287 OldProto->isVariadic(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00001288 OldProto->getTypeQuals(),
1289 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00001290 OldProto->getExtInfo());
Douglas Gregor68719812009-02-16 18:20:44 +00001291 New->setType(NewQType);
Anders Carlssona75e8532009-05-14 21:46:00 +00001292 New->setHasInheritedPrototype();
Douglas Gregor450da982009-02-16 20:58:07 +00001293
1294 // Synthesize a parameter for each argument type.
1295 llvm::SmallVector<ParmVarDecl*, 16> Params;
Mike Stump1eb44332009-09-09 15:08:12 +00001296 for (FunctionProtoType::arg_type_iterator
1297 ParamType = OldProto->arg_type_begin(),
Douglas Gregor450da982009-02-16 20:58:07 +00001298 ParamEnd = OldProto->arg_type_end();
1299 ParamType != ParamEnd; ++ParamType) {
1300 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
1301 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00001302 *ParamType, /*TInfo=*/0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001303 VarDecl::None, VarDecl::None,
1304 0);
Douglas Gregor450da982009-02-16 20:58:07 +00001305 Param->setImplicit();
1306 Params.push_back(Param);
1307 }
1308
Douglas Gregor838db382010-02-11 01:19:42 +00001309 New->setParams(Params.data(), Params.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001310 }
Douglas Gregor68719812009-02-16 18:20:44 +00001311
Douglas Gregor04495c82009-02-24 01:23:02 +00001312 return MergeCompatibleFunctionDecls(New, Old);
Chris Lattner04421082008-04-08 04:40:51 +00001313 }
Chris Lattnere3995fe2007-11-06 06:07:26 +00001314
Douglas Gregorc8376562009-03-06 22:43:54 +00001315 // GNU C permits a K&R definition to follow a prototype declaration
1316 // if the declared types of the parameters in the K&R definition
1317 // match the types in the prototype declaration, even when the
1318 // promoted types of the parameters from the K&R definition differ
1319 // from the types in the prototype. GCC then keeps the types from
1320 // the prototype.
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00001321 //
1322 // If a variadic prototype is followed by a non-variadic K&R definition,
1323 // the K&R definition becomes variadic. This is sort of an edge case, but
1324 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
1325 // C99 6.9.1p8.
Douglas Gregorc8376562009-03-06 22:43:54 +00001326 if (!getLangOptions().CPlusPlus &&
Douglas Gregorc8376562009-03-06 22:43:54 +00001327 Old->hasPrototype() && !New->hasPrototype() &&
John McCall183700f2009-09-21 23:43:11 +00001328 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregorc8376562009-03-06 22:43:54 +00001329 Old->getNumParams() == New->getNumParams()) {
1330 llvm::SmallVector<QualType, 16> ArgTypes;
1331 llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump1eb44332009-09-09 15:08:12 +00001332 const FunctionProtoType *OldProto
John McCall183700f2009-09-21 23:43:11 +00001333 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001334 const FunctionProtoType *NewProto
John McCall183700f2009-09-21 23:43:11 +00001335 = New->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001336
Douglas Gregorc8376562009-03-06 22:43:54 +00001337 // Determine whether this is the GNU C extension.
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00001338 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
1339 NewProto->getResultType());
1340 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump1eb44332009-09-09 15:08:12 +00001341 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00001342 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregorc8376562009-03-06 22:43:54 +00001343 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
1344 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump1eb44332009-09-09 15:08:12 +00001345 if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregorc8376562009-03-06 22:43:54 +00001346 NewProto->getArgType(Idx))) {
1347 ArgTypes.push_back(NewParm->getType());
1348 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor447234d2010-07-29 15:18:02 +00001349 NewParm->getType(),
1350 /*CompareUnqualified=*/true)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001351 GNUCompatibleParamWarning Warn
Douglas Gregorc8376562009-03-06 22:43:54 +00001352 = { OldParm, NewParm, NewProto->getArgType(Idx) };
1353 Warnings.push_back(Warn);
1354 ArgTypes.push_back(NewParm->getType());
1355 } else
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00001356 LooseCompatible = false;
Douglas Gregorc8376562009-03-06 22:43:54 +00001357 }
1358
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00001359 if (LooseCompatible) {
Douglas Gregorc8376562009-03-06 22:43:54 +00001360 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
1361 Diag(Warnings[Warn].NewParm->getLocation(),
1362 diag::ext_param_promoted_not_compatible_with_prototype)
1363 << Warnings[Warn].PromotedType
1364 << Warnings[Warn].OldParm->getType();
Douglas Gregor447234d2010-07-29 15:18:02 +00001365 if (Warnings[Warn].OldParm->getLocation().isValid())
1366 Diag(Warnings[Warn].OldParm->getLocation(),
1367 diag::note_previous_declaration);
Douglas Gregorc8376562009-03-06 22:43:54 +00001368 }
1369
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00001370 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
1371 ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00001372 OldProto->isVariadic(), 0,
1373 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00001374 OldProto->getExtInfo()));
Douglas Gregorc8376562009-03-06 22:43:54 +00001375 return MergeCompatibleFunctionDecls(New, Old);
1376 }
1377
1378 // Fall through to diagnose conflicting types.
1379 }
1380
Steve Naroff837618c2008-01-16 15:01:34 +00001381 // A function that has already been declared has been redeclared or defined
1382 // with a different type- show appropriate diagnostic
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001383 if (unsigned BuiltinID = Old->getBuiltinID()) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00001384 // The user has declared a builtin function with an incompatible
1385 // signature.
1386 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
1387 // The function the user is redeclaring is a library-defined
1388 // function like 'malloc' or 'printf'. Warn about the
Douglas Gregor374e1562009-03-23 17:47:24 +00001389 // redeclaration, then pretend that we don't know about this
1390 // library built-in.
Douglas Gregorcda9c672009-02-16 17:45:42 +00001391 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
1392 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
1393 << Old << Old->getType();
Douglas Gregor374e1562009-03-23 17:47:24 +00001394 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
1395 Old->setInvalidDecl();
1396 return false;
Douglas Gregorcda9c672009-02-16 17:45:42 +00001397 }
Steve Naroff837618c2008-01-16 15:01:34 +00001398
Douglas Gregorcda9c672009-02-16 17:45:42 +00001399 PrevDiag = diag::note_previous_builtin_declaration;
1400 }
1401
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001402 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregor3e41d602009-02-13 23:20:09 +00001403 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregorcda9c672009-02-16 17:45:42 +00001404 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001405}
1406
Douglas Gregor04495c82009-02-24 01:23:02 +00001407/// \brief Completes the merge of two function declarations that are
Mike Stump1eb44332009-09-09 15:08:12 +00001408/// known to be compatible.
Douglas Gregor04495c82009-02-24 01:23:02 +00001409///
1410/// This routine handles the merging of attributes and other
1411/// properties of function declarations form the old declaration to
1412/// the new declaration, once we know that New is in fact a
1413/// redeclaration of Old.
1414///
1415/// \returns false
1416bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
1417 // Merge the attributes
Sean Huntcf807c42010-08-18 23:23:40 +00001418 MergeDeclAttributes(New, Old, Context);
Douglas Gregor04495c82009-02-24 01:23:02 +00001419
1420 // Merge the storage class.
Douglas Gregor1fc09a92009-09-13 07:46:26 +00001421 if (Old->getStorageClass() != FunctionDecl::Extern &&
1422 Old->getStorageClass() != FunctionDecl::None)
Douglas Gregor9f9bf252009-04-28 06:37:30 +00001423 New->setStorageClass(Old->getStorageClass());
Douglas Gregor04495c82009-02-24 01:23:02 +00001424
Douglas Gregor04495c82009-02-24 01:23:02 +00001425 // Merge "pure" flag.
1426 if (Old->isPure())
1427 New->setPure();
1428
1429 // Merge the "deleted" flag.
1430 if (Old->isDeleted())
1431 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001432
Douglas Gregor04495c82009-02-24 01:23:02 +00001433 if (getLangOptions().CPlusPlus)
1434 return MergeCXXFunctionDecl(New, Old);
1435
1436 return false;
1437}
1438
Reid Spencer5f016e22007-07-11 17:01:13 +00001439/// MergeVarDecl - We just parsed a variable 'New' which has the same name
1440/// and scope as a previous declaration 'Old'. Figure out how to resolve this
1441/// situation, merging decls or emitting diagnostics as appropriate.
1442///
Mike Stump1eb44332009-09-09 15:08:12 +00001443/// Tentative definition rules (C99 6.9.2p2) are checked by
1444/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001445/// definitions here, since the initializer hasn't been attached.
Mike Stump1eb44332009-09-09 15:08:12 +00001446///
John McCall68263142009-11-18 22:49:29 +00001447void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
1448 // If the new decl is already invalid, don't do any other checking.
1449 if (New->isInvalidDecl())
1450 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001451
Reid Spencer5f016e22007-07-11 17:01:13 +00001452 // Verify the old decl was also a variable.
John McCall68263142009-11-18 22:49:29 +00001453 VarDecl *Old = 0;
1454 if (!Previous.isSingleResult() ||
1455 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001456 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +00001457 << New->getDeclName();
John McCall68263142009-11-18 22:49:29 +00001458 Diag(Previous.getRepresentativeDecl()->getLocation(),
1459 diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001460 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001461 }
Chris Lattnerddee4232008-03-03 03:28:21 +00001462
Sean Huntcf807c42010-08-18 23:23:40 +00001463 MergeDeclAttributes(New, Old, Context);
Chris Lattnerddee4232008-03-03 03:28:21 +00001464
Eli Friedman13ca96a2009-01-24 23:49:55 +00001465 // Merge the types
Eli Friedman88d936b2009-05-16 13:54:38 +00001466 QualType MergedT;
1467 if (getLangOptions().CPlusPlus) {
1468 if (Context.hasSameType(New->getType(), Old->getType()))
1469 MergedT = New->getType();
Eli Friedman153c33e2009-12-10 08:54:47 +00001470 // C++ [basic.link]p10:
1471 // [...] the types specified by all declarations referring to a given
1472 // object or function shall be identical, except that declarations for an
1473 // array object can specify array types that differ by the presence or
1474 // absence of a major array bound (8.3.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001475 else if (Old->getType()->isIncompleteArrayType() &&
Douglas Gregor8dfb7ec2009-09-09 06:04:29 +00001476 New->getType()->isArrayType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001477 CanQual<ArrayType> OldArray
Douglas Gregor8dfb7ec2009-09-09 06:04:29 +00001478 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001479 CanQual<ArrayType> NewArray
Douglas Gregor8dfb7ec2009-09-09 06:04:29 +00001480 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1481 if (OldArray->getElementType() == NewArray->getElementType())
1482 MergedT = New->getType();
Eli Friedman153c33e2009-12-10 08:54:47 +00001483 } else if (Old->getType()->isArrayType() &&
1484 New->getType()->isIncompleteArrayType()) {
1485 CanQual<ArrayType> OldArray
1486 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1487 CanQual<ArrayType> NewArray
1488 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1489 if (OldArray->getElementType() == NewArray->getElementType())
1490 MergedT = Old->getType();
Fariborz Jahanian2390a722010-05-19 21:37:30 +00001491 } else if (New->getType()->isObjCObjectPointerType()
1492 && Old->getType()->isObjCObjectPointerType()) {
1493 MergedT = Context.mergeObjCGCQualifiers(New->getType(), Old->getType());
Douglas Gregor8dfb7ec2009-09-09 06:04:29 +00001494 }
Eli Friedman88d936b2009-05-16 13:54:38 +00001495 } else {
1496 MergedT = Context.mergeTypes(New->getType(), Old->getType());
1497 }
Eli Friedman13ca96a2009-01-24 23:49:55 +00001498 if (MergedT.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001499 Diag(New->getLocation(), diag::err_redefinition_different_type)
Douglas Gregor6037fcb2009-01-09 19:42:16 +00001500 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001501 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001502 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001503 }
Eli Friedman13ca96a2009-01-24 23:49:55 +00001504 New->setType(MergedT);
Douglas Gregor656de632009-03-11 23:52:16 +00001505
Steve Naroffb7b032e2008-01-30 00:44:01 +00001506 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
1507 if (New->getStorageClass() == VarDecl::Static &&
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00001508 (Old->getStorageClass() == VarDecl::None || Old->hasExternalStorage())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001509 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001510 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001511 return New->setInvalidDecl();
Steve Naroffb7b032e2008-01-30 00:44:01 +00001512 }
Mike Stump1eb44332009-09-09 15:08:12 +00001513 // C99 6.2.2p4:
Douglas Gregor5ef122e2009-03-19 22:01:50 +00001514 // For an identifier declared with the storage-class specifier
1515 // extern in a scope in which a prior declaration of that
1516 // identifier is visible,23) if the prior declaration specifies
1517 // internal or external linkage, the linkage of the identifier at
1518 // the later declaration is the same as the linkage specified at
1519 // the prior declaration. If no prior declaration is visible, or
1520 // if the prior declaration specifies no linkage, then the
1521 // identifier has external linkage.
Douglas Gregor38179b22009-03-23 16:17:01 +00001522 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor5ef122e2009-03-19 22:01:50 +00001523 /* Okay */;
1524 else if (New->getStorageClass() != VarDecl::Static &&
1525 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001526 Diag(New->getLocation(), diag::err_non_static_static) << 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();
Steve Naroffb7b032e2008-01-30 00:44:01 +00001529 }
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00001530
Steve Naroff094cefb2008-09-17 14:05:40 +00001531 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump1eb44332009-09-09 15:08:12 +00001532
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00001533 // FIXME: The test for external storage here seems wrong? We still
1534 // need to check for mismatches.
1535 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor656de632009-03-11 23:52:16 +00001536 // Don't complain about out-of-line definitions of static members.
1537 !(Old->getLexicalDeclContext()->isRecord() &&
1538 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattner08631c52008-11-23 21:45:46 +00001539 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001540 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnereaaebc72009-04-25 08:06:05 +00001541 return New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001542 }
Douglas Gregor275a3692009-03-10 23:43:53 +00001543
Eli Friedman63054b32009-04-19 20:27:55 +00001544 if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
1545 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
1546 Diag(Old->getLocation(), diag::note_previous_definition);
1547 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
1548 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
1549 Diag(Old->getLocation(), diag::note_previous_definition);
1550 }
1551
Sebastian Redl4cae1b32010-02-02 18:35:11 +00001552 // C++ doesn't have tentative definitions, so go right ahead and check here.
1553 const VarDecl *Def;
Sebastian Redl6c048a92010-02-03 02:08:48 +00001554 if (getLangOptions().CPlusPlus &&
1555 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redl4cae1b32010-02-02 18:35:11 +00001556 (Def = Old->getDefinition())) {
1557 Diag(New->getLocation(), diag::err_redefinition)
1558 << New->getDeclName();
1559 Diag(Def->getLocation(), diag::note_previous_definition);
1560 New->setInvalidDecl();
1561 return;
1562 }
Fariborz Jahanianfba9e8f2010-06-25 00:05:45 +00001563 // c99 6.2.2 P4.
1564 // For an identifier declared with the storage-class specifier extern in a
1565 // scope in which a prior declaration of that identifier is visible, if
1566 // the prior declaration specifies internal or external linkage, the linkage
1567 // of the identifier at the later declaration is the same as the linkage
1568 // specified at the prior declaration.
1569 // FIXME. revisit this code.
Fariborz Jahanian2bf6d7b2010-06-21 16:08:37 +00001570 if (New->hasExternalStorage() &&
Fariborz Jahanian7d99e982010-06-24 18:50:41 +00001571 Old->getLinkage() == InternalLinkage &&
1572 New->getDeclContext() == Old->getDeclContext())
Fariborz Jahanian2bf6d7b2010-06-21 16:08:37 +00001573 New->setStorageClass(Old->getStorageClass());
1574
Douglas Gregor275a3692009-03-10 23:43:53 +00001575 // Keep a chain of previous declarations.
1576 New->setPreviousDeclaration(Old);
John McCall46460a62010-01-20 21:53:11 +00001577
1578 // Inherit access appropriately.
1579 New->setAccess(Old->getAccess());
Reid Spencer5f016e22007-07-11 17:01:13 +00001580}
1581
1582/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
1583/// no declarator (e.g. "struct foo;") is parsed.
John McCallaec03712010-05-21 20:45:30 +00001584Sema::DeclPtrTy Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1585 DeclSpec &DS) {
Eli Friedmand2968362009-04-09 21:26:42 +00001586 // FIXME: Error on auto/register at file scope
1587 // FIXME: Error on inline/virtual/explicit
Eli Friedman63054b32009-04-19 20:27:55 +00001588 // FIXME: Warn on useless __thread
Eli Friedmand2968362009-04-09 21:26:42 +00001589 // FIXME: Warn on useless const/volatile
1590 // FIXME: Warn on useless static/extern/typedef/private_extern/mutable
1591 // FIXME: Warn on useless attributes
John McCalle3af0232009-10-07 23:34:25 +00001592 Decl *TagD = 0;
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001593 TagDecl *Tag = 0;
1594 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
1595 DS.getTypeSpecType() == DeclSpec::TST_struct ||
1596 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00001597 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCalle3af0232009-10-07 23:34:25 +00001598 TagD = static_cast<Decl *>(DS.getTypeRep());
1599
1600 if (!TagD) // We probably had an error
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00001601 return DeclPtrTy();
1602
John McCall67d1a672009-08-06 02:15:43 +00001603 // Note that the above type specs guarantee that the
1604 // type rep is a Decl, whereas in many of the others
1605 // it's a Type.
John McCalle3af0232009-10-07 23:34:25 +00001606 Tag = dyn_cast<TagDecl>(TagD);
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00001607 }
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001608
Nuno Lopes0a8bab02009-12-17 11:35:26 +00001609 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1610 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
1611 // or incomplete types shall not be restrict-qualified."
1612 if (TypeQuals & DeclSpec::TQ_restrict)
1613 Diag(DS.getRestrictSpecLoc(),
1614 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
1615 << DS.getSourceRange();
1616 }
1617
Douglas Gregord85bea22009-09-26 06:47:28 +00001618 if (DS.isFriendSpecified()) {
John McCalle3af0232009-10-07 23:34:25 +00001619 // If we're dealing with a class template decl, assume that the
1620 // template routines are handling it.
1621 if (TagD && isa<ClassTemplateDecl>(TagD))
Douglas Gregord85bea22009-09-26 06:47:28 +00001622 return DeclPtrTy();
John McCalle3af0232009-10-07 23:34:25 +00001623 return ActOnFriendTypeDecl(S, DS, MultiTemplateParamsArg(*this, 0, 0));
Douglas Gregord85bea22009-09-26 06:47:28 +00001624 }
1625
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001626 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
Sean Huntcf807c42010-08-18 23:23:40 +00001627 ProcessDeclAttributeList(S, Record, DS.getAttributes());
Chris Lattnerd451f832009-10-25 22:21:57 +00001628
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001629 if (!Record->getDeclName() && Record->isDefinition() &&
Douglas Gregora71c1292009-03-06 23:06:59 +00001630 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
1631 if (getLangOptions().CPlusPlus ||
1632 Record->getDeclContext()->isRecord())
John McCallaec03712010-05-21 20:45:30 +00001633 return BuildAnonymousStructOrUnion(S, DS, AS, Record);
Douglas Gregora71c1292009-03-06 23:06:59 +00001634
Douglas Gregorcb821d02010-04-08 21:33:23 +00001635 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
Douglas Gregora71c1292009-03-06 23:06:59 +00001636 << DS.getSourceRange();
1637 }
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001638
1639 // Microsoft allows unnamed struct/union fields. Don't complain
1640 // about them.
1641 // FIXME: Should we support Microsoft's extensions in this area?
1642 if (Record->getDeclName() && getLangOptions().Microsoft)
Chris Lattnerb28317a2009-03-28 19:18:32 +00001643 return DeclPtrTy::make(Tag);
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001644 }
Douglas Gregord85bea22009-09-26 06:47:28 +00001645
Douglas Gregora131d0f2010-07-13 06:24:26 +00001646 if (getLangOptions().CPlusPlus &&
1647 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
1648 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
1649 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
1650 !Enum->getIdentifier() && !Enum->isInvalidDecl())
1651 Diag(Enum->getLocation(), diag::ext_no_declarators)
1652 << DS.getSourceRange();
1653
Mike Stump1eb44332009-09-09 15:08:12 +00001654 if (!DS.isMissingDeclaratorOk() &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00001655 DS.getTypeSpecType() != DeclSpec::TST_error) {
Douglas Gregor21282df2009-01-22 16:23:54 +00001656 // Warn about typedefs of enums without names, since this is an
Douglas Gregora0ebd602010-07-16 15:40:40 +00001657 // extension in both Microsoft and GNU.
Douglas Gregor8158f692009-01-17 02:55:50 +00001658 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
1659 Tag && isa<EnumDecl>(Tag)) {
Douglas Gregora0ebd602010-07-16 15:40:40 +00001660 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
1661 << DS.getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00001662 return DeclPtrTy::make(Tag);
Douglas Gregoree159c12009-01-13 23:10:51 +00001663 }
1664
Douglas Gregorcb821d02010-04-08 21:33:23 +00001665 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
Sebastian Redla4ed0d82008-12-28 15:28:59 +00001666 << DS.getSourceRange();
Sebastian Redla4ed0d82008-12-28 15:28:59 +00001667 }
Mike Stump1eb44332009-09-09 15:08:12 +00001668
John McCallc9068d72010-07-16 08:13:16 +00001669 return DeclPtrTy::make(TagD);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001670}
1671
John McCall1d7c5282009-12-18 10:40:03 +00001672/// We are trying to inject an anonymous member into the given scope;
John McCall68263142009-11-18 22:49:29 +00001673/// check if there's an existing declaration that can't be overloaded.
1674///
1675/// \return true if this is a forbidden redeclaration
John McCall1d7c5282009-12-18 10:40:03 +00001676static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
1677 Scope *S,
Fariborz Jahanian588a4ad2010-01-22 18:30:17 +00001678 DeclContext *Owner,
John McCall1d7c5282009-12-18 10:40:03 +00001679 DeclarationName Name,
1680 SourceLocation NameLoc,
1681 unsigned diagnostic) {
1682 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
1683 Sema::ForRedeclaration);
1684 if (!SemaRef.LookupName(R, S)) return false;
John McCall68263142009-11-18 22:49:29 +00001685
John McCall1d7c5282009-12-18 10:40:03 +00001686 if (R.getAsSingle<TagDecl>())
John McCall68263142009-11-18 22:49:29 +00001687 return false;
1688
1689 // Pick a representative declaration.
John McCall1d7c5282009-12-18 10:40:03 +00001690 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Fariborz Jahanian588a4ad2010-01-22 18:30:17 +00001691 if (PrevDecl && Owner->isRecord()) {
1692 RecordDecl *Record = cast<RecordDecl>(Owner);
1693 if (!SemaRef.isDeclInScope(PrevDecl, Record, S))
1694 return false;
1695 }
John McCall68263142009-11-18 22:49:29 +00001696
John McCall1d7c5282009-12-18 10:40:03 +00001697 SemaRef.Diag(NameLoc, diagnostic) << Name;
1698 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall68263142009-11-18 22:49:29 +00001699
1700 return true;
1701}
1702
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001703/// InjectAnonymousStructOrUnionMembers - Inject the members of the
1704/// anonymous struct or union AnonRecord into the owning context Owner
1705/// and scope S. This routine will be invoked just after we realize
1706/// that an unnamed union or struct is actually an anonymous union or
1707/// struct, e.g.,
1708///
1709/// @code
1710/// union {
1711/// int i;
1712/// float f;
1713/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
1714/// // f into the surrounding scope.x
1715/// @endcode
1716///
1717/// This routine is recursive, injecting the names of nested anonymous
1718/// structs/unions into the owning context and scope as well.
John McCallaec03712010-05-21 20:45:30 +00001719static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
1720 DeclContext *Owner,
1721 RecordDecl *AnonRecord,
1722 AccessSpecifier AS) {
John McCall68263142009-11-18 22:49:29 +00001723 unsigned diagKind
1724 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
1725 : diag::err_anonymous_struct_member_redecl;
1726
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001727 bool Invalid = false;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001728 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
1729 FEnd = AnonRecord->field_end();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001730 F != FEnd; ++F) {
1731 if ((*F)->getDeclName()) {
John McCallaec03712010-05-21 20:45:30 +00001732 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, (*F)->getDeclName(),
John McCall1d7c5282009-12-18 10:40:03 +00001733 (*F)->getLocation(), diagKind)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001734 // C++ [class.union]p2:
1735 // The names of the members of an anonymous union shall be
1736 // distinct from the names of any other entity in the
1737 // scope in which the anonymous union is declared.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001738 Invalid = true;
1739 } else {
1740 // C++ [class.union]p2:
1741 // For the purpose of name lookup, after the anonymous union
1742 // definition, the members of the anonymous union are
1743 // considered to have been defined in the scope in which the
1744 // anonymous union is declared.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001745 Owner->makeDeclVisibleInContext(*F);
John McCallaec03712010-05-21 20:45:30 +00001746 S->AddDecl(Sema::DeclPtrTy::make(*F));
1747 SemaRef.IdResolver.AddDecl(*F);
1748
1749 // That includes picking up the appropriate access specifier.
1750 if (AS != AS_none) (*F)->setAccess(AS);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001751 }
1752 } else if (const RecordType *InnerRecordType
Ted Kremenek6217b802009-07-29 21:53:49 +00001753 = (*F)->getType()->getAs<RecordType>()) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001754 RecordDecl *InnerRecord = InnerRecordType->getDecl();
1755 if (InnerRecord->isAnonymousStructOrUnion())
Mike Stump1eb44332009-09-09 15:08:12 +00001756 Invalid = Invalid ||
John McCallaec03712010-05-21 20:45:30 +00001757 InjectAnonymousStructOrUnionMembers(SemaRef, S, Owner,
1758 InnerRecord, AS);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001759 }
1760 }
1761
1762 return Invalid;
1763}
1764
Douglas Gregor16573fa2010-04-19 22:54:31 +00001765/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
1766/// a VarDecl::StorageClass. Any error reporting is up to the caller:
1767/// illegal input values are mapped to VarDecl::None.
1768static VarDecl::StorageClass
Abramo Bagnara35f9a192010-07-30 16:47:02 +00001769StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
Douglas Gregor16573fa2010-04-19 22:54:31 +00001770 switch (StorageClassSpec) {
1771 case DeclSpec::SCS_unspecified: return VarDecl::None;
Abramo Bagnara35f9a192010-07-30 16:47:02 +00001772 case DeclSpec::SCS_extern: return VarDecl::Extern;
Douglas Gregor16573fa2010-04-19 22:54:31 +00001773 case DeclSpec::SCS_static: return VarDecl::Static;
1774 case DeclSpec::SCS_auto: return VarDecl::Auto;
1775 case DeclSpec::SCS_register: return VarDecl::Register;
1776 case DeclSpec::SCS_private_extern: return VarDecl::PrivateExtern;
1777 // Illegal SCSs map to None: error reporting is up to the caller.
1778 case DeclSpec::SCS_mutable: // Fall through.
1779 case DeclSpec::SCS_typedef: return VarDecl::None;
1780 }
1781 llvm_unreachable("unknown storage class specifier");
1782}
1783
1784/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
1785/// a FunctionDecl::StorageClass. Any error reporting is up to the caller:
1786/// illegal input values are mapped to FunctionDecl::None.
1787static FunctionDecl::StorageClass
Abramo Bagnara35f9a192010-07-30 16:47:02 +00001788StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
Douglas Gregor16573fa2010-04-19 22:54:31 +00001789 switch (StorageClassSpec) {
1790 case DeclSpec::SCS_unspecified: return FunctionDecl::None;
Abramo Bagnara35f9a192010-07-30 16:47:02 +00001791 case DeclSpec::SCS_extern: return FunctionDecl::Extern;
Douglas Gregor16573fa2010-04-19 22:54:31 +00001792 case DeclSpec::SCS_static: return FunctionDecl::Static;
1793 case DeclSpec::SCS_private_extern: return FunctionDecl::PrivateExtern;
1794 // Illegal SCSs map to None: error reporting is up to the caller.
1795 case DeclSpec::SCS_auto: // Fall through.
1796 case DeclSpec::SCS_mutable: // Fall through.
1797 case DeclSpec::SCS_register: // Fall through.
1798 case DeclSpec::SCS_typedef: return FunctionDecl::None;
1799 }
1800 llvm_unreachable("unknown storage class specifier");
1801}
1802
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001803/// ActOnAnonymousStructOrUnion - Handle the declaration of an
1804/// anonymous structure or union. Anonymous unions are a C++ feature
1805/// (C++ [class.union]) and a GNU C extension; anonymous structures
Mike Stump1eb44332009-09-09 15:08:12 +00001806/// are a GNU C and GNU C++ extension.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001807Sema::DeclPtrTy Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
John McCallaec03712010-05-21 20:45:30 +00001808 AccessSpecifier AS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001809 RecordDecl *Record) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001810 DeclContext *Owner = Record->getDeclContext();
1811
1812 // Diagnose whether this anonymous struct/union is an extension.
1813 if (Record->isUnion() && !getLangOptions().CPlusPlus)
1814 Diag(Record->getLocation(), diag::ext_anonymous_union);
1815 else if (!Record->isUnion())
1816 Diag(Record->getLocation(), diag::ext_anonymous_struct);
Mike Stump1eb44332009-09-09 15:08:12 +00001817
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001818 // C and C++ require different kinds of checks for anonymous
1819 // structs/unions.
1820 bool Invalid = false;
1821 if (getLangOptions().CPlusPlus) {
1822 const char* PrevSpec = 0;
John McCallfec54012009-08-03 20:12:06 +00001823 unsigned DiagID;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001824 // C++ [class.union]p3:
1825 // Anonymous unions declared in a named namespace or in the
1826 // global namespace shall be declared static.
1827 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
1828 (isa<TranslationUnitDecl>(Owner) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001829 (isa<NamespaceDecl>(Owner) &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001830 cast<NamespaceDecl>(Owner)->getDeclName()))) {
1831 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
1832 Invalid = true;
1833
1834 // Recover by adding 'static'.
John McCallfec54012009-08-03 20:12:06 +00001835 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(),
1836 PrevSpec, DiagID);
Mike Stump1eb44332009-09-09 15:08:12 +00001837 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001838 // C++ [class.union]p3:
1839 // A storage class is not allowed in a declaration of an
1840 // anonymous union in a class scope.
1841 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1842 isa<RecordDecl>(Owner)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001843 Diag(DS.getStorageClassSpecLoc(),
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001844 diag::err_anonymous_union_with_storage_spec);
1845 Invalid = true;
1846
1847 // Recover by removing the storage specifier.
1848 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
John McCallfec54012009-08-03 20:12:06 +00001849 PrevSpec, DiagID);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001850 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001851
Mike Stump1eb44332009-09-09 15:08:12 +00001852 // C++ [class.union]p2:
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001853 // The member-specification of an anonymous union shall only
1854 // define non-static data members. [Note: nested types and
1855 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001856 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
1857 MemEnd = Record->decls_end();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001858 Mem != MemEnd; ++Mem) {
1859 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
1860 // C++ [class.union]p3:
1861 // An anonymous union shall not have private or protected
1862 // members (clause 11).
John McCallaec03712010-05-21 20:45:30 +00001863 assert(FD->getAccess() != AS_none);
1864 if (FD->getAccess() != AS_public) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001865 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
1866 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
1867 Invalid = true;
1868 }
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +00001869
1870 if (CheckNontrivialField(FD))
1871 Invalid = true;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001872 } else if ((*Mem)->isImplicit()) {
1873 // Any implicit members are fine.
Douglas Gregor1931b442009-02-03 00:34:39 +00001874 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
1875 // This is a type that showed up in an
1876 // elaborated-type-specifier inside the anonymous struct or
1877 // union, but which actually declares a type outside of the
1878 // anonymous struct or union. It's okay.
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001879 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
1880 if (!MemRecord->isAnonymousStructOrUnion() &&
1881 MemRecord->getDeclName()) {
1882 // This is a nested type declaration.
1883 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
1884 << (int)Record->isUnion();
1885 Invalid = true;
1886 }
Abramo Bagnara6206d532010-06-05 05:09:32 +00001887 } else if (isa<AccessSpecDecl>(*Mem)) {
1888 // Any access specifier is fine.
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001889 } else {
1890 // We have something that isn't a non-static data
1891 // member. Complain about it.
1892 unsigned DK = diag::err_anonymous_record_bad_member;
1893 if (isa<TypeDecl>(*Mem))
1894 DK = diag::err_anonymous_record_with_type;
1895 else if (isa<FunctionDecl>(*Mem))
1896 DK = diag::err_anonymous_record_with_function;
1897 else if (isa<VarDecl>(*Mem))
1898 DK = diag::err_anonymous_record_with_static;
1899 Diag((*Mem)->getLocation(), DK)
1900 << (int)Record->isUnion();
1901 Invalid = true;
1902 }
1903 }
Mike Stump1eb44332009-09-09 15:08:12 +00001904 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001905
1906 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001907 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
1908 << (int)getLangOptions().CPlusPlus;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001909 Invalid = true;
1910 }
1911
John McCalleb692e02009-10-22 23:31:08 +00001912 // Mock up a declarator.
1913 Declarator Dc(DS, Declarator::TypeNameContext);
John McCallbf1a0282010-06-04 23:28:52 +00001914 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCalla93c9342009-12-07 02:54:59 +00001915 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCalleb692e02009-10-22 23:31:08 +00001916
Mike Stump1eb44332009-09-09 15:08:12 +00001917 // Create a declaration for this anonymous struct/union.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001918 NamedDecl *Anon = 0;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001919 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
1920 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001921 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00001922 Context.getTypeDeclType(Record),
John McCalla93c9342009-12-07 02:54:59 +00001923 TInfo,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00001924 /*BitWidth=*/0, /*Mutable=*/false);
John McCallaec03712010-05-21 20:45:30 +00001925 Anon->setAccess(AS);
Douglas Gregorfe60f842010-05-03 15:18:25 +00001926 if (getLangOptions().CPlusPlus) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001927 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregorfe60f842010-05-03 15:18:25 +00001928 if (!cast<CXXRecordDecl>(Record)->isEmpty())
1929 cast<CXXRecordDecl>(OwningClass)->setEmpty(false);
1930 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001931 } else {
Douglas Gregor16573fa2010-04-19 22:54:31 +00001932 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
1933 assert(SCSpec != DeclSpec::SCS_typedef &&
1934 "Parser allowed 'typedef' as storage class VarDecl.");
Abramo Bagnara35f9a192010-07-30 16:47:02 +00001935 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregor16573fa2010-04-19 22:54:31 +00001936 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001937 // mutable can only appear on non-static class members, so it's always
1938 // an error here
1939 Diag(Record->getLocation(), diag::err_mutable_nonmember);
1940 Invalid = true;
1941 SC = VarDecl::None;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001942 }
Douglas Gregor16573fa2010-04-19 22:54:31 +00001943 SCSpec = DS.getStorageClassSpecAsWritten();
1944 VarDecl::StorageClass SCAsWritten
Abramo Bagnara35f9a192010-07-30 16:47:02 +00001945 = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001946
1947 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001948 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00001949 Context.getTypeDeclType(Record),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001950 TInfo, SC, SCAsWritten);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001951 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001952 Anon->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001953
1954 // Add the anonymous struct/union object to the current
1955 // context. We'll be referencing this object when we refer to one of
1956 // its members.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001957 Owner->addDecl(Anon);
Douglas Gregorfe60f842010-05-03 15:18:25 +00001958
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001959 // Inject the members of the anonymous struct/union into the owning
1960 // context and into the identifier resolver chain for name lookup
1961 // purposes.
John McCallaec03712010-05-21 20:45:30 +00001962 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS))
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001963 Invalid = true;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001964
1965 // Mark this as an anonymous struct/union type. Note that we do not
1966 // do this until after we have already checked and injected the
1967 // members of this anonymous struct/union type, because otherwise
1968 // the members could be injected twice: once by DeclContext when it
1969 // builds its lookup table, and once by
Mike Stump1eb44332009-09-09 15:08:12 +00001970 // InjectAnonymousStructOrUnionMembers.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001971 Record->setAnonymousStructOrUnion(true);
1972
1973 if (Invalid)
1974 Anon->setInvalidDecl();
1975
Chris Lattnerb28317a2009-03-28 19:18:32 +00001976 return DeclPtrTy::make(Anon);
Reid Spencer5f016e22007-07-11 17:01:13 +00001977}
1978
Steve Narofff0090632007-09-02 02:04:30 +00001979
Douglas Gregor10bd3682008-11-17 22:58:34 +00001980/// GetNameForDeclarator - Determine the full declaration name for the
1981/// given Declarator.
Abramo Bagnara25777432010-08-11 22:01:17 +00001982DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregor02a24ee2009-11-03 16:56:39 +00001983 return GetNameFromUnqualifiedId(D.getName());
1984}
1985
Abramo Bagnara25777432010-08-11 22:01:17 +00001986/// \brief Retrieves the declaration name from a parsed unqualified-id.
1987DeclarationNameInfo
1988Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
1989 DeclarationNameInfo NameInfo;
1990 NameInfo.setLoc(Name.StartLocation);
1991
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001992 switch (Name.getKind()) {
Sean Hunt0486d742009-11-28 04:44:28 +00001993
Abramo Bagnara25777432010-08-11 22:01:17 +00001994 case UnqualifiedId::IK_Identifier:
1995 NameInfo.setName(Name.Identifier);
1996 NameInfo.setLoc(Name.StartLocation);
1997 return NameInfo;
Sean Hunt0486d742009-11-28 04:44:28 +00001998
Abramo Bagnara25777432010-08-11 22:01:17 +00001999 case UnqualifiedId::IK_OperatorFunctionId:
2000 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
2001 Name.OperatorFunctionId.Operator));
2002 NameInfo.setLoc(Name.StartLocation);
2003 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
2004 = Name.OperatorFunctionId.SymbolLocations[0];
2005 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
2006 = Name.EndLocation.getRawEncoding();
2007 return NameInfo;
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002008
Abramo Bagnara25777432010-08-11 22:01:17 +00002009 case UnqualifiedId::IK_LiteralOperatorId:
2010 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
2011 Name.Identifier));
2012 NameInfo.setLoc(Name.StartLocation);
2013 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
2014 return NameInfo;
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002015
Abramo Bagnara25777432010-08-11 22:01:17 +00002016 case UnqualifiedId::IK_ConversionFunctionId: {
2017 TypeSourceInfo *TInfo;
2018 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
2019 if (Ty.isNull())
2020 return DeclarationNameInfo();
2021 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
2022 Context.getCanonicalType(Ty)));
2023 NameInfo.setLoc(Name.StartLocation);
2024 NameInfo.setNamedTypeInfo(TInfo);
2025 return NameInfo;
Douglas Gregordb422df2009-09-25 21:45:23 +00002026 }
Abramo Bagnara25777432010-08-11 22:01:17 +00002027
2028 case UnqualifiedId::IK_ConstructorName: {
2029 TypeSourceInfo *TInfo;
2030 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
2031 if (Ty.isNull())
2032 return DeclarationNameInfo();
2033 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
2034 Context.getCanonicalType(Ty)));
2035 NameInfo.setLoc(Name.StartLocation);
2036 NameInfo.setNamedTypeInfo(TInfo);
2037 return NameInfo;
2038 }
2039
2040 case UnqualifiedId::IK_ConstructorTemplateId: {
2041 // In well-formed code, we can only have a constructor
2042 // template-id that refers to the current context, so go there
2043 // to find the actual type being constructed.
2044 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
2045 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
2046 return DeclarationNameInfo();
2047
2048 // Determine the type of the class being constructed.
2049 QualType CurClassType = Context.getTypeDeclType(CurClass);
2050
2051 // FIXME: Check two things: that the template-id names the same type as
2052 // CurClassType, and that the template-id does not occur when the name
2053 // was qualified.
2054
2055 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
2056 Context.getCanonicalType(CurClassType)));
2057 NameInfo.setLoc(Name.StartLocation);
2058 // FIXME: should we retrieve TypeSourceInfo?
2059 NameInfo.setNamedTypeInfo(0);
2060 return NameInfo;
2061 }
2062
2063 case UnqualifiedId::IK_DestructorName: {
2064 TypeSourceInfo *TInfo;
2065 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
2066 if (Ty.isNull())
2067 return DeclarationNameInfo();
2068 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
2069 Context.getCanonicalType(Ty)));
2070 NameInfo.setLoc(Name.StartLocation);
2071 NameInfo.setNamedTypeInfo(TInfo);
2072 return NameInfo;
2073 }
2074
2075 case UnqualifiedId::IK_TemplateId: {
2076 TemplateName TName
2077 = TemplateName::getFromVoidPointer(Name.TemplateId->Template);
2078 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
2079 return Context.getNameForTemplate(TName, TNameLoc);
2080 }
2081
2082 } // switch (Name.getKind())
2083
Douglas Gregor10bd3682008-11-17 22:58:34 +00002084 assert(false && "Unknown name kind");
Abramo Bagnara25777432010-08-11 22:01:17 +00002085 return DeclarationNameInfo();
Douglas Gregor10bd3682008-11-17 22:58:34 +00002086}
2087
Douglas Gregor4ce205f2009-02-06 17:46:57 +00002088/// isNearlyMatchingFunction - Determine whether the C++ functions
2089/// Declaration and Definition are "nearly" matching. This heuristic
2090/// is used to improve diagnostics in the case where an out-of-line
2091/// function definition doesn't match any declaration within
2092/// the class or namespace.
2093static bool isNearlyMatchingFunction(ASTContext &Context,
2094 FunctionDecl *Declaration,
2095 FunctionDecl *Definition) {
Douglas Gregor584049d2008-12-15 23:53:10 +00002096 if (Declaration->param_size() != Definition->param_size())
2097 return false;
2098 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
2099 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
2100 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
2101
Douglas Gregora4923eb2009-11-16 21:35:15 +00002102 if (!Context.hasSameUnqualifiedType(DeclParamTy.getNonReferenceType(),
2103 DefParamTy.getNonReferenceType()))
Douglas Gregor584049d2008-12-15 23:53:10 +00002104 return false;
2105 }
2106
2107 return true;
2108}
2109
John McCall63b43852010-04-29 23:50:39 +00002110/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
2111/// declarator needs to be rebuilt in the current instantiation.
2112/// Any bits of declarator which appear before the name are valid for
2113/// consideration here. That's specifically the type in the decl spec
2114/// and the base type in any member-pointer chunks.
2115static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
2116 DeclarationName Name) {
2117 // The types we specifically need to rebuild are:
2118 // - typenames, typeofs, and decltypes
2119 // - types which will become injected class names
2120 // Of course, we also need to rebuild any type referencing such a
2121 // type. It's safest to just say "dependent", but we call out a
2122 // few cases here.
2123
2124 DeclSpec &DS = D.getMutableDeclSpec();
2125 switch (DS.getTypeSpecType()) {
2126 case DeclSpec::TST_typename:
2127 case DeclSpec::TST_typeofType:
2128 case DeclSpec::TST_typeofExpr:
2129 case DeclSpec::TST_decltype: {
2130 // Grab the type from the parser.
2131 TypeSourceInfo *TSI = 0;
2132 QualType T = S.GetTypeFromParser(DS.getTypeRep(), &TSI);
2133 if (T.isNull() || !T->isDependentType()) break;
2134
2135 // Make sure there's a type source info. This isn't really much
2136 // of a waste; most dependent types should have type source info
2137 // attached already.
2138 if (!TSI)
2139 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
2140
2141 // Rebuild the type in the current instantiation.
2142 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
2143 if (!TSI) return true;
2144
2145 // Store the new type back in the decl spec.
2146 QualType LocType = S.CreateLocInfoType(TSI->getType(), TSI);
2147 DS.UpdateTypeRep(LocType.getAsOpaquePtr());
2148 break;
2149 }
2150
2151 default:
2152 // Nothing to do for these decl specs.
2153 break;
2154 }
2155
2156 // It doesn't matter what order we do this in.
2157 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
2158 DeclaratorChunk &Chunk = D.getTypeObject(I);
2159
2160 // The only type information in the declarator which can come
2161 // before the declaration name is the base type of a member
2162 // pointer.
2163 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
2164 continue;
2165
2166 // Rebuild the scope specifier in-place.
2167 CXXScopeSpec &SS = Chunk.Mem.Scope();
2168 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
2169 return true;
2170 }
2171
2172 return false;
2173}
2174
Mike Stump1eb44332009-09-09 15:08:12 +00002175Sema::DeclPtrTy
2176Sema::HandleDeclarator(Scope *S, Declarator &D,
Douglas Gregore542c862009-06-23 23:11:28 +00002177 MultiTemplateParamsArg TemplateParamLists,
2178 bool IsFunctionDefinition) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002179 // TODO: consider using NameInfo for diagnostic.
2180 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2181 DeclarationName Name = NameInfo.getName();
Douglas Gregor10bd3682008-11-17 22:58:34 +00002182
Chris Lattnere80a59c2007-07-25 00:24:17 +00002183 // All of these full declarators require an identifier. If it doesn't have
2184 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00002185 if (!Name) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00002186 if (!D.isInvalidType()) // Reject this if we think it is valid.
Chris Lattner1f6f54b2008-11-11 06:13:16 +00002187 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002188 diag::err_declarator_need_ident)
2189 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00002190 return DeclPtrTy();
Chris Lattnere80a59c2007-07-25 00:24:17 +00002191 }
Mike Stump1eb44332009-09-09 15:08:12 +00002192
Chris Lattner31e05722007-08-26 06:24:45 +00002193 // The scope passed in may not be a decl scope. Zip up the scope tree until
2194 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00002195 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregoraaba5e32009-02-04 19:02:06 +00002196 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00002197 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00002198
John McCall63b43852010-04-29 23:50:39 +00002199 DeclContext *DC = CurContext;
2200 if (D.getCXXScopeSpec().isInvalid())
2201 D.setInvalidType();
2202 else if (D.getCXXScopeSpec().isSet()) {
2203 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
2204 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
2205 if (!DC) {
2206 // If we could not compute the declaration context, it's because the
2207 // declaration context is dependent but does not refer to a class,
2208 // class template, or class template partial specialization. Complain
2209 // and return early, to avoid the coming semantic disaster.
2210 Diag(D.getIdentifierLoc(),
2211 diag::err_template_qualified_declarator_no_match)
2212 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
2213 << D.getCXXScopeSpec().getRange();
2214 return DeclPtrTy();
2215 }
John McCall0dd7ceb2009-12-19 09:35:56 +00002216
John McCall63b43852010-04-29 23:50:39 +00002217 bool IsDependentContext = DC->isDependentContext();
John McCall0dd7ceb2009-12-19 09:35:56 +00002218
John McCall63b43852010-04-29 23:50:39 +00002219 if (!IsDependentContext &&
John McCall77bb1aa2010-05-01 00:40:08 +00002220 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCall63b43852010-04-29 23:50:39 +00002221 return DeclPtrTy();
2222
2223 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
2224 Diag(D.getIdentifierLoc(),
2225 diag::err_member_def_undefined_record)
2226 << Name << DC << D.getCXXScopeSpec().getRange();
2227 D.setInvalidType();
2228 }
2229
2230 // Check whether we need to rebuild the type of the given
2231 // declaration in the current instantiation.
2232 if (EnteringContext && IsDependentContext &&
2233 TemplateParamLists.size() != 0) {
2234 ContextRAII SavedContext(*this, DC);
2235 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
2236 D.setInvalidType();
Douglas Gregor4a959d82009-08-06 16:20:37 +00002237 }
2238 }
Mike Stump1eb44332009-09-09 15:08:12 +00002239
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002240 NamedDecl *New;
Douglas Gregorcda9c672009-02-16 17:45:42 +00002241
John McCallbf1a0282010-06-04 23:28:52 +00002242 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
2243 QualType R = TInfo->getType();
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00002244
Abramo Bagnara25777432010-08-11 22:01:17 +00002245 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +00002246 ForRedeclaration);
2247
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002248 // See if this is a redefinition of a variable in the same scope.
John McCall63b43852010-04-29 23:50:39 +00002249 if (!D.getCXXScopeSpec().isSet()) {
John McCall68263142009-11-18 22:49:29 +00002250 bool IsLinkageLookup = false;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00002251
2252 // If the declaration we're planning to build will be a function
2253 // or object with linkage, then look for another declaration with
2254 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
2255 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2256 /* Do nothing*/;
2257 else if (R->isFunctionType()) {
Douglas Gregor6bec78d2009-07-07 17:00:05 +00002258 if (CurContext->isFunctionOrMethod() ||
2259 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall68263142009-11-18 22:49:29 +00002260 IsLinkageLookup = true;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00002261 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
John McCall68263142009-11-18 22:49:29 +00002262 IsLinkageLookup = true;
Douglas Gregor6bec78d2009-07-07 17:00:05 +00002263 else if (CurContext->getLookupContext()->isTranslationUnit() &&
2264 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall68263142009-11-18 22:49:29 +00002265 IsLinkageLookup = true;
2266
2267 if (IsLinkageLookup)
2268 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00002269
John McCall68263142009-11-18 22:49:29 +00002270 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002271 } else { // Something like "int foo::x;"
John McCall68263142009-11-18 22:49:29 +00002272 LookupQualifiedName(Previous, DC);
2273
2274 // Don't consider using declarations as previous declarations for
2275 // out-of-line members.
2276 RemoveUsingDecls(Previous);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002277
2278 // C++ 7.3.1.2p2:
2279 // Members (including explicit specializations of templates) of a named
2280 // namespace can also be defined outside that namespace by explicit
2281 // qualification of the name being defined, provided that the entity being
2282 // defined was already declared in the namespace and the definition appears
2283 // after the point of declaration in a namespace that encloses the
2284 // declarations namespace.
2285 //
Douglas Gregor584049d2008-12-15 23:53:10 +00002286 // Note that we only check the context at this point. We don't yet
2287 // have enough information to make sure that PrevDecl is actually
2288 // the declaration we want to match. For example, given:
2289 //
Douglas Gregor9d350972008-12-12 08:25:50 +00002290 // class X {
2291 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00002292 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00002293 // };
2294 //
Douglas Gregor584049d2008-12-15 23:53:10 +00002295 // void X::f(int) { } // ill-formed
2296 //
2297 // In this case, PrevDecl will point to the overload set
2298 // containing the two f's declared in X, but neither of them
Mike Stump1eb44332009-09-09 15:08:12 +00002299 // matches.
Douglas Gregor4ce205f2009-02-06 17:46:57 +00002300
2301 // First check whether we named the global scope.
2302 if (isa<TranslationUnitDecl>(DC)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002303 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
Douglas Gregor4ce205f2009-02-06 17:46:57 +00002304 << Name << D.getCXXScopeSpec().getRange();
Sebastian Redl9770ef02009-11-08 11:36:54 +00002305 } else {
2306 DeclContext *Cur = CurContext;
2307 while (isa<LinkageSpecDecl>(Cur))
2308 Cur = Cur->getParent();
2309 if (!Cur->Encloses(DC)) {
2310 // The qualifying scope doesn't enclose the original declaration.
2311 // Emit diagnostic based on current scope.
2312 SourceLocation L = D.getIdentifierLoc();
2313 SourceRange R = D.getCXXScopeSpec().getRange();
2314 if (isa<FunctionDecl>(Cur))
2315 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
2316 else
2317 Diag(L, diag::err_invalid_declarator_scope)
2318 << Name << cast<NamedDecl>(DC) << R;
2319 D.setInvalidType();
2320 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002321 }
2322 }
2323
John McCall68263142009-11-18 22:49:29 +00002324 if (Previous.isSingleResult() &&
2325 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002326 // Maybe we will complain about the shadowed template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00002327 if (!D.isInvalidType())
John McCall68263142009-11-18 22:49:29 +00002328 if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
2329 Previous.getFoundDecl()))
Chris Lattnereaaebc72009-04-25 08:06:05 +00002330 D.setInvalidType();
Mike Stump1eb44332009-09-09 15:08:12 +00002331
Douglas Gregor72c3f312008-12-05 18:15:24 +00002332 // Just pretend that we didn't see the previous declaration.
John McCall68263142009-11-18 22:49:29 +00002333 Previous.clear();
Douglas Gregor72c3f312008-12-05 18:15:24 +00002334 }
2335
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002336 // In C++, the previous declaration we find might be a tag type
2337 // (class or enum). In this case, the new declaration will hide the
Douglas Gregor66973122009-01-28 17:15:10 +00002338 // tag type. Note that this does does not apply if we're declaring a
2339 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00002340 if (Previous.isSingleTagDecl() &&
Douglas Gregor66973122009-01-28 17:15:10 +00002341 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall68263142009-11-18 22:49:29 +00002342 Previous.clear();
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002343
Douglas Gregorcda9c672009-02-16 17:45:42 +00002344 bool Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002345 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregore542c862009-06-23 23:11:28 +00002346 if (TemplateParamLists.size()) {
2347 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
2348 return DeclPtrTy();
2349 }
Mike Stump1eb44332009-09-09 15:08:12 +00002350
John McCalla93c9342009-12-07 02:54:59 +00002351 New = ActOnTypedefDeclarator(S, D, DC, R, TInfo, Previous, Redeclaration);
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00002352 } else if (R->isFunctionType()) {
John McCalla93c9342009-12-07 02:54:59 +00002353 New = ActOnFunctionDeclarator(S, D, DC, R, TInfo, Previous,
Douglas Gregore542c862009-06-23 23:11:28 +00002354 move(TemplateParamLists),
Chris Lattnereaaebc72009-04-25 08:06:05 +00002355 IsFunctionDefinition, Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +00002356 } else {
John McCalla93c9342009-12-07 02:54:59 +00002357 New = ActOnVariableDeclarator(S, D, DC, R, TInfo, Previous,
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00002358 move(TemplateParamLists),
2359 Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +00002360 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002361
2362 if (New == 0)
Chris Lattnerb28317a2009-03-28 19:18:32 +00002363 return DeclPtrTy();
Mike Stump1eb44332009-09-09 15:08:12 +00002364
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00002365 // If this has an identifier and is not an invalid redeclaration or
2366 // function template specialization, add it to the scope stack.
Douglas Gregorf178dca2010-07-24 00:10:38 +00002367 if (New->getDeclName() && !(Redeclaration && New->isInvalidDecl()))
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002368 PushOnScopeChains(New, S);
Mike Stump1eb44332009-09-09 15:08:12 +00002369
Chris Lattnerb28317a2009-03-28 19:18:32 +00002370 return DeclPtrTy::make(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00002371}
2372
Eli Friedman1ca48132009-02-21 00:44:51 +00002373/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2374/// types into constant array types in certain situations which would otherwise
2375/// be errors (for GCC compatibility).
2376static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2377 ASTContext &Context,
Douglas Gregor2767ce22010-08-18 00:39:00 +00002378 bool &SizeIsNegative,
2379 llvm::APSInt &Oversized) {
Eli Friedman1ca48132009-02-21 00:44:51 +00002380 // This method tries to turn a variable array into a constant
2381 // array even when the size isn't an ICE. This is necessary
2382 // for compatibility with code that depends on gcc's buggy
2383 // constant expression folding, like struct {char x[(int)(char*)2];}
2384 SizeIsNegative = false;
Douglas Gregor2767ce22010-08-18 00:39:00 +00002385 Oversized = 0;
2386
2387 if (T->isDependentType())
2388 return QualType();
2389
John McCall0953e762009-09-24 19:53:00 +00002390 QualifierCollector Qs;
2391 const Type *Ty = Qs.strip(T);
2392
2393 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedman1ca48132009-02-21 00:44:51 +00002394 QualType Pointee = PTy->getPointeeType();
2395 QualType FixedType =
Douglas Gregor2767ce22010-08-18 00:39:00 +00002396 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
2397 Oversized);
Eli Friedman1ca48132009-02-21 00:44:51 +00002398 if (FixedType.isNull()) return FixedType;
Eli Friedman61125c82009-02-21 00:58:02 +00002399 FixedType = Context.getPointerType(FixedType);
John McCall0953e762009-09-24 19:53:00 +00002400 return Qs.apply(FixedType);
Eli Friedman1ca48132009-02-21 00:44:51 +00002401 }
2402
2403 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanbc592e62009-02-26 03:58:54 +00002404 if (!VLATy)
2405 return QualType();
2406 // FIXME: We should probably handle this case
2407 if (VLATy->getElementType()->isVariablyModifiedType())
2408 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00002409
Eli Friedman1ca48132009-02-21 00:44:51 +00002410 Expr::EvalResult EvalResult;
2411 if (!VLATy->getSizeExpr() ||
Eli Friedmanbc592e62009-02-26 03:58:54 +00002412 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
2413 !EvalResult.Val.isInt())
Eli Friedman1ca48132009-02-21 00:44:51 +00002414 return QualType();
Eli Friedmanbc592e62009-02-26 03:58:54 +00002415
Douglas Gregor2767ce22010-08-18 00:39:00 +00002416 // Check whether the array size is negative.
Eli Friedman1ca48132009-02-21 00:44:51 +00002417 llvm::APSInt &Res = EvalResult.Val.getInt();
Douglas Gregor2767ce22010-08-18 00:39:00 +00002418 if (Res.isSigned() && Res.isNegative()) {
2419 SizeIsNegative = true;
2420 return QualType();
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002421 }
Eli Friedman1ca48132009-02-21 00:44:51 +00002422
Douglas Gregor2767ce22010-08-18 00:39:00 +00002423 // Check whether the array is too large to be addressed.
2424 unsigned ActiveSizeBits
2425 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
2426 Res);
2427 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2428 Oversized = Res;
2429 return QualType();
2430 }
2431
2432 return Context.getConstantArrayType(VLATy->getElementType(),
2433 Res, ArrayType::Normal, 0);
Eli Friedman1ca48132009-02-21 00:44:51 +00002434}
2435
Douglas Gregor63935192009-03-02 00:19:53 +00002436/// \brief Register the given locally-scoped external C declaration so
2437/// that it can be found later for redeclarations
Mike Stump1eb44332009-09-09 15:08:12 +00002438void
John McCall68263142009-11-18 22:49:29 +00002439Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
2440 const LookupResult &Previous,
Douglas Gregor63935192009-03-02 00:19:53 +00002441 Scope *S) {
2442 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
2443 "Decl is not a locally-scoped decl!");
2444 // Note that we have a locally-scoped external with this name.
2445 LocallyScopedExternalDecls[ND->getDeclName()] = ND;
2446
John McCall68263142009-11-18 22:49:29 +00002447 if (!Previous.isSingleResult())
Douglas Gregor63935192009-03-02 00:19:53 +00002448 return;
2449
John McCall68263142009-11-18 22:49:29 +00002450 NamedDecl *PrevDecl = Previous.getFoundDecl();
2451
Douglas Gregor63935192009-03-02 00:19:53 +00002452 // If there was a previous declaration of this variable, it may be
2453 // in our identifier chain. Update the identifier chain with the new
2454 // declaration.
Douglas Gregor2dc0e642009-03-23 23:06:20 +00002455 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
Douglas Gregor63935192009-03-02 00:19:53 +00002456 // The previous declaration was found on the identifer resolver
2457 // chain, so remove it from its scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002458 while (S && !S->isDeclScope(DeclPtrTy::make(PrevDecl)))
Douglas Gregor63935192009-03-02 00:19:53 +00002459 S = S->getParent();
2460
2461 if (S)
Chris Lattnerb28317a2009-03-28 19:18:32 +00002462 S->RemoveDecl(DeclPtrTy::make(PrevDecl));
Douglas Gregor63935192009-03-02 00:19:53 +00002463 }
2464}
2465
Eli Friedman85a53192009-04-07 19:37:57 +00002466/// \brief Diagnose function specifiers on a declaration of an identifier that
2467/// does not identify a function.
2468void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
2469 // FIXME: We should probably indicate the identifier in question to avoid
2470 // confusion for constructs like "inline int a(), b;"
2471 if (D.getDeclSpec().isInlineSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00002472 Diag(D.getDeclSpec().getInlineSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00002473 diag::err_inline_non_function);
2474
2475 if (D.getDeclSpec().isVirtualSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00002476 Diag(D.getDeclSpec().getVirtualSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00002477 diag::err_virtual_non_function);
2478
2479 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00002480 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Eli Friedman85a53192009-04-07 19:37:57 +00002481 diag::err_explicit_non_function);
2482}
2483
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002484NamedDecl*
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002485Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
John McCalla93c9342009-12-07 02:54:59 +00002486 QualType R, TypeSourceInfo *TInfo,
John McCall68263142009-11-18 22:49:29 +00002487 LookupResult &Previous, bool &Redeclaration) {
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002488 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
2489 if (D.getCXXScopeSpec().isSet()) {
2490 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
2491 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00002492 D.setInvalidType();
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002493 // Pretend we didn't see the scope specifier.
Douglas Gregor9de672f2010-03-23 15:26:55 +00002494 DC = CurContext;
2495 Previous.clear();
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002496 }
2497
Douglas Gregor021c3b32009-03-11 23:00:04 +00002498 if (getLangOptions().CPlusPlus) {
2499 // Check that there are no default arguments (C++ only).
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002500 CheckExtraCXXDefaultArguments(D);
Douglas Gregor021c3b32009-03-11 23:00:04 +00002501 }
2502
Eli Friedman85a53192009-04-07 19:37:57 +00002503 DiagnoseFunctionSpecifiers(D);
2504
Eli Friedman63054b32009-04-19 20:27:55 +00002505 if (D.getDeclSpec().isThreadSpecified())
2506 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2507
Douglas Gregoraef01992010-07-13 06:37:01 +00002508 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
2509 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
2510 << D.getName().getSourceRange();
2511 return 0;
2512 }
2513
John McCalla93c9342009-12-07 02:54:59 +00002514 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, TInfo);
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002515 if (!NewTD) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002516
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002517 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002518 ProcessDeclAttributes(S, NewTD, D);
John McCall68263142009-11-18 22:49:29 +00002519
Chris Lattner38c5ebd2009-04-19 05:21:20 +00002520 // C99 6.7.7p2: If a typedef name specifies a variably modified type
2521 // then it shall have block scope.
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00002522 // Note that variably modified types must be fixed before merging the decl so
2523 // that redeclarations will match.
Chris Lattner38c5ebd2009-04-19 05:21:20 +00002524 QualType T = NewTD->getUnderlyingType();
2525 if (T->isVariablyModifiedType()) {
John McCallb60a77e2010-08-01 00:26:45 +00002526 setFunctionHasBranchProtectedScope();
Mike Stump1eb44332009-09-09 15:08:12 +00002527
Chris Lattner38c5ebd2009-04-19 05:21:20 +00002528 if (S->getFnParent() == 0) {
Eli Friedman1ca48132009-02-21 00:44:51 +00002529 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +00002530 llvm::APSInt Oversized;
Eli Friedman1ca48132009-02-21 00:44:51 +00002531 QualType FixedTy =
Douglas Gregor2767ce22010-08-18 00:39:00 +00002532 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
2533 Oversized);
Eli Friedman1ca48132009-02-21 00:44:51 +00002534 if (!FixedTy.isNull()) {
2535 Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size);
John McCalla93c9342009-12-07 02:54:59 +00002536 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
Eli Friedman1ca48132009-02-21 00:44:51 +00002537 } else {
2538 if (SizeIsNegative)
2539 Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size);
2540 else if (T->isVariableArrayType())
2541 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
Douglas Gregor2767ce22010-08-18 00:39:00 +00002542 else if (Oversized.getBoolValue())
2543 Diag(D.getIdentifierLoc(), diag::err_array_too_large)
2544 << Oversized.toString(10);
Eli Friedman1ca48132009-02-21 00:44:51 +00002545 else
2546 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002547 NewTD->setInvalidDecl();
Eli Friedman1ca48132009-02-21 00:44:51 +00002548 }
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002549 }
2550 }
Douglas Gregorc29f77b2009-07-07 16:35:42 +00002551
Eli Friedmanbf87f2c2010-08-10 03:13:15 +00002552 // Merge the decl with the existing one if appropriate. If the decl is
2553 // in an outer scope, it isn't the same thing.
2554 FilterLookupForScope(*this, Previous, DC, S, /*ConsiderLinkage*/ false);
2555 if (!Previous.empty()) {
2556 Redeclaration = true;
2557 MergeTypeDefDecl(NewTD, Previous);
2558 }
2559
Douglas Gregorc29f77b2009-07-07 16:35:42 +00002560 // If this is the C FILE type, notify the AST context.
2561 if (IdentifierInfo *II = NewTD->getIdentifier())
2562 if (!NewTD->isInvalidDecl() &&
Mike Stump782fa302009-07-28 02:25:19 +00002563 NewTD->getDeclContext()->getLookupContext()->isTranslationUnit()) {
2564 if (II->isStr("FILE"))
2565 Context.setFILEDecl(NewTD);
2566 else if (II->isStr("jmp_buf"))
2567 Context.setjmp_bufDecl(NewTD);
2568 else if (II->isStr("sigjmp_buf"))
2569 Context.setsigjmp_bufDecl(NewTD);
2570 }
2571
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00002572 return NewTD;
2573}
2574
Douglas Gregor8f301052009-02-24 19:23:27 +00002575/// \brief Determines whether the given declaration is an out-of-scope
2576/// previous declaration.
2577///
2578/// This routine should be invoked when name lookup has found a
2579/// previous declaration (PrevDecl) that is not in the scope where a
2580/// new declaration by the same name is being introduced. If the new
2581/// declaration occurs in a local scope, previous declarations with
2582/// linkage may still be considered previous declarations (C99
2583/// 6.2.2p4-5, C++ [basic.link]p6).
2584///
2585/// \param PrevDecl the previous declaration found by name
2586/// lookup
Mike Stump1eb44332009-09-09 15:08:12 +00002587///
Douglas Gregor8f301052009-02-24 19:23:27 +00002588/// \param DC the context in which the new declaration is being
2589/// declared.
2590///
2591/// \returns true if PrevDecl is an out-of-scope previous declaration
2592/// for a new delcaration with the same name.
Mike Stump1eb44332009-09-09 15:08:12 +00002593static bool
Douglas Gregor8f301052009-02-24 19:23:27 +00002594isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
2595 ASTContext &Context) {
2596 if (!PrevDecl)
2597 return 0;
2598
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00002599 if (!PrevDecl->hasLinkage())
2600 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00002601
2602 if (Context.getLangOptions().CPlusPlus) {
2603 // C++ [basic.link]p6:
2604 // If there is a visible declaration of an entity with linkage
2605 // having the same name and type, ignoring entities declared
2606 // outside the innermost enclosing namespace scope, the block
2607 // scope declaration declares that same entity and receives the
2608 // linkage of the previous declaration.
2609 DeclContext *OuterContext = DC->getLookupContext();
2610 if (!OuterContext->isFunctionOrMethod())
2611 // This rule only applies to block-scope declarations.
2612 return false;
2613 else {
2614 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
2615 if (PrevOuterContext->isRecord())
2616 // We found a member function: ignore it.
2617 return false;
2618 else {
2619 // Find the innermost enclosing namespace for the new and
2620 // previous declarations.
2621 while (!OuterContext->isFileContext())
2622 OuterContext = OuterContext->getParent();
2623 while (!PrevOuterContext->isFileContext())
2624 PrevOuterContext = PrevOuterContext->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00002625
Douglas Gregor8f301052009-02-24 19:23:27 +00002626 // The previous declaration is in a different namespace, so it
2627 // isn't the same function.
Mike Stump1eb44332009-09-09 15:08:12 +00002628 if (OuterContext->getPrimaryContext() !=
Douglas Gregor8f301052009-02-24 19:23:27 +00002629 PrevOuterContext->getPrimaryContext())
2630 return false;
2631 }
2632 }
2633 }
2634
Douglas Gregor8f301052009-02-24 19:23:27 +00002635 return true;
2636}
2637
John McCallb6217662010-03-15 10:12:16 +00002638static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
2639 CXXScopeSpec &SS = D.getCXXScopeSpec();
2640 if (!SS.isSet()) return;
2641 DD->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2642 SS.getRange());
2643}
2644
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002645NamedDecl*
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002646Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
John McCalla93c9342009-12-07 02:54:59 +00002647 QualType R, TypeSourceInfo *TInfo,
John McCall68263142009-11-18 22:49:29 +00002648 LookupResult &Previous,
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00002649 MultiTemplateParamsArg TemplateParamLists,
Douglas Gregorcda9c672009-02-16 17:45:42 +00002650 bool &Redeclaration) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002651 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002652
2653 // Check that there are no default arguments (C++ only).
2654 if (getLangOptions().CPlusPlus)
2655 CheckExtraCXXDefaultArguments(D);
2656
Douglas Gregor16573fa2010-04-19 22:54:31 +00002657 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
2658 assert(SCSpec != DeclSpec::SCS_typedef &&
2659 "Parser allowed 'typedef' as storage class VarDecl.");
Abramo Bagnara35f9a192010-07-30 16:47:02 +00002660 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregor16573fa2010-04-19 22:54:31 +00002661 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002662 // mutable can only appear on non-static class members, so it's always
2663 // an error here
2664 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002665 D.setInvalidType();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002666 SC = VarDecl::None;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002667 }
Douglas Gregor16573fa2010-04-19 22:54:31 +00002668 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
2669 VarDecl::StorageClass SCAsWritten
Abramo Bagnara35f9a192010-07-30 16:47:02 +00002670 = StorageClassSpecToVarDeclStorageClass(SCSpec);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002671
2672 IdentifierInfo *II = Name.getAsIdentifierInfo();
2673 if (!II) {
2674 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
2675 << Name.getAsString();
2676 return 0;
2677 }
2678
Eli Friedman85a53192009-04-07 19:37:57 +00002679 DiagnoseFunctionSpecifiers(D);
Douglas Gregor021c3b32009-03-11 23:00:04 +00002680
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00002681 if (!DC->isRecord() && S->getFnParent() == 0) {
2682 // C99 6.9p2: The storage-class specifiers auto and register shall not
2683 // appear in the declaration specifiers in an external declaration.
2684 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Mike Stump1eb44332009-09-09 15:08:12 +00002685
Chris Lattnerd4b19d52009-05-12 21:44:00 +00002686 // If this is a register variable with an asm label specified, then this
2687 // is a GNU extension.
2688 if (SC == VarDecl::Register && D.getAsmLabel())
2689 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
2690 else
2691 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002692 D.setInvalidType();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002693 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002694 }
Douglas Gregor656de632009-03-11 23:52:16 +00002695 if (DC->isRecord() && !CurContext->isRecord()) {
2696 // This is an out-of-line definition of a static data member.
2697 if (SC == VarDecl::Static) {
Mike Stump1eb44332009-09-09 15:08:12 +00002698 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregor656de632009-03-11 23:52:16 +00002699 diag::err_static_out_of_line)
Douglas Gregor849b2432010-03-31 17:46:05 +00002700 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregor656de632009-03-11 23:52:16 +00002701 } else if (SC == VarDecl::None)
2702 SC = VarDecl::Static;
2703 }
Anders Carlssone98da2e2009-06-24 00:28:53 +00002704 if (SC == VarDecl::Static) {
2705 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
2706 if (RD->isLocalClass())
Mike Stump1eb44332009-09-09 15:08:12 +00002707 Diag(D.getIdentifierLoc(),
Anders Carlssone98da2e2009-06-24 00:28:53 +00002708 diag::err_static_data_member_not_allowed_in_local_class)
2709 << Name << RD->getDeclName();
2710 }
2711 }
Mike Stump1eb44332009-09-09 15:08:12 +00002712
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00002713 // Match up the template parameter lists with the scope specifier, then
2714 // determine whether we have a template or a template specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002715 bool isExplicitSpecialization = false;
Abramo Bagnara9b934882010-06-12 08:15:14 +00002716 unsigned NumMatchedTemplateParamLists = TemplateParamLists.size();
Douglas Gregor0167f3c2010-07-14 23:14:12 +00002717 bool Invalid = false;
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00002718 if (TemplateParameterList *TemplateParams
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002719 = MatchTemplateParametersToScopeSpecifier(
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00002720 D.getDeclSpec().getSourceRange().getBegin(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002721 D.getCXXScopeSpec(),
Douglas Gregor27eeb5e2009-07-22 22:05:02 +00002722 (TemplateParameterList**)TemplateParamLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002723 TemplateParamLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00002724 /*never a friend*/ false,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00002725 isExplicitSpecialization,
2726 Invalid)) {
Abramo Bagnara9b934882010-06-12 08:15:14 +00002727 // All but one template parameter lists have been matching.
2728 --NumMatchedTemplateParamLists;
2729
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00002730 if (TemplateParams->size() > 0) {
2731 // There is no such thing as a variable template.
2732 Diag(D.getIdentifierLoc(), diag::err_template_variable)
2733 << II
2734 << SourceRange(TemplateParams->getTemplateLoc(),
2735 TemplateParams->getRAngleLoc());
2736 return 0;
2737 } else {
2738 // There is an extraneous 'template<>' for this variable. Complain
2739 // about it, but allow the declaration of the variable.
Mike Stump1eb44332009-09-09 15:08:12 +00002740 Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor7cdbc582009-07-22 23:48:44 +00002741 diag::err_template_variable_noparams)
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00002742 << II
2743 << SourceRange(TemplateParams->getTemplateLoc(),
Mike Stump1eb44332009-09-09 15:08:12 +00002744 TemplateParams->getRAngleLoc());
Douglas Gregor1fef4e62009-10-07 22:35:40 +00002745
2746 isExplicitSpecialization = true;
Douglas Gregordfe3f2d2009-07-22 17:18:37 +00002747 }
Mike Stump1eb44332009-09-09 15:08:12 +00002748 }
2749
Douglas Gregor16573fa2010-04-19 22:54:31 +00002750 VarDecl *NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
2751 II, R, TInfo, SC, SCAsWritten);
Eli Friedman63054b32009-04-19 20:27:55 +00002752
Douglas Gregor0167f3c2010-07-14 23:14:12 +00002753 if (D.isInvalidType() || Invalid)
Chris Lattnereaaebc72009-04-25 08:06:05 +00002754 NewVD->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002755
John McCallb6217662010-03-15 10:12:16 +00002756 SetNestedNameSpecifier(NewVD, D);
2757
Douglas Gregor98c2e622010-07-28 23:59:57 +00002758 if (NumMatchedTemplateParamLists > 0 && D.getCXXScopeSpec().isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00002759 NewVD->setTemplateParameterListsInfo(Context,
2760 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00002761 (TemplateParameterList**)TemplateParamLists.release());
2762 }
2763
Eli Friedman63054b32009-04-19 20:27:55 +00002764 if (D.getDeclSpec().isThreadSpecified()) {
2765 if (NewVD->hasLocalStorage())
2766 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
Eli Friedman4fb71b02009-04-19 21:48:33 +00002767 else if (!Context.Target.isTLSSupported())
2768 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
Eli Friedman63054b32009-04-19 20:27:55 +00002769 else
2770 NewVD->setThreadSpecified(true);
2771 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002772
Douglas Gregor656de632009-03-11 23:52:16 +00002773 // Set the lexical context. If the declarator has a C++ scope specifier, the
2774 // lexical context will be different from the semantic context.
2775 NewVD->setLexicalDeclContext(CurContext);
2776
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002777 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002778 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002779
2780 // Handle GNU asm-label extension (encoded as an attribute).
2781 if (Expr *E = (Expr*) D.getAsmLabel()) {
2782 // The parser guarantees this is a string.
Mike Stump1eb44332009-09-09 15:08:12 +00002783 StringLiteral *SE = cast<StringLiteral>(E);
Sean Huntcf807c42010-08-18 23:23:40 +00002784 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
2785 Context, SE->getString()));
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002786 }
2787
John McCall8472af42010-03-16 21:48:18 +00002788 // Diagnose shadowed variables before filtering for scope.
John McCalla369a952010-03-20 04:12:52 +00002789 if (!D.getCXXScopeSpec().isSet())
John McCall053f4bd2010-03-22 09:20:08 +00002790 CheckShadow(S, NewVD, Previous);
John McCall8472af42010-03-16 21:48:18 +00002791
John McCall68263142009-11-18 22:49:29 +00002792 // Don't consider existing declarations that are in a different
2793 // scope and are out-of-semantic-context declarations (if the new
2794 // declaration has linkage).
2795 FilterLookupForScope(*this, Previous, DC, S, NewVD->hasLinkage());
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002796
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002797 // Merge the decl with the existing one if appropriate.
John McCall68263142009-11-18 22:49:29 +00002798 if (!Previous.empty()) {
2799 if (Previous.isSingleResult() &&
2800 isa<FieldDecl>(Previous.getFoundDecl()) &&
2801 D.getCXXScopeSpec().isSet()) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002802 // The user tried to define a non-static data member
2803 // out-of-line (C++ [dcl.meaning]p1).
2804 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
2805 << D.getCXXScopeSpec().getRange();
John McCall68263142009-11-18 22:49:29 +00002806 Previous.clear();
Chris Lattnereaaebc72009-04-25 08:06:05 +00002807 NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002808 }
2809 } else if (D.getCXXScopeSpec().isSet()) {
2810 // No previous declaration in the qualifying scope.
Douglas Gregor3f093272009-10-13 21:16:44 +00002811 Diag(D.getIdentifierLoc(), diag::err_no_member)
2812 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
2813 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00002814 NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002815 }
2816
John McCall68263142009-11-18 22:49:29 +00002817 CheckVariableDeclaration(NewVD, Previous, Redeclaration);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002818
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002819 // This is an explicit specialization of a static data member. Check it.
2820 if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
John McCall68263142009-11-18 22:49:29 +00002821 CheckMemberSpecialization(NewVD, Previous))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002822 NewVD->setInvalidDecl();
John McCall68263142009-11-18 22:49:29 +00002823
Ryan Flynn478fbc62009-07-25 22:29:44 +00002824 // attributes declared post-definition are currently ignored
Sean Huntcf807c42010-08-18 23:23:40 +00002825 // FIXME: This should be handled in attribute merging, not
2826 // here.
John McCall68263142009-11-18 22:49:29 +00002827 if (Previous.isSingleResult()) {
Sebastian Redl31310a22010-02-01 20:16:42 +00002828 VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl());
2829 if (Def && (Def = Def->getDefinition()) &&
2830 Def != NewVD && D.hasAttributes()) {
Ryan Flynn478fbc62009-07-25 22:29:44 +00002831 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
2832 Diag(Def->getLocation(), diag::note_previous_definition);
2833 }
2834 }
2835
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002836 // If this is a locally-scoped extern C variable, update the map of
2837 // such variables.
Douglas Gregor48a83b52009-09-12 00:17:51 +00002838 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
Chris Lattnereaaebc72009-04-25 08:06:05 +00002839 !NewVD->isInvalidDecl())
John McCall68263142009-11-18 22:49:29 +00002840 RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002841
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00002842 // If there's a #pragma GCC visibility in scope, and this isn't a class
2843 // member, set the visibility of this variable.
2844 if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord())
2845 AddPushedVisibilityAttribute(NewVD);
2846
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00002847 MarkUnusedFileScopedDecl(NewVD);
2848
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002849 return NewVD;
2850}
2851
John McCall053f4bd2010-03-22 09:20:08 +00002852/// \brief Diagnose variable or built-in function shadowing. Implements
2853/// -Wshadow.
John McCall8472af42010-03-16 21:48:18 +00002854///
John McCall053f4bd2010-03-22 09:20:08 +00002855/// This method is called whenever a VarDecl is added to a "useful"
2856/// scope.
John McCall8472af42010-03-16 21:48:18 +00002857///
John McCalla369a952010-03-20 04:12:52 +00002858/// \param S the scope in which the shadowing name is being declared
2859/// \param R the lookup of the name
John McCall8472af42010-03-16 21:48:18 +00002860///
John McCall053f4bd2010-03-22 09:20:08 +00002861void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCall8472af42010-03-16 21:48:18 +00002862 // Return if warning is ignored.
2863 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow) == Diagnostic::Ignored)
2864 return;
2865
John McCalla369a952010-03-20 04:12:52 +00002866 // Don't diagnose declarations at file scope. The scope might not
2867 // have a DeclContext if (e.g.) we're parsing a function prototype.
2868 DeclContext *NewDC = static_cast<DeclContext*>(S->getEntity());
2869 if (NewDC && NewDC->isFileContext())
John McCall8472af42010-03-16 21:48:18 +00002870 return;
John McCalla369a952010-03-20 04:12:52 +00002871
2872 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregorc48c9162010-03-17 16:03:44 +00002873 if (R.getResultKind() != LookupResult::Found)
John McCall8472af42010-03-16 21:48:18 +00002874 return;
John McCall8472af42010-03-16 21:48:18 +00002875
John McCall8472af42010-03-16 21:48:18 +00002876 NamedDecl* ShadowedDecl = R.getFoundDecl();
2877 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
2878 return;
2879
John McCalla369a952010-03-20 04:12:52 +00002880 DeclContext *OldDC = ShadowedDecl->getDeclContext();
2881
2882 // Only warn about certain kinds of shadowing for class members.
2883 if (NewDC && NewDC->isRecord()) {
2884 // In particular, don't warn about shadowing non-class members.
2885 if (!OldDC->isRecord())
2886 return;
2887
2888 // TODO: should we warn about static data members shadowing
2889 // static data members from base classes?
2890
2891 // TODO: don't diagnose for inaccessible shadowed members.
2892 // This is hard to do perfectly because we might friend the
2893 // shadowing context, but that's just a false negative.
2894 }
2895
2896 // Determine what kind of declaration we're shadowing.
John McCall8472af42010-03-16 21:48:18 +00002897 unsigned Kind;
John McCalla369a952010-03-20 04:12:52 +00002898 if (isa<RecordDecl>(OldDC)) {
John McCall8472af42010-03-16 21:48:18 +00002899 if (isa<FieldDecl>(ShadowedDecl))
2900 Kind = 3; // field
2901 else
2902 Kind = 2; // static data member
John McCalla369a952010-03-20 04:12:52 +00002903 } else if (OldDC->isFileContext())
John McCall8472af42010-03-16 21:48:18 +00002904 Kind = 1; // global
2905 else
2906 Kind = 0; // local
2907
John McCalla369a952010-03-20 04:12:52 +00002908 DeclarationName Name = R.getLookupName();
2909
John McCall8472af42010-03-16 21:48:18 +00002910 // Emit warning and note.
John McCalla369a952010-03-20 04:12:52 +00002911 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCall8472af42010-03-16 21:48:18 +00002912 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
2913}
2914
John McCall053f4bd2010-03-22 09:20:08 +00002915/// \brief Check -Wshadow without the advantage of a previous lookup.
2916void Sema::CheckShadow(Scope *S, VarDecl *D) {
2917 LookupResult R(*this, D->getDeclName(), D->getLocation(),
2918 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
2919 LookupName(R, S);
2920 CheckShadow(S, D, R);
2921}
2922
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002923/// \brief Perform semantic checking on a newly-created variable
2924/// declaration.
2925///
2926/// This routine performs all of the type-checking required for a
Douglas Gregor180bb632009-05-01 15:47:09 +00002927/// variable declaration once it has been built. It is used both to
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002928/// check variables after they have been parsed and their declarators
Douglas Gregor180bb632009-05-01 15:47:09 +00002929/// have been translated into a declaration, and to check variables
2930/// that have been instantiated from a template.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002931///
Chris Lattnereaaebc72009-04-25 08:06:05 +00002932/// Sets NewVD->isInvalidDecl() if an error was encountered.
John McCall68263142009-11-18 22:49:29 +00002933void Sema::CheckVariableDeclaration(VarDecl *NewVD,
2934 LookupResult &Previous,
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002935 bool &Redeclaration) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00002936 // If the decl is already known invalid, don't check it.
2937 if (NewVD->isInvalidDecl())
2938 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002939
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002940 QualType T = NewVD->getType();
2941
John McCallc12c5bb2010-05-15 11:32:37 +00002942 if (T->isObjCObjectType()) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002943 Diag(NewVD->getLocation(), diag::err_statically_allocated_object);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002944 return NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002945 }
Mike Stump1eb44332009-09-09 15:08:12 +00002946
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002947 // Emit an error if an address space was applied to decl with local storage.
2948 // This includes arrays of objects with address space qualifiers, but not
2949 // automatic variables that point to other address spaces.
2950 // ISO/IEC TR 18037 S5.1.2
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002951 if (NewVD->hasLocalStorage() && (T.getAddressSpace() != 0)) {
2952 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002953 return NewVD->setInvalidDecl();
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00002954 }
Fariborz Jahanian7b5b3172009-02-21 19:44:02 +00002955
Mike Stumpf33651c2009-04-14 00:57:29 +00002956 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002957 && !NewVD->hasAttr<BlocksAttr>())
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002958 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Fariborz Jahanian7b5b3172009-02-21 19:44:02 +00002959
Chris Lattner38c5ebd2009-04-19 05:21:20 +00002960 bool isVM = T->isVariablyModifiedType();
Chris Lattnerbe6d2592009-07-19 20:17:11 +00002961 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalle46f62c2010-08-01 01:24:59 +00002962 NewVD->hasAttr<BlocksAttr>())
John McCallb60a77e2010-08-01 00:26:45 +00002963 setFunctionHasBranchProtectedScope();
Mike Stump1eb44332009-09-09 15:08:12 +00002964
Chris Lattner38c5ebd2009-04-19 05:21:20 +00002965 if ((isVM && NewVD->hasLinkage()) ||
2966 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00002967 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +00002968 llvm::APSInt Oversized;
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00002969 QualType FixedTy =
Douglas Gregor2767ce22010-08-18 00:39:00 +00002970 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
2971 Oversized);
Mike Stump1eb44332009-09-09 15:08:12 +00002972
Chris Lattnereaaebc72009-04-25 08:06:05 +00002973 if (FixedTy.isNull() && T->isVariableArrayType()) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00002974 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002975 // FIXME: This won't give the correct result for
2976 // int a[10][n];
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00002977 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002978
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00002979 if (NewVD->isFileVarDecl())
2980 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnereaaebc72009-04-25 08:06:05 +00002981 << SizeRange;
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00002982 else if (NewVD->getStorageClass() == VarDecl::Static)
2983 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnereaaebc72009-04-25 08:06:05 +00002984 << SizeRange;
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00002985 else
2986 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnereaaebc72009-04-25 08:06:05 +00002987 << SizeRange;
2988 return NewVD->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002989 }
2990
Chris Lattnereaaebc72009-04-25 08:06:05 +00002991 if (FixedTy.isNull()) {
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00002992 if (NewVD->isFileVarDecl())
2993 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
2994 else
2995 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002996 return NewVD->setInvalidDecl();
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00002997 }
Mike Stump1eb44332009-09-09 15:08:12 +00002998
Chris Lattnereaaebc72009-04-25 08:06:05 +00002999 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
3000 NewVD->setType(FixedTy);
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00003001 }
3002
John McCall68263142009-11-18 22:49:29 +00003003 if (Previous.empty() && NewVD->isExternC()) {
Douglas Gregor63935192009-03-02 00:19:53 +00003004 // Since we did not find anything by this name and we're declaring
3005 // an extern "C" variable, look for a non-visible extern "C"
3006 // declaration with the same name.
3007 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00003008 = LocallyScopedExternalDecls.find(NewVD->getDeclName());
Douglas Gregor63935192009-03-02 00:19:53 +00003009 if (Pos != LocallyScopedExternalDecls.end())
John McCall68263142009-11-18 22:49:29 +00003010 Previous.addDecl(Pos->second);
Douglas Gregor63935192009-03-02 00:19:53 +00003011 }
3012
Chris Lattnereaaebc72009-04-25 08:06:05 +00003013 if (T->isVoidType() && !NewVD->hasExternalStorage()) {
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00003014 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
3015 << T;
Chris Lattnereaaebc72009-04-25 08:06:05 +00003016 return NewVD->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00003017 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00003018
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003019 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpea000bf2009-04-30 00:19:40 +00003020 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
3021 return NewVD->setInvalidDecl();
3022 }
Mike Stump1eb44332009-09-09 15:08:12 +00003023
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003024 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpc975bb02009-05-01 23:41:47 +00003025 Diag(NewVD->getLocation(), diag::err_block_on_vm);
3026 return NewVD->setInvalidDecl();
3027 }
3028
Sebastian Redlf9ea1f32010-07-12 23:11:43 +00003029 // Function pointers and references cannot have qualified function type, only
3030 // function pointer-to-members can do that.
3031 QualType Pointee;
3032 unsigned PtrOrRef = 0;
3033 if (const PointerType *Ptr = T->getAs<PointerType>())
3034 Pointee = Ptr->getPointeeType();
3035 else if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
3036 Pointee = Ref->getPointeeType();
3037 PtrOrRef = 1;
3038 }
3039 if (!Pointee.isNull() && Pointee->isFunctionProtoType() &&
3040 Pointee->getAs<FunctionProtoType>()->getTypeQuals() != 0) {
3041 Diag(NewVD->getLocation(), diag::err_invalid_qualified_function_pointer)
3042 << PtrOrRef;
3043 return NewVD->setInvalidDecl();
3044 }
3045
John McCall68263142009-11-18 22:49:29 +00003046 if (!Previous.empty()) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00003047 Redeclaration = true;
John McCall68263142009-11-18 22:49:29 +00003048 MergeVarDecl(NewVD, Previous);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00003049 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00003050}
3051
Douglas Gregora8f32e02009-10-06 17:59:45 +00003052/// \brief Data used with FindOverriddenMethod
3053struct FindOverriddenMethodData {
3054 Sema *S;
3055 CXXMethodDecl *Method;
3056};
3057
3058/// \brief Member lookup function that determines whether a given C++
3059/// method overrides a method in a base class, to be used with
3060/// CXXRecordDecl::lookupInBases().
John McCallaf8e6ed2009-11-12 03:15:40 +00003061static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregora8f32e02009-10-06 17:59:45 +00003062 CXXBasePath &Path,
3063 void *UserData) {
3064 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlsson95496802009-11-26 20:50:40 +00003065
Douglas Gregora8f32e02009-10-06 17:59:45 +00003066 FindOverriddenMethodData *Data
3067 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlsson95496802009-11-26 20:50:40 +00003068
3069 DeclarationName Name = Data->Method->getDeclName();
3070
3071 // FIXME: Do we care about other names here too?
3072 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCallad00b772010-06-16 08:42:20 +00003073 // We really want to find the base class destructor here.
Anders Carlsson95496802009-11-26 20:50:40 +00003074 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
3075 CanQualType CT = Data->S->Context.getCanonicalType(T);
3076
Anders Carlsson1a689722009-11-27 01:26:58 +00003077 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlsson95496802009-11-26 20:50:40 +00003078 }
3079
3080 for (Path.Decls = BaseRecord->lookup(Name);
Douglas Gregora8f32e02009-10-06 17:59:45 +00003081 Path.Decls.first != Path.Decls.second;
3082 ++Path.Decls.first) {
John McCall52a02752010-06-16 09:33:39 +00003083 NamedDecl *D = *Path.Decls.first;
John McCallad00b772010-06-16 08:42:20 +00003084 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
3085 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregora8f32e02009-10-06 17:59:45 +00003086 return true;
3087 }
3088 }
3089
3090 return false;
3091}
3092
Sebastian Redla165da02009-11-18 21:51:29 +00003093/// AddOverriddenMethods - See if a method overrides any in the base classes,
3094/// and if so, check that it's a valid override and remember it.
3095void Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
3096 // Look for virtual methods in base classes that this method might override.
3097 CXXBasePaths Paths;
3098 FindOverriddenMethodData Data;
3099 Data.Method = MD;
3100 Data.S = this;
3101 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
3102 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
3103 E = Paths.found_decls_end(); I != E; ++I) {
3104 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
3105 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Sean Huntbbd37c62009-11-21 08:43:09 +00003106 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
3107 !CheckOverridingFunctionAttributes(MD, OldMD))
Anders Carlsson3aaf4862009-12-04 05:51:56 +00003108 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redla165da02009-11-18 21:51:29 +00003109 }
3110 }
3111 }
3112}
3113
Mike Stump1eb44332009-09-09 15:08:12 +00003114NamedDecl*
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003115Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
John McCalla93c9342009-12-07 02:54:59 +00003116 QualType R, TypeSourceInfo *TInfo,
John McCall68263142009-11-18 22:49:29 +00003117 LookupResult &Previous,
Douglas Gregore542c862009-06-23 23:11:28 +00003118 MultiTemplateParamsArg TemplateParamLists,
Chris Lattnereaaebc72009-04-25 08:06:05 +00003119 bool IsFunctionDefinition, bool &Redeclaration) {
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003120 assert(R.getTypePtr()->isFunctionType());
3121
Abramo Bagnara25777432010-08-11 22:01:17 +00003122 // TODO: consider using NameInfo for diagnostic.
3123 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3124 DeclarationName Name = NameInfo.getName();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003125 FunctionDecl::StorageClass SC = FunctionDecl::None;
3126 switch (D.getDeclSpec().getStorageClassSpec()) {
3127 default: assert(0 && "Unknown storage class!");
3128 case DeclSpec::SCS_auto:
3129 case DeclSpec::SCS_register:
3130 case DeclSpec::SCS_mutable:
Mike Stump1eb44332009-09-09 15:08:12 +00003131 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregor04495c82009-02-24 01:23:02 +00003132 diag::err_typecheck_sclass_func);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003133 D.setInvalidType();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003134 break;
3135 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
3136 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
Douglas Gregor04495c82009-02-24 01:23:02 +00003137 case DeclSpec::SCS_static: {
Douglas Gregor656de632009-03-11 23:52:16 +00003138 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor04495c82009-02-24 01:23:02 +00003139 // C99 6.7.1p5:
3140 // The declaration of an identifier for a function that has
3141 // block scope shall have no explicit storage-class specifier
3142 // other than extern
3143 // See also (C++ [dcl.stc]p4).
Mike Stump1eb44332009-09-09 15:08:12 +00003144 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregor04495c82009-02-24 01:23:02 +00003145 diag::err_static_block_func);
3146 SC = FunctionDecl::None;
3147 } else
Mike Stump1eb44332009-09-09 15:08:12 +00003148 SC = FunctionDecl::Static;
Douglas Gregor04495c82009-02-24 01:23:02 +00003149 break;
3150 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003151 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
3152 }
3153
Eli Friedman63054b32009-04-19 20:27:55 +00003154 if (D.getDeclSpec().isThreadSpecified())
3155 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
3156
John McCall3f9a8a62009-08-11 06:59:38 +00003157 bool isFriend = D.getDeclSpec().isFriendSpecified();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003158 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor021c3b32009-03-11 23:00:04 +00003159 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003160 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
3161
Douglas Gregor16573fa2010-04-19 22:54:31 +00003162 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
3163 FunctionDecl::StorageClass SCAsWritten
Abramo Bagnara35f9a192010-07-30 16:47:02 +00003164 = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
Douglas Gregor16573fa2010-04-19 22:54:31 +00003165
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003166 // Check that the return type is not an abstract class type.
Anders Carlsson8211eff2009-03-24 01:19:16 +00003167 // For record types, this is done by the AbstractClassUsageDiagnoser once
Mike Stump1eb44332009-09-09 15:08:12 +00003168 // the class has been completely parsed.
Anders Carlsson8211eff2009-03-24 01:19:16 +00003169 if (!DC->isRecord() &&
Mike Stump1eb44332009-09-09 15:08:12 +00003170 RequireNonAbstractType(D.getIdentifierLoc(),
John McCall183700f2009-09-21 23:43:11 +00003171 R->getAs<FunctionType>()->getResultType(),
Mike Stump1eb44332009-09-09 15:08:12 +00003172 diag::err_abstract_type_in_decl,
Anders Carlsson8211eff2009-03-24 01:19:16 +00003173 AbstractReturnType))
Chris Lattnereaaebc72009-04-25 08:06:05 +00003174 D.setInvalidType();
Mike Stump1eb44332009-09-09 15:08:12 +00003175
Chris Lattnerbb749822009-04-11 19:17:25 +00003176 // Do not allow returning a objc interface by-value.
John McCallc12c5bb2010-05-15 11:32:37 +00003177 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
Chris Lattnerbb749822009-04-11 19:17:25 +00003178 Diag(D.getIdentifierLoc(),
3179 diag::err_object_cannot_be_passed_returned_by_value) << 0
John McCall183700f2009-09-21 23:43:11 +00003180 << R->getAs<FunctionType>()->getResultType();
Chris Lattnereaaebc72009-04-25 08:06:05 +00003181 D.setInvalidType();
Chris Lattnerbb749822009-04-11 19:17:25 +00003182 }
Douglas Gregore542c862009-06-23 23:11:28 +00003183
Douglas Gregor021c3b32009-03-11 23:00:04 +00003184 bool isVirtualOkay = false;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003185 FunctionDecl *NewFD;
John McCall02cace72009-08-28 07:59:38 +00003186
John McCall3f9a8a62009-08-11 06:59:38 +00003187 if (isFriend) {
John McCall3f9a8a62009-08-11 06:59:38 +00003188 // C++ [class.friend]p5
3189 // A function can be defined in a friend declaration of a
3190 // class . . . . Such a function is implicitly inline.
3191 isInline |= IsFunctionDefinition;
John McCall02cace72009-08-28 07:59:38 +00003192 }
John McCall3f9a8a62009-08-11 06:59:38 +00003193
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003194 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003195 // This is a C++ constructor declaration.
3196 assert(DC->isRecord() &&
3197 "Constructors can only be declared in a member context");
3198
Chris Lattner65401802009-04-25 08:28:21 +00003199 R = CheckConstructorDeclarator(D, R, SC);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003200
3201 // Create the new declaration
Mike Stump1eb44332009-09-09 15:08:12 +00003202 NewFD = CXXConstructorDecl::Create(Context,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003203 cast<CXXRecordDecl>(DC),
Abramo Bagnara25777432010-08-11 22:01:17 +00003204 NameInfo, R, TInfo,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003205 isExplicit, isInline,
3206 /*isImplicitlyDeclared=*/false);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003207 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003208 // This is a C++ destructor declaration.
3209 if (DC->isRecord()) {
Douglas Gregord92ec472010-07-01 05:10:53 +00003210 R = CheckDestructorDeclarator(D, R, SC);
Mike Stump1eb44332009-09-09 15:08:12 +00003211
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003212 NewFD = CXXDestructorDecl::Create(Context,
3213 cast<CXXRecordDecl>(DC),
Abramo Bagnara25777432010-08-11 22:01:17 +00003214 NameInfo, R,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003215 isInline,
3216 /*isImplicitlyDeclared=*/false);
John McCall21ef0fa2010-03-11 09:03:00 +00003217 NewFD->setTypeSourceInfo(TInfo);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003218
Douglas Gregor021c3b32009-03-11 23:00:04 +00003219 isVirtualOkay = true;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003220 } else {
3221 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
3222
3223 // Create a FunctionDecl to satisfy the function definition parsing
3224 // code path.
3225 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00003226 Name, R, TInfo, SC, SCAsWritten, isInline,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00003227 /*hasPrototype=*/true);
Chris Lattnereaaebc72009-04-25 08:06:05 +00003228 D.setInvalidType();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003229 }
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003230 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003231 if (!DC->isRecord()) {
3232 Diag(D.getIdentifierLoc(),
3233 diag::err_conv_function_not_member);
3234 return 0;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003235 }
Mike Stump1eb44332009-09-09 15:08:12 +00003236
Chris Lattner6e475012009-04-25 08:35:12 +00003237 CheckConversionDeclarator(D, R, SC);
3238 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
Abramo Bagnara25777432010-08-11 22:01:17 +00003239 NameInfo, R, TInfo,
Chris Lattner6e475012009-04-25 08:35:12 +00003240 isInline, isExplicit);
Mike Stump1eb44332009-09-09 15:08:12 +00003241
Chris Lattner6e475012009-04-25 08:35:12 +00003242 isVirtualOkay = true;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003243 } else if (DC->isRecord()) {
Anders Carlsson4649cac2009-04-30 22:41:11 +00003244 // If the of the function is the same as the name of the record, then this
Mike Stump1eb44332009-09-09 15:08:12 +00003245 // must be an invalid constructor that has a return type.
3246 // (The parser checks for a return type and makes the declarator a
Anders Carlsson4649cac2009-04-30 22:41:11 +00003247 // constructor if it has no return type).
Mike Stump1eb44332009-09-09 15:08:12 +00003248 // must have an invalid constructor that has a return type
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00003249 if (Name.getAsIdentifierInfo() &&
3250 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
Anders Carlsson4649cac2009-04-30 22:41:11 +00003251 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
3252 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3253 << SourceRange(D.getIdentifierLoc());
3254 return 0;
3255 }
Mike Stump1eb44332009-09-09 15:08:12 +00003256
Anders Carlsson67bf2e72009-11-15 18:59:32 +00003257 bool isStatic = SC == FunctionDecl::Static;
3258
3259 // [class.free]p1:
3260 // Any allocation function for a class T is a static member
3261 // (even if not explicitly declared static).
3262 if (Name.getCXXOverloadedOperator() == OO_New ||
3263 Name.getCXXOverloadedOperator() == OO_Array_New)
3264 isStatic = true;
Anders Carlsson1f126bd2009-11-15 19:08:46 +00003265
3266 // [class.free]p6 Any deallocation function for a class X is a static member
3267 // (even if not explicitly declared static).
3268 if (Name.getCXXOverloadedOperator() == OO_Delete ||
3269 Name.getCXXOverloadedOperator() == OO_Array_Delete)
3270 isStatic = true;
Anders Carlsson67bf2e72009-11-15 18:59:32 +00003271
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003272 // This is a C++ method declaration.
3273 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Abramo Bagnara25777432010-08-11 22:01:17 +00003274 NameInfo, R, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00003275 isStatic, SCAsWritten, isInline);
Douglas Gregor021c3b32009-03-11 23:00:04 +00003276
Anders Carlsson1f126bd2009-11-15 19:08:46 +00003277 isVirtualOkay = !isStatic;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003278 } else {
Douglas Gregord874def2009-03-19 18:33:54 +00003279 // Determine whether the function was written with a
3280 // prototype. This true when:
3281 // - we're in C++ (where every function has a prototype),
3282 // - there is a prototype in the declarator, or
3283 // - the type R of the function is some kind of typedef or other reference
3284 // to a type name (which eventually refers to a function type).
Mike Stump1eb44332009-09-09 15:08:12 +00003285 bool HasPrototype =
Chris Lattner0d48bf92009-03-17 23:17:04 +00003286 getLangOptions().CPlusPlus ||
Douglas Gregor13d7a322009-03-19 18:14:46 +00003287 (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) ||
Douglas Gregord1659a62009-03-23 16:26:51 +00003288 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
Mike Stump1eb44332009-09-09 15:08:12 +00003289
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003290 NewFD = FunctionDecl::Create(Context, DC,
Abramo Bagnara25777432010-08-11 22:01:17 +00003291 NameInfo, R, TInfo, SC, SCAsWritten, isInline,
Douglas Gregor16573fa2010-04-19 22:54:31 +00003292 HasPrototype);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003293 }
3294
Chris Lattnereaaebc72009-04-25 08:06:05 +00003295 if (D.isInvalidType())
Chris Lattner584be452009-04-25 05:44:12 +00003296 NewFD->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003297
John McCallb6217662010-03-15 10:12:16 +00003298 SetNestedNameSpecifier(NewFD, D);
3299
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003300 // Set the lexical context. If the declarator has a C++
John McCall02cace72009-08-28 07:59:38 +00003301 // scope specifier, or is the object of a friend declaration, the
3302 // lexical context will be different from the semantic context.
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003303 NewFD->setLexicalDeclContext(CurContext);
3304
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003305 // Match up the template parameter lists with the scope specifier, then
3306 // determine whether we have a template or a template specialization.
Douglas Gregorc5c903a2009-06-24 00:23:40 +00003307 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003308 bool isExplicitSpecialization = false;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003309 bool isFunctionTemplateSpecialization = false;
Abramo Bagnara9b934882010-06-12 08:15:14 +00003310 unsigned NumMatchedTemplateParamLists = TemplateParamLists.size();
Douglas Gregor0167f3c2010-07-14 23:14:12 +00003311 bool Invalid = false;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00003312 if (TemplateParameterList *TemplateParams
3313 = MatchTemplateParametersToScopeSpecifier(
3314 D.getDeclSpec().getSourceRange().getBegin(),
3315 D.getCXXScopeSpec(),
Douglas Gregor27eeb5e2009-07-22 22:05:02 +00003316 (TemplateParameterList**)TemplateParamLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003317 TemplateParamLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00003318 isFriend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00003319 isExplicitSpecialization,
3320 Invalid)) {
Abramo Bagnara9b934882010-06-12 08:15:14 +00003321 // All but one template parameter lists have been matching.
3322 --NumMatchedTemplateParamLists;
3323
Douglas Gregorc5c903a2009-06-24 00:23:40 +00003324 if (TemplateParams->size() > 0) {
3325 // This is a function template
Mike Stump1eb44332009-09-09 15:08:12 +00003326
Douglas Gregor05396e22009-08-25 17:23:04 +00003327 // Check that we can declare a template here.
3328 if (CheckTemplateDeclScope(S, TemplateParams))
3329 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003330
Douglas Gregord60e1052009-08-27 16:57:43 +00003331 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
Douglas Gregorc5c903a2009-06-24 00:23:40 +00003332 NewFD->getLocation(),
3333 Name, TemplateParams,
3334 NewFD);
Douglas Gregord60e1052009-08-27 16:57:43 +00003335 FunctionTemplate->setLexicalDeclContext(CurContext);
Douglas Gregorc5c903a2009-06-24 00:23:40 +00003336 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
3337 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003338 // This is a function template specialization.
3339 isFunctionTemplateSpecialization = true;
John McCall7ad650f2010-03-24 07:46:06 +00003340
John McCallaf2094e2010-04-08 09:05:18 +00003341 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
John McCall7ad650f2010-03-24 07:46:06 +00003342 if (isFriend && isFunctionTemplateSpecialization) {
John McCall5fd378b2010-03-24 08:27:58 +00003343 // We want to remove the "template<>", found here.
3344 SourceRange RemoveRange = TemplateParams->getSourceRange();
3345
3346 // If we remove the template<> and the name is not a
3347 // template-id, we're actually silently creating a problem:
3348 // the friend declaration will refer to an untemplated decl,
3349 // and clearly the user wants a template specialization. So
3350 // we need to insert '<>' after the name.
3351 SourceLocation InsertLoc;
3352 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
3353 InsertLoc = D.getName().getSourceRange().getEnd();
3354 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
3355 }
3356
John McCall7ad650f2010-03-24 07:46:06 +00003357 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
John McCall5fd378b2010-03-24 08:27:58 +00003358 << Name << RemoveRange
Douglas Gregor849b2432010-03-31 17:46:05 +00003359 << FixItHint::CreateRemoval(RemoveRange)
3360 << FixItHint::CreateInsertion(InsertLoc, "<>");
John McCall7ad650f2010-03-24 07:46:06 +00003361 }
Douglas Gregorc5c903a2009-06-24 00:23:40 +00003362 }
Mike Stump1eb44332009-09-09 15:08:12 +00003363 }
Abramo Bagnara9b934882010-06-12 08:15:14 +00003364
Douglas Gregor98c2e622010-07-28 23:59:57 +00003365 if (NumMatchedTemplateParamLists > 0 && D.getCXXScopeSpec().isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00003366 NewFD->setTemplateParameterListsInfo(Context,
3367 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00003368 (TemplateParameterList**)TemplateParamLists.release());
3369 }
3370
Douglas Gregor0167f3c2010-07-14 23:14:12 +00003371 if (Invalid) {
3372 NewFD->setInvalidDecl();
3373 if (FunctionTemplate)
3374 FunctionTemplate->setInvalidDecl();
3375 }
3376
Douglas Gregor021c3b32009-03-11 23:00:04 +00003377 // C++ [dcl.fct.spec]p5:
3378 // The virtual specifier shall only be used in declarations of
3379 // nonstatic class member functions that appear within a
3380 // member-specification of a class declaration; see 10.3.
3381 //
Chris Lattnereaaebc72009-04-25 08:06:05 +00003382 if (isVirtual && !NewFD->isInvalidDecl()) {
Douglas Gregor021c3b32009-03-11 23:00:04 +00003383 if (!isVirtualOkay) {
Mike Stump1eb44332009-09-09 15:08:12 +00003384 Diag(D.getDeclSpec().getVirtualSpecLoc(),
Douglas Gregor021c3b32009-03-11 23:00:04 +00003385 diag::err_virtual_non_function);
3386 } else if (!CurContext->isRecord()) {
3387 // 'virtual' was specified outside of the class.
3388 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class)
Douglas Gregor849b2432010-03-31 17:46:05 +00003389 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
Douglas Gregor021c3b32009-03-11 23:00:04 +00003390 } else {
3391 // Okay: Add virtual to the method.
Douglas Gregor021c3b32009-03-11 23:00:04 +00003392 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC);
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00003393 CurClass->setMethodAsVirtual(NewFD);
Douglas Gregor021c3b32009-03-11 23:00:04 +00003394 }
3395 }
3396
Douglas Gregored328c62010-08-06 11:44:10 +00003397 // C++ [dcl.fct.spec]p3:
3398 // The inline specifier shall not appear on a block scope function declaration.
3399 if (isInline && !NewFD->isInvalidDecl() && getLangOptions().CPlusPlus) {
3400 if (CurContext->isFunctionOrMethod()) {
3401 // 'inline' is not allowed on block scope function declaration.
3402 Diag(D.getDeclSpec().getInlineSpecLoc(),
3403 diag::err_inline_declaration_block_scope) << Name
3404 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
3405 }
3406 }
3407
Anders Carlsson0757c8c2010-01-24 16:49:46 +00003408 // C++ [dcl.fct.spec]p6:
3409 // The explicit specifier shall be used only in the declaration of a
3410 // constructor or conversion function within its class definition; see 12.3.1
3411 // and 12.3.2.
3412 if (isExplicit && !NewFD->isInvalidDecl()) {
3413 if (!CurContext->isRecord()) {
3414 // 'explicit' was specified outside of the class.
3415 Diag(D.getDeclSpec().getExplicitSpecLoc(),
3416 diag::err_explicit_out_of_class)
Douglas Gregor849b2432010-03-31 17:46:05 +00003417 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
Anders Carlsson0757c8c2010-01-24 16:49:46 +00003418 } else if (!isa<CXXConstructorDecl>(NewFD) &&
3419 !isa<CXXConversionDecl>(NewFD)) {
3420 // 'explicit' was specified on a function that wasn't a constructor
3421 // or conversion function.
3422 Diag(D.getDeclSpec().getExplicitSpecLoc(),
3423 diag::err_explicit_non_ctor_or_conv_function)
Douglas Gregor849b2432010-03-31 17:46:05 +00003424 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
Anders Carlsson0757c8c2010-01-24 16:49:46 +00003425 }
3426 }
3427
John McCall68263142009-11-18 22:49:29 +00003428 // Filter out previous declarations that don't match the scope.
3429 FilterLookupForScope(*this, Previous, DC, S, NewFD->hasLinkage());
3430
Douglas Gregora735b202009-10-13 14:39:41 +00003431 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00003432 // DC is the namespace in which the function is being declared.
3433 assert((DC->isFileContext() || !Previous.empty()) &&
3434 "previously-undeclared friend function being created "
3435 "in a non-namespace context");
3436
John McCallb0cb0222010-03-27 05:57:59 +00003437 // For now, claim that the objects have no previous declaration.
Douglas Gregora735b202009-10-13 14:39:41 +00003438 if (FunctionTemplate) {
John McCallb0cb0222010-03-27 05:57:59 +00003439 FunctionTemplate->setObjectOfFriendDecl(false);
Douglas Gregora735b202009-10-13 14:39:41 +00003440 FunctionTemplate->setAccess(AS_public);
3441 }
John McCall77e8b112010-04-13 20:37:33 +00003442 NewFD->setObjectOfFriendDecl(false);
Douglas Gregora735b202009-10-13 14:39:41 +00003443 NewFD->setAccess(AS_public);
3444 }
3445
Mike Stump1eb44332009-09-09 15:08:12 +00003446 if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) &&
Douglas Gregor656de632009-03-11 23:52:16 +00003447 !CurContext->isRecord()) {
3448 // C++ [class.static]p1:
3449 // A data or function member of a class may be declared static
3450 // in a class definition, in which case it is a static member of
3451 // the class.
3452
3453 // Complain about the 'static' specifier if it's on an out-of-line
3454 // member function definition.
Mike Stump1eb44332009-09-09 15:08:12 +00003455 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregor656de632009-03-11 23:52:16 +00003456 diag::err_static_out_of_line)
Douglas Gregor849b2432010-03-31 17:46:05 +00003457 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregor656de632009-03-11 23:52:16 +00003458 }
3459
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003460 // Handle GNU asm-label extension (encoded as an attribute).
3461 if (Expr *E = (Expr*) D.getAsmLabel()) {
3462 // The parser guarantees this is a string.
Mike Stump1eb44332009-09-09 15:08:12 +00003463 StringLiteral *SE = cast<StringLiteral>(E);
Sean Huntcf807c42010-08-18 23:23:40 +00003464 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
3465 SE->getString()));
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003466 }
3467
Chris Lattner2dbd2852009-04-25 06:12:16 +00003468 // Copy the parameter declarations from the declarator D to the function
3469 // declaration NewFD, if they are available. First scavenge them into Params.
3470 llvm::SmallVector<ParmVarDecl*, 16> Params;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003471 if (D.getNumTypeObjects() > 0) {
3472 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3473
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003474 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
3475 // function that takes no arguments, not a function that takes a
3476 // single void argument.
3477 // We let through "const void" here because Sema::GetTypeForDeclarator
3478 // already checks for that case.
3479 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3480 FTI.ArgInfo[0].Param &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00003481 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()) {
Chris Lattner2dbd2852009-04-25 06:12:16 +00003482 // Empty arg list, don't push any params.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003483 ParmVarDecl *Param = FTI.ArgInfo[0].Param.getAs<ParmVarDecl>();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003484
3485 // In C++, the empty parameter-type-list must be spelled "void"; a
3486 // typedef of void is not permitted.
3487 if (getLangOptions().CPlusPlus &&
Chris Lattner584be452009-04-25 05:44:12 +00003488 Param->getType().getUnqualifiedType() != Context.VoidTy)
Douglas Gregora3a83512009-04-01 23:51:29 +00003489 Diag(Param->getLocation(), diag::err_param_typedef_of_void);
Chris Lattner2dbd2852009-04-25 06:12:16 +00003490 // FIXME: Leaks decl?
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003491 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00003492 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
3493 ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
3494 assert(Param->getDeclContext() != NewFD && "Was set before ?");
3495 Param->setDeclContext(NewFD);
3496 Params.push_back(Param);
John McCallf19de1c2010-04-14 01:27:20 +00003497
3498 if (Param->isInvalidDecl())
3499 NewFD->setInvalidDecl();
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00003500 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003501 }
Mike Stump1eb44332009-09-09 15:08:12 +00003502
John McCall183700f2009-09-21 23:43:11 +00003503 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner1ad9b282009-04-25 06:03:53 +00003504 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003505 // following example, we'll need to synthesize (unnamed)
3506 // parameters for use in the declaration.
3507 //
3508 // @code
3509 // typedef void fn(int);
3510 // fn f;
3511 // @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003512
Chris Lattner1ad9b282009-04-25 06:03:53 +00003513 // Synthesize a parameter for each argument type.
Chris Lattner1ad9b282009-04-25 06:03:53 +00003514 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
3515 AE = FT->arg_type_end(); AI != AE; ++AI) {
John McCall82dc0092010-06-04 11:21:44 +00003516 ParmVarDecl *Param =
3517 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
Chris Lattner1ad9b282009-04-25 06:03:53 +00003518 Params.push_back(Param);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003519 }
Chris Lattner84bb9442009-04-25 18:38:18 +00003520 } else {
3521 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
3522 "Should not need args for typedef of non-prototype fn");
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003523 }
Chris Lattner2dbd2852009-04-25 06:12:16 +00003524 // Finally, we know we have the right number of parameters, install them.
Douglas Gregor838db382010-02-11 01:19:42 +00003525 NewFD->setParams(Params.data(), Params.size());
Mike Stump1eb44332009-09-09 15:08:12 +00003526
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00003527 // If the declarator is a template-id, translate the parser's template
3528 // argument list into our AST format.
3529 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00003530 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00003531 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
3532 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00003533 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
3534 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00003535 ASTTemplateArgsPtr TemplateArgsPtr(*this,
3536 TemplateId->getTemplateArgs(),
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00003537 TemplateId->NumArgs);
3538 translateTemplateArguments(TemplateArgsPtr,
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00003539 TemplateArgs);
3540 TemplateArgsPtr.release();
3541
3542 HasExplicitTemplateArgs = true;
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00003543
3544 if (FunctionTemplate) {
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003545 // FIXME: Diagnose function template with explicit template
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00003546 // arguments.
3547 HasExplicitTemplateArgs = false;
3548 } else if (!isFunctionTemplateSpecialization &&
3549 !D.getDeclSpec().isFriendSpecified()) {
3550 // We have encountered something that the user meant to be a
3551 // specialization (because it has explicitly-specified template
3552 // arguments) but that was not introduced with a "template<>" (or had
3553 // too few of them).
3554 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
3555 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
Douglas Gregor849b2432010-03-31 17:46:05 +00003556 << FixItHint::CreateInsertion(
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00003557 D.getDeclSpec().getSourceRange().getBegin(),
3558 "template<> ");
3559 isFunctionTemplateSpecialization = true;
John McCall7ad650f2010-03-24 07:46:06 +00003560 } else {
3561 // "friend void foo<>(int);" is an implicit specialization decl.
3562 isFunctionTemplateSpecialization = true;
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00003563 }
John McCallaf2094e2010-04-08 09:05:18 +00003564 } else if (isFriend && isFunctionTemplateSpecialization) {
3565 // This combination is only possible in a recovery case; the user
3566 // wrote something like:
3567 // template <> friend void foo(int);
3568 // which we're recovering from as if the user had written:
3569 // friend void foo<>(int);
3570 // Go ahead and fake up a template id.
3571 HasExplicitTemplateArgs = true;
3572 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
3573 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00003574 }
John McCall68263142009-11-18 22:49:29 +00003575
John McCallaf2094e2010-04-08 09:05:18 +00003576 // If it's a friend (and only if it's a friend), it's possible
3577 // that either the specialized function type or the specialized
3578 // template is dependent, and therefore matching will fail. In
3579 // this case, don't check the specialization yet.
3580 if (isFunctionTemplateSpecialization && isFriend &&
3581 (NewFD->getType()->isDependentType() || DC->isDependentContext())) {
3582 assert(HasExplicitTemplateArgs &&
3583 "friend function specialization without template args");
3584 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
3585 Previous))
Douglas Gregor036ada22010-03-24 17:31:23 +00003586 NewFD->setInvalidDecl();
John McCallaf2094e2010-04-08 09:05:18 +00003587 } else if (isFunctionTemplateSpecialization) {
3588 if (CheckFunctionTemplateSpecialization(NewFD,
3589 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
3590 Previous))
3591 NewFD->setInvalidDecl();
3592 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
3593 if (CheckMemberSpecialization(NewFD, Previous))
3594 NewFD->setInvalidDecl();
3595 }
John McCallba9d8532010-04-13 06:39:49 +00003596
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003597 // Perform semantic checking on the function declaration.
3598 bool OverloadableAttrRequired = false; // FIXME: HACK!
John McCall9f54ad42009-12-10 09:41:52 +00003599 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization,
Douglas Gregorfd056bc2009-10-13 16:30:37 +00003600 Redeclaration, /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003601
John McCall68263142009-11-18 22:49:29 +00003602 assert((NewFD->isInvalidDecl() || !Redeclaration ||
3603 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
3604 "previous declaration set still overloaded");
3605
John McCall76d32642010-04-24 01:30:58 +00003606 NamedDecl *PrincipalDecl = (FunctionTemplate
3607 ? cast<NamedDecl>(FunctionTemplate)
3608 : NewFD);
3609
John McCallb0cb0222010-03-27 05:57:59 +00003610 if (isFriend && Redeclaration) {
John McCallba9d8532010-04-13 06:39:49 +00003611 AccessSpecifier Access = AS_public;
3612 if (!NewFD->isInvalidDecl())
3613 Access = NewFD->getPreviousDeclaration()->getAccess();
3614
John McCallb0cb0222010-03-27 05:57:59 +00003615 NewFD->setAccess(Access);
John McCall76d32642010-04-24 01:30:58 +00003616 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
3617
3618 PrincipalDecl->setObjectOfFriendDecl(true);
John McCallb0cb0222010-03-27 05:57:59 +00003619 }
3620
John McCall76d32642010-04-24 01:30:58 +00003621 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
3622 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
3623 PrincipalDecl->setNonMemberOperator();
3624
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00003625 // If we have a function template, check the template parameter
3626 // list. This will check and merge default template arguments.
3627 if (FunctionTemplate) {
3628 FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration();
3629 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
3630 PrevTemplate? PrevTemplate->getTemplateParameters() : 0,
3631 D.getDeclSpec().isFriendSpecified()? TPC_FriendFunctionTemplate
3632 : TPC_FunctionTemplate);
3633 }
3634
Chris Lattnereaaebc72009-04-25 08:06:05 +00003635 if (D.getCXXScopeSpec().isSet() && !NewFD->isInvalidDecl()) {
John McCall46460a62010-01-20 21:53:11 +00003636 // Fake up an access specifier if it's supposed to be a class member.
John McCall86ff3082010-02-04 22:26:26 +00003637 if (!Redeclaration && isa<CXXRecordDecl>(NewFD->getDeclContext()))
John McCall46460a62010-01-20 21:53:11 +00003638 NewFD->setAccess(AS_public);
3639
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003640 // An out-of-line member function declaration must also be a
3641 // definition (C++ [dcl.meaning]p1).
Douglas Gregor741fab62009-10-08 15:54:21 +00003642 // Note that this is not the case for explicit specializations of
3643 // function templates or member functions of class templates, per
Chandler Carruthb21fc4a2010-07-16 04:32:28 +00003644 // C++ [temp.expl.spec]p2. We also allow these declarations as an extension
3645 // for compatibility with old SWIG code which likes to generate them.
Douglas Gregord85cef52009-09-17 19:51:30 +00003646 if (!IsFunctionDefinition && !isFriend &&
Douglas Gregor37d681852009-10-12 22:27:17 +00003647 !isFunctionTemplateSpecialization && !isExplicitSpecialization) {
Chandler Carruthb21fc4a2010-07-16 04:32:28 +00003648 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003649 << D.getCXXScopeSpec().getRange();
Chandler Carruthb21fc4a2010-07-16 04:32:28 +00003650 }
3651 if (!Redeclaration && !(isFriend && CurContext->isDependentContext())) {
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003652 // The user tried to provide an out-of-line definition for a
3653 // function that is a member of a class or namespace, but there
Mike Stump1eb44332009-09-09 15:08:12 +00003654 // was no such member function declared (C++ [class.mfct]p2,
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003655 // C++ [namespace.memdef]p2). For example:
Mike Stump1eb44332009-09-09 15:08:12 +00003656 //
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003657 // class X {
3658 // void f() const;
Mike Stump1eb44332009-09-09 15:08:12 +00003659 // };
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003660 //
3661 // void X::f() { } // ill-formed
3662 //
3663 // Complain about this problem, and attempt to suggest close
3664 // matches (e.g., those that differ only in cv-qualifiers and
3665 // whether the parameter types are references).
3666 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
Douglas Gregor3f093272009-10-13 21:16:44 +00003667 << Name << DC << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00003668 NewFD->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003669
John McCalla24dc2e2009-11-17 02:14:36 +00003670 LookupResult Prev(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +00003671 ForRedeclaration);
John McCalla24dc2e2009-11-17 02:14:36 +00003672 LookupQualifiedName(Prev, DC);
Mike Stump1eb44332009-09-09 15:08:12 +00003673 assert(!Prev.isAmbiguous() &&
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003674 "Cannot have an ambiguity in previous-declaration lookup");
3675 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
3676 Func != FuncEnd; ++Func) {
3677 if (isa<FunctionDecl>(*Func) &&
3678 isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
3679 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
3680 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003681 }
3682 }
3683
3684 // Handle attributes. We need to have merged decls when handling attributes
3685 // (for example to check for conflicts, etc).
3686 // FIXME: This needs to happen before we merge declarations. Then,
3687 // let attribute merging cope with attribute conflicts.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003688 ProcessDeclAttributes(S, NewFD, D);
Ryan Flynn478fbc62009-07-25 22:29:44 +00003689
3690 // attributes declared post-definition are currently ignored
Sean Huntcf807c42010-08-18 23:23:40 +00003691 // FIXME: This should happen during attribute merging
John McCall68263142009-11-18 22:49:29 +00003692 if (Redeclaration && Previous.isSingleResult()) {
3693 const FunctionDecl *Def;
3694 FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00003695 if (PrevFD && PrevFD->hasBody(Def) && D.hasAttributes()) {
Ryan Flynn478fbc62009-07-25 22:29:44 +00003696 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
3697 Diag(Def->getLocation(), diag::note_previous_definition);
3698 }
3699 }
3700
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003701 AddKnownFunctionAttributes(NewFD);
3702
Sean Huntcf807c42010-08-18 23:23:40 +00003703 if (OverloadableAttrRequired && !NewFD->hasAttr<OverloadableAttr>()) {
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003704 // If a function name is overloadable in C, then every function
3705 // with that name must be marked "overloadable".
3706 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
3707 << Redeclaration << NewFD;
John McCall68263142009-11-18 22:49:29 +00003708 if (!Previous.empty())
3709 Diag(Previous.getRepresentativeDecl()->getLocation(),
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003710 diag::note_attribute_overloadable_prev_overload);
Sean Huntcf807c42010-08-18 23:23:40 +00003711 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(), Context));
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003712 }
3713
Douglas Gregord9455382010-08-06 13:50:58 +00003714 if (NewFD->hasAttr<OverloadableAttr>() &&
3715 !NewFD->getType()->getAs<FunctionProtoType>()) {
3716 Diag(NewFD->getLocation(),
3717 diag::err_attribute_overloadable_no_prototype)
3718 << NewFD;
3719
3720 // Turn this into a variadic function with no parameters.
3721 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
3722 QualType R = Context.getFunctionType(FT->getResultType(),
3723 0, 0, true, 0, false, false, 0, 0,
3724 FT->getExtInfo());
3725 NewFD->setType(R);
3726 }
3727
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00003728 // If there's a #pragma GCC visibility in scope, and this isn't a class
3729 // member, set the visibility of this function.
3730 if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
3731 AddPushedVisibilityAttribute(NewFD);
3732
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003733 // If this is a locally-scoped extern C function, update the
3734 // map of such names.
Douglas Gregor48a83b52009-09-12 00:17:51 +00003735 if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
Chris Lattnereaaebc72009-04-25 08:06:05 +00003736 && !NewFD->isInvalidDecl())
John McCall68263142009-11-18 22:49:29 +00003737 RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003738
Argyrios Kyrtzidis16f19302009-06-25 18:22:24 +00003739 // Set this FunctionDecl's range up to the right paren.
3740 NewFD->setLocEnd(D.getSourceRange().getEnd());
3741
Douglas Gregore53060f2009-06-25 22:08:12 +00003742 if (FunctionTemplate && NewFD->isInvalidDecl())
3743 FunctionTemplate->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003744
Douglas Gregore53060f2009-06-25 22:08:12 +00003745 if (FunctionTemplate)
3746 return FunctionTemplate;
Mike Stump1eb44332009-09-09 15:08:12 +00003747
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00003748 MarkUnusedFileScopedDecl(NewFD);
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +00003749
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003750 return NewFD;
3751}
3752
3753/// \brief Perform semantic checking of a new function declaration.
3754///
3755/// Performs semantic analysis of the new function declaration
3756/// NewFD. This routine performs all semantic checking that does not
3757/// require the actual declarator involved in the declaration, and is
3758/// used both for the declaration of functions as they are parsed
3759/// (called via ActOnDeclarator) and for the declaration of functions
3760/// that have been instantiated via C++ template instantiation (called
3761/// via InstantiateDecl).
3762///
Douglas Gregorfd056bc2009-10-13 16:30:37 +00003763/// \param IsExplicitSpecialiation whether this new function declaration is
3764/// an explicit specialization of the previous declaration.
3765///
Chris Lattnereaaebc72009-04-25 08:06:05 +00003766/// This sets NewFD->isInvalidDecl() to true if there was an error.
John McCall9f54ad42009-12-10 09:41:52 +00003767void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall68263142009-11-18 22:49:29 +00003768 LookupResult &Previous,
Douglas Gregorfd056bc2009-10-13 16:30:37 +00003769 bool IsExplicitSpecialization,
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003770 bool &Redeclaration,
3771 bool &OverloadableAttrRequired) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00003772 // If NewFD is already known erroneous, don't do any of this checking.
John McCallfcadea22010-08-12 00:57:17 +00003773 if (NewFD->isInvalidDecl()) {
3774 // If this is a class member, mark the class invalid immediately.
3775 // This avoids some consistency errors later.
3776 if (isa<CXXMethodDecl>(NewFD))
3777 cast<CXXMethodDecl>(NewFD)->getParent()->setInvalidDecl();
3778
Chris Lattnereaaebc72009-04-25 08:06:05 +00003779 return;
John McCallfcadea22010-08-12 00:57:17 +00003780 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003781
Eli Friedman88f7b572009-05-16 12:15:55 +00003782 if (NewFD->getResultType()->isVariablyModifiedType()) {
3783 // Functions returning a variably modified type violate C99 6.7.5.2p2
3784 // because all functions have linkage.
3785 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
3786 return NewFD->setInvalidDecl();
3787 }
3788
Douglas Gregor48a83b52009-09-12 00:17:51 +00003789 if (NewFD->isMain())
3790 CheckMain(NewFD);
John McCall8c4859a2009-07-24 03:03:21 +00003791
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003792 // Check for a previous declaration of this name.
John McCall68263142009-11-18 22:49:29 +00003793 if (Previous.empty() && NewFD->isExternC()) {
Douglas Gregor63935192009-03-02 00:19:53 +00003794 // Since we did not find anything by this name and we're declaring
3795 // an extern "C" function, look for a non-visible extern "C"
3796 // declaration with the same name.
3797 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003798 = LocallyScopedExternalDecls.find(NewFD->getDeclName());
Douglas Gregor63935192009-03-02 00:19:53 +00003799 if (Pos != LocallyScopedExternalDecls.end())
John McCall68263142009-11-18 22:49:29 +00003800 Previous.addDecl(Pos->second);
Douglas Gregor63935192009-03-02 00:19:53 +00003801 }
3802
Douglas Gregor04495c82009-02-24 01:23:02 +00003803 // Merge or overload the declaration with an existing declaration of
3804 // the same name, if appropriate.
John McCall68263142009-11-18 22:49:29 +00003805 if (!Previous.empty()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00003806 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003807 // a declaration that requires merging. If it's an overload,
3808 // there's no more work to do here; we'll just add the new
3809 // function to the scope.
Douglas Gregorae170942009-02-13 00:26:38 +00003810
John McCall68263142009-11-18 22:49:29 +00003811 NamedDecl *OldDecl = 0;
John McCall871b2e72009-12-09 03:35:25 +00003812 if (!AllowOverloadingOfFunction(Previous, Context)) {
3813 Redeclaration = true;
3814 OldDecl = Previous.getFoundDecl();
3815 } else {
Douglas Gregord9455382010-08-06 13:50:58 +00003816 if (!getLangOptions().CPlusPlus)
John McCall871b2e72009-12-09 03:35:25 +00003817 OverloadableAttrRequired = true;
3818
John McCallad00b772010-06-16 08:42:20 +00003819 switch (CheckOverload(S, NewFD, Previous, OldDecl,
3820 /*NewIsUsingDecl*/ false)) {
John McCall871b2e72009-12-09 03:35:25 +00003821 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00003822 Redeclaration = true;
John McCall871b2e72009-12-09 03:35:25 +00003823 break;
3824
3825 case Ovl_NonFunction:
3826 Redeclaration = true;
3827 break;
3828
3829 case Ovl_Overload:
3830 Redeclaration = false;
3831 break;
John McCall68263142009-11-18 22:49:29 +00003832 }
3833 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003834
John McCall68263142009-11-18 22:49:29 +00003835 if (Redeclaration) {
Douglas Gregor2dc0e642009-03-23 23:06:20 +00003836 // NewFD and OldDecl represent declarations that need to be
Mike Stump1eb44332009-09-09 15:08:12 +00003837 // merged.
Douglas Gregorcda9c672009-02-16 17:45:42 +00003838 if (MergeFunctionDecl(NewFD, OldDecl))
Chris Lattnereaaebc72009-04-25 08:06:05 +00003839 return NewFD->setInvalidDecl();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003840
John McCall68263142009-11-18 22:49:29 +00003841 Previous.clear();
3842 Previous.addDecl(OldDecl);
3843
Douglas Gregore53060f2009-06-25 22:08:12 +00003844 if (FunctionTemplateDecl *OldTemplateDecl
Douglas Gregor37d681852009-10-12 22:27:17 +00003845 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
Douglas Gregorfd056bc2009-10-13 16:30:37 +00003846 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
Douglas Gregor37d681852009-10-12 22:27:17 +00003847 FunctionTemplateDecl *NewTemplateDecl
3848 = NewFD->getDescribedFunctionTemplate();
3849 assert(NewTemplateDecl && "Template/non-template mismatch");
3850 if (CXXMethodDecl *Method
3851 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
3852 Method->setAccess(OldTemplateDecl->getAccess());
3853 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
3854 }
Douglas Gregorfd056bc2009-10-13 16:30:37 +00003855
3856 // If this is an explicit specialization of a member that is a function
3857 // template, mark it as a member specialization.
3858 if (IsExplicitSpecialization &&
3859 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
3860 NewTemplateDecl->setMemberSpecialization();
3861 assert(OldTemplateDecl->isMemberSpecialization());
3862 }
Douglas Gregor37d681852009-10-12 22:27:17 +00003863 } else {
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00003864 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
3865 NewFD->setAccess(OldDecl->getAccess());
Douglas Gregore53060f2009-06-25 22:08:12 +00003866 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
Argyrios Kyrtzidis9bedef62009-07-14 03:18:53 +00003867 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003868 }
Douglas Gregor4ce205f2009-02-06 17:46:57 +00003869 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003870
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00003871 // Semantic checking for this function declaration (in isolation).
3872 if (getLangOptions().CPlusPlus) {
3873 // C++-specific checks.
3874 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
3875 CheckConstructor(Constructor);
Anders Carlsson6d701392009-11-15 22:49:34 +00003876 } else if (CXXDestructorDecl *Destructor =
3877 dyn_cast<CXXDestructorDecl>(NewFD)) {
3878 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00003879 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson6d701392009-11-15 22:49:34 +00003880
Douglas Gregor4923aa22010-07-02 20:37:36 +00003881 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson6d701392009-11-15 22:49:34 +00003882 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00003883 if (!ClassType->isDependentType()) {
3884 DeclarationName Name
3885 = Context.DeclarationNames.getCXXDestructorName(
3886 Context.getCanonicalType(ClassType));
Abramo Bagnara25777432010-08-11 22:01:17 +00003887// NewFD->getDeclName().dump();
3888// Name.dump();
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00003889 if (NewFD->getDeclName() != Name) {
3890 Diag(NewFD->getLocation(), diag::err_destructor_name);
3891 return NewFD->setInvalidDecl();
3892 }
3893 }
Anders Carlsson6d701392009-11-15 22:49:34 +00003894
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00003895 Record->setUserDeclaredDestructor(true);
3896 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
3897 // user-defined destructor.
3898 Record->setPOD(false);
3899
3900 // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly-
3901 // declared destructor.
3902 // FIXME: C++0x: don't do this for "= default" destructors
3903 Record->setHasTrivialDestructor(false);
3904 } else if (CXXConversionDecl *Conversion
Douglas Gregor4ba31362009-12-01 17:24:26 +00003905 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00003906 ActOnConversionDeclarator(Conversion);
Douglas Gregor4ba31362009-12-01 17:24:26 +00003907 }
3908
3909 // Find any virtual functions that this function overrides.
Douglas Gregore6342c02009-12-01 17:35:23 +00003910 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
3911 if (!Method->isFunctionTemplateSpecialization() &&
3912 !Method->getDescribedFunctionTemplate())
3913 AddOverriddenMethods(Method->getParent(), Method);
3914 }
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00003915
3916 // Extra checking for C++ overloaded operators (C++ [over.oper]).
3917 if (NewFD->isOverloadedOperator() &&
3918 CheckOverloadedOperatorDeclaration(NewFD))
3919 return NewFD->setInvalidDecl();
Sean Hunta6c058d2010-01-13 09:01:02 +00003920
3921 // Extra checking for C++0x literal operators (C++0x [over.literal]).
3922 if (NewFD->getLiteralIdentifier() &&
3923 CheckLiteralOperatorDeclaration(NewFD))
3924 return NewFD->setInvalidDecl();
3925
Anders Carlsson2c59d3c2009-09-13 21:33:06 +00003926 // In C++, check default arguments now that we have merged decls. Unless
3927 // the lexical context is the class, because in this case this is done
3928 // during delayed parsing anyway.
3929 if (!CurContext->isRecord())
3930 CheckCXXDefaultArguments(NewFD);
3931 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00003932}
3933
John McCall8c4859a2009-07-24 03:03:21 +00003934void Sema::CheckMain(FunctionDecl* FD) {
John McCall13591ed2009-07-25 04:36:53 +00003935 // C++ [basic.start.main]p3: A program that declares main to be inline
3936 // or static is ill-formed.
3937 // C99 6.7.4p4: In a hosted environment, the inline function specifier
3938 // shall not appear in a declaration of main.
3939 // static main is not an error under C99, but we should warn about it.
Douglas Gregor0130f3c2009-10-27 21:01:01 +00003940 bool isInline = FD->isInlineSpecified();
John McCall13591ed2009-07-25 04:36:53 +00003941 bool isStatic = FD->getStorageClass() == FunctionDecl::Static;
3942 if (isInline || isStatic) {
3943 unsigned diagID = diag::warn_unusual_main_decl;
3944 if (isInline || getLangOptions().CPlusPlus)
3945 diagID = diag::err_unusual_main_decl;
3946
3947 int which = isStatic + (isInline << 1) - 1;
3948 Diag(FD->getLocation(), diagID) << which;
3949 }
3950
3951 QualType T = FD->getType();
3952 assert(T->isFunctionType() && "function decl is not of function type");
John McCall183700f2009-09-21 23:43:11 +00003953 const FunctionType* FT = T->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003954
John McCall13591ed2009-07-25 04:36:53 +00003955 if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
3956 // TODO: add a replacement fixit to turn the return type into 'int'.
3957 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
3958 FD->setInvalidDecl(true);
3959 }
3960
3961 // Treat protoless main() as nullary.
3962 if (isa<FunctionNoProtoType>(FT)) return;
3963
3964 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
3965 unsigned nparams = FTP->getNumArgs();
3966 assert(FD->getNumParams() == nparams);
3967
John McCall66755862009-12-24 09:58:38 +00003968 bool HasExtraParameters = (nparams > 3);
3969
3970 // Darwin passes an undocumented fourth argument of type char**. If
3971 // other platforms start sprouting these, the logic below will start
3972 // getting shifty.
3973 if (nparams == 4 &&
3974 Context.Target.getTriple().getOS() == llvm::Triple::Darwin)
3975 HasExtraParameters = false;
3976
3977 if (HasExtraParameters) {
John McCall13591ed2009-07-25 04:36:53 +00003978 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
3979 FD->setInvalidDecl(true);
3980 nparams = 3;
3981 }
3982
3983 // FIXME: a lot of the following diagnostics would be improved
3984 // if we had some location information about types.
3985
3986 QualType CharPP =
3987 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall66755862009-12-24 09:58:38 +00003988 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall13591ed2009-07-25 04:36:53 +00003989
3990 for (unsigned i = 0; i < nparams; ++i) {
3991 QualType AT = FTP->getArgType(i);
3992
3993 bool mismatch = true;
3994
3995 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
3996 mismatch = false;
3997 else if (Expected[i] == CharPP) {
3998 // As an extension, the following forms are okay:
3999 // char const **
4000 // char const * const *
4001 // char * const *
4002
John McCall0953e762009-09-24 19:53:00 +00004003 QualifierCollector qs;
John McCall13591ed2009-07-25 04:36:53 +00004004 const PointerType* PT;
Ted Kremenek6217b802009-07-29 21:53:49 +00004005 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
4006 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
John McCall13591ed2009-07-25 04:36:53 +00004007 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
4008 qs.removeConst();
4009 mismatch = !qs.empty();
4010 }
4011 }
4012
4013 if (mismatch) {
4014 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
4015 // TODO: suggest replacing given type with expected type
4016 FD->setInvalidDecl(true);
4017 }
4018 }
4019
4020 if (nparams == 1 && !FD->isInvalidDecl()) {
4021 Diag(FD->getLocation(), diag::warn_main_one_arg);
4022 }
John McCall8c4859a2009-07-24 03:03:21 +00004023}
4024
Eli Friedmanc594b322008-05-20 13:48:25 +00004025bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman3b8a36a2009-02-27 04:17:12 +00004026 // FIXME: Need strict checking. In C89, we need to check for
4027 // any assignment, increment, decrement, function-calls, or
4028 // commas outside of a sizeof. In C99, it's the same list,
4029 // except that the aforementioned are allowed in unevaluated
4030 // expressions. Everything else falls under the
4031 // "may accept other forms of constant expressions" exception.
4032 // (We never end up here for C++, so the constant expression
4033 // rules there don't matter.)
John McCall4204f072010-08-02 21:13:48 +00004034 if (Init->isConstantInitializer(Context, false))
Eli Friedman578a9722009-02-22 06:45:27 +00004035 return false;
Eli Friedman21298282009-02-26 04:47:58 +00004036 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
4037 << Init->getSourceRange();
Eli Friedmanc594b322008-05-20 13:48:25 +00004038 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00004039}
4040
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00004041void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init) {
4042 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004043}
4044
4045/// AddInitializerToDecl - Adds the initializer Init to the
4046/// declaration dcl. If DirectInit is true, this is C++ direct
4047/// initialization rather than copy initialization.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004048void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init, bool DirectInit) {
4049 Decl *RealDecl = dcl.getAs<Decl>();
Chris Lattner9a11b9a2007-10-19 20:10:30 +00004050 // If there is no declaration, there was an error parsing it. Just ignore
4051 // the initializer.
Eli Friedman3b8a36a2009-02-27 04:17:12 +00004052 if (RealDecl == 0)
Chris Lattner9a11b9a2007-10-19 20:10:30 +00004053 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004054
Douglas Gregor021c3b32009-03-11 23:00:04 +00004055 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
4056 // With declarators parsed the way they are, the parser cannot
4057 // distinguish between a normal initializer and a pure-specifier.
4058 // Thus this grotesque test.
4059 IntegerLiteral *IL;
4060 Expr *Init = static_cast<Expr *>(init.get());
4061 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor4ba31362009-12-01 17:24:26 +00004062 Context.getCanonicalType(IL->getType()) == Context.IntTy)
4063 CheckPureMethod(Method, Init->getSourceRange());
4064 else {
Douglas Gregor021c3b32009-03-11 23:00:04 +00004065 Diag(Method->getLocation(), diag::err_member_function_initialization)
4066 << Method->getDeclName() << Init->getSourceRange();
4067 Method->setInvalidDecl();
4068 }
4069 return;
4070 }
4071
Steve Naroff410e3e22007-09-12 20:13:48 +00004072 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4073 if (!VDecl) {
Douglas Gregor021c3b32009-03-11 23:00:04 +00004074 if (getLangOptions().CPlusPlus &&
4075 RealDecl->getLexicalDeclContext()->isRecord() &&
4076 isa<NamedDecl>(RealDecl))
4077 Diag(RealDecl->getLocation(), diag::err_member_initialization)
4078 << cast<NamedDecl>(RealDecl)->getDeclName();
4079 else
4080 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00004081 RealDecl->setInvalidDecl();
4082 return;
Eli Friedman3b8a36a2009-02-27 04:17:12 +00004083 }
4084
Eli Friedman49e2b8e2009-11-14 03:40:14 +00004085 // A definition must end up with a complete type, which means it must be
4086 // complete with the restriction that an array type might be completed by the
4087 // initializer; note that later code assumes this restriction.
4088 QualType BaseDeclType = VDecl->getType();
4089 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
4090 BaseDeclType = Array->getElementType();
4091 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
Eli Friedmana31feca2009-04-13 21:28:54 +00004092 diag::err_typecheck_decl_incomplete_type)) {
4093 RealDecl->setInvalidDecl();
4094 return;
4095 }
4096
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004097 // The variable can not have an abstract class type.
4098 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4099 diag::err_abstract_type_in_decl,
4100 AbstractVariableType))
4101 VDecl->setInvalidDecl();
4102
Sebastian Redl31310a22010-02-01 20:16:42 +00004103 const VarDecl *Def;
4104 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004105 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor275a3692009-03-10 23:43:53 +00004106 << VDecl->getDeclName();
4107 Diag(Def->getLocation(), diag::note_previous_definition);
4108 VDecl->setInvalidDecl();
4109 return;
4110 }
4111
John McCalle46f62c2010-08-01 01:24:59 +00004112 if (getLangOptions().CPlusPlus && VDecl->hasLocalStorage())
4113 setFunctionHasBranchProtectedScope();
4114
Eli Friedman3b8a36a2009-02-27 04:17:12 +00004115 // Take ownership of the expression, now that we're sure we have somewhere
4116 // to put it.
Anders Carlssonf1b1d592009-05-01 19:30:39 +00004117 Expr *Init = init.takeAs<Expr>();
Eli Friedman3b8a36a2009-02-27 04:17:12 +00004118 assert(Init && "missing initializer");
4119
Douglas Gregor99a2e602009-12-16 01:38:02 +00004120 // Capture the variable that is being initialized and the style of
4121 // initialization.
4122 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4123
4124 // FIXME: Poor source location information.
4125 InitializationKind Kind
4126 = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(),
4127 Init->getLocStart(),
4128 Init->getLocEnd())
4129 : InitializationKind::CreateCopy(VDecl->getLocation(),
4130 Init->getLocStart());
4131
Steve Naroffbb204692007-09-12 14:07:44 +00004132 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00004133 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00004134 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00004135 if (VDecl->isBlockVarDecl()) {
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00004136 if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00004137 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00004138 VDecl->setInvalidDecl();
4139 } else if (!VDecl->isInvalidDecl()) {
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004140 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
Eli Friedmana91eb542009-12-22 02:10:53 +00004141 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004142 MultiExprArg(*this, (void**)&Init, 1),
Eli Friedmana91eb542009-12-22 02:10:53 +00004143 &DclT);
4144 if (Result.isInvalid()) {
Steve Naroff248a7532008-04-15 22:42:06 +00004145 VDecl->setInvalidDecl();
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004146 return;
4147 }
Mike Stump1eb44332009-09-09 15:08:12 +00004148
Eli Friedmana91eb542009-12-22 02:10:53 +00004149 Init = Result.takeAs<Expr>();
4150
Anders Carlssonc5eb7312008-08-22 05:00:02 +00004151 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmanda153232009-02-20 01:34:21 +00004152 // Don't check invalid declarations to avoid emitting useless diagnostics.
4153 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00004154 if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4.
Anders Carlssonc5eb7312008-08-22 05:00:02 +00004155 CheckForConstantInitializer(Init, DclT);
4156 }
Steve Naroffbb204692007-09-12 14:07:44 +00004157 }
Mike Stump1eb44332009-09-09 15:08:12 +00004158 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor021c3b32009-03-11 23:00:04 +00004159 VDecl->getLexicalDeclContext()->isRecord()) {
4160 // This is an in-class initialization for a static data member, e.g.,
4161 //
4162 // struct S {
4163 // static const int value = 17;
4164 // };
4165
4166 // Attach the initializer
Douglas Gregor838db382010-02-11 01:19:42 +00004167 VDecl->setInit(Init);
Douglas Gregor021c3b32009-03-11 23:00:04 +00004168
4169 // C++ [class.mem]p4:
4170 // A member-declarator can contain a constant-initializer only
4171 // if it declares a static member (9.4) of const integral or
4172 // const enumeration type, see 9.4.2.
4173 QualType T = VDecl->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004174 if (!T->isDependentType() &&
Douglas Gregor021c3b32009-03-11 23:00:04 +00004175 (!Context.getCanonicalType(T).isConstQualified() ||
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004176 !T->isIntegralOrEnumerationType())) {
Douglas Gregor021c3b32009-03-11 23:00:04 +00004177 Diag(VDecl->getLocation(), diag::err_member_initialization)
4178 << VDecl->getDeclName() << Init->getSourceRange();
4179 VDecl->setInvalidDecl();
4180 } else {
4181 // C++ [class.static.data]p4:
4182 // If a static data member is of const integral or const
4183 // enumeration type, its declaration in the class definition
4184 // can specify a constant-initializer which shall be an
4185 // integral constant expression (5.19).
4186 if (!Init->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004187 !Init->getType()->isIntegralOrEnumerationType()) {
Douglas Gregor021c3b32009-03-11 23:00:04 +00004188 // We have a non-dependent, non-integral or enumeration type.
Mike Stump1eb44332009-09-09 15:08:12 +00004189 Diag(Init->getSourceRange().getBegin(),
Douglas Gregor021c3b32009-03-11 23:00:04 +00004190 diag::err_in_class_initializer_non_integral_type)
4191 << Init->getType() << Init->getSourceRange();
4192 VDecl->setInvalidDecl();
4193 } else if (!Init->isTypeDependent() && !Init->isValueDependent()) {
4194 // Check whether the expression is a constant expression.
4195 llvm::APSInt Value;
4196 SourceLocation Loc;
4197 if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) {
4198 Diag(Loc, diag::err_in_class_initializer_non_constant)
4199 << Init->getSourceRange();
4200 VDecl->setInvalidDecl();
Douglas Gregor3d7a12a2009-03-25 23:32:15 +00004201 } else if (!VDecl->getType()->isDependentType())
Eli Friedman73c39ab2009-10-20 08:27:19 +00004202 ImpCastExprToType(Init, VDecl->getType(), CastExpr::CK_IntegralCast);
Douglas Gregor021c3b32009-03-11 23:00:04 +00004203 }
4204 }
Steve Naroff248a7532008-04-15 22:42:06 +00004205 } else if (VDecl->isFileVarDecl()) {
Douglas Gregor41b1d6b2010-04-19 21:31:25 +00004206 if (VDecl->getStorageClass() == VarDecl::Extern &&
Douglas Gregor66dd9392010-04-22 14:36:26 +00004207 (!getLangOptions().CPlusPlus ||
4208 !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
Steve Naroff410e3e22007-09-12 20:13:48 +00004209 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedmana91eb542009-12-22 02:10:53 +00004210 if (!VDecl->isInvalidDecl()) {
4211 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
4212 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
4213 MultiExprArg(*this, (void**)&Init, 1),
4214 &DclT);
4215 if (Result.isInvalid()) {
Steve Naroff248a7532008-04-15 22:42:06 +00004216 VDecl->setInvalidDecl();
Eli Friedmana91eb542009-12-22 02:10:53 +00004217 return;
4218 }
4219
4220 Init = Result.takeAs<Expr>();
4221 }
Mike Stump1eb44332009-09-09 15:08:12 +00004222
Anders Carlssonc5eb7312008-08-22 05:00:02 +00004223 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmanda153232009-02-20 01:34:21 +00004224 // Don't check invalid declarations to avoid emitting useless diagnostics.
4225 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
Anders Carlssonc5eb7312008-08-22 05:00:02 +00004226 // C99 6.7.8p4. All file scoped initializers need to be constant.
4227 CheckForConstantInitializer(Init, DclT);
4228 }
Steve Naroffbb204692007-09-12 14:07:44 +00004229 }
4230 // If the type changed, it means we had an incomplete type that was
Mike Stump1eb44332009-09-09 15:08:12 +00004231 // completed by the initializer. For example:
Steve Naroffbb204692007-09-12 14:07:44 +00004232 // int ary[] = { 1, 3, 5 };
4233 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00004234 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00004235 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00004236 Init->setType(DclT);
4237 }
Mike Stump1eb44332009-09-09 15:08:12 +00004238
Anders Carlsson0ece4912009-12-15 20:51:39 +00004239 Init = MaybeCreateCXXExprWithTemporaries(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00004240 // Attach the initializer to the decl.
Douglas Gregor838db382010-02-11 01:19:42 +00004241 VDecl->setInit(Init);
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00004242
Eli Friedmandd4e4852009-12-20 22:29:11 +00004243 if (getLangOptions().CPlusPlus) {
John McCall626e96e2010-08-01 20:20:59 +00004244 if (!VDecl->isInvalidDecl() &&
4245 !VDecl->getDeclContext()->isDependentContext() &&
John McCall4204f072010-08-02 21:13:48 +00004246 VDecl->hasGlobalStorage() &&
4247 !Init->isConstantInitializer(Context,
4248 VDecl->getType()->isReferenceType()))
4249 Diag(VDecl->getLocation(), diag::warn_global_constructor)
4250 << Init->getSourceRange();
John McCall626e96e2010-08-01 20:20:59 +00004251
Eli Friedmandd4e4852009-12-20 22:29:11 +00004252 // Make sure we mark the destructor as used if necessary.
4253 QualType InitType = VDecl->getType();
Douglas Gregorbd6d6192010-01-05 19:06:31 +00004254 while (const ArrayType *Array = Context.getAsArrayType(InitType))
Eli Friedmandd4e4852009-12-20 22:29:11 +00004255 InitType = Context.getBaseElementType(Array);
John McCall68c6c9a2010-02-02 09:10:11 +00004256 if (const RecordType *Record = InitType->getAs<RecordType>())
4257 FinalizeVarWithDestructor(VDecl, Record);
Eli Friedmandd4e4852009-12-20 22:29:11 +00004258 }
4259
Steve Naroffbb204692007-09-12 14:07:44 +00004260 return;
4261}
4262
John McCall7727acf2010-03-31 02:13:20 +00004263/// ActOnInitializerError - Given that there was an error parsing an
4264/// initializer for the given declaration, try to return to some form
4265/// of sanity.
4266void Sema::ActOnInitializerError(DeclPtrTy dcl) {
4267 // Our main concern here is re-establishing invariants like "a
4268 // variable's type is either dependent or complete".
4269 Decl *D = dcl.getAs<Decl>();
4270 if (!D || D->isInvalidDecl()) return;
4271
4272 VarDecl *VD = dyn_cast<VarDecl>(D);
4273 if (!VD) return;
4274
4275 QualType Ty = VD->getType();
4276 if (Ty->isDependentType()) return;
4277
4278 // Require a complete type.
4279 if (RequireCompleteType(VD->getLocation(),
4280 Context.getBaseElementType(Ty),
4281 diag::err_typecheck_decl_incomplete_type)) {
4282 VD->setInvalidDecl();
4283 return;
4284 }
4285
4286 // Require an abstract type.
4287 if (RequireNonAbstractType(VD->getLocation(), Ty,
4288 diag::err_abstract_type_in_decl,
4289 AbstractVariableType)) {
4290 VD->setInvalidDecl();
4291 return;
4292 }
4293
4294 // Don't bother complaining about constructors or destructors,
4295 // though.
4296}
4297
Mike Stump1eb44332009-09-09 15:08:12 +00004298void Sema::ActOnUninitializedDecl(DeclPtrTy dcl,
Anders Carlsson6a75cd92009-07-11 00:34:39 +00004299 bool TypeContainsUndeducedAuto) {
Chris Lattnerb28317a2009-03-28 19:18:32 +00004300 Decl *RealDecl = dcl.getAs<Decl>();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004301
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00004302 // If there is no declaration, there was an error parsing it. Just ignore it.
4303 if (RealDecl == 0)
4304 return;
4305
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004306 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
4307 QualType Type = Var->getType();
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00004308
Anders Carlsson6a75cd92009-07-11 00:34:39 +00004309 // C++0x [dcl.spec.auto]p3
4310 if (TypeContainsUndeducedAuto) {
4311 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
4312 << Var->getDeclName() << Type;
4313 Var->setInvalidDecl();
4314 return;
4315 }
Mike Stump1eb44332009-09-09 15:08:12 +00004316
Douglas Gregor60c93c92010-02-09 07:26:29 +00004317 switch (Var->isThisDeclarationADefinition()) {
4318 case VarDecl::Definition:
4319 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
4320 break;
4321
4322 // We have an out-of-line definition of a static data member
4323 // that has an in-class initializer, so we type-check this like
4324 // a declaration.
4325 //
4326 // Fall through
4327
4328 case VarDecl::DeclarationOnly:
4329 // It's only a declaration.
4330
4331 // Block scope. C99 6.7p7: If an identifier for an object is
4332 // declared with no linkage (C99 6.2.2p6), the type for the
4333 // object shall be complete.
4334 if (!Type->isDependentType() && Var->isBlockVarDecl() &&
4335 !Var->getLinkage() && !Var->isInvalidDecl() &&
4336 RequireCompleteType(Var->getLocation(), Type,
4337 diag::err_typecheck_decl_incomplete_type))
4338 Var->setInvalidDecl();
4339
4340 // Make sure that the type is not abstract.
4341 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
4342 RequireNonAbstractType(Var->getLocation(), Type,
4343 diag::err_abstract_type_in_decl,
4344 AbstractVariableType))
4345 Var->setInvalidDecl();
4346 return;
4347
4348 case VarDecl::TentativeDefinition:
4349 // File scope. C99 6.9.2p2: A declaration of an identifier for an
4350 // object that has file scope without an initializer, and without a
4351 // storage-class specifier or with the storage-class specifier "static",
4352 // constitutes a tentative definition. Note: A tentative definition with
4353 // external linkage is valid (C99 6.2.2p5).
4354 if (!Var->isInvalidDecl()) {
4355 if (const IncompleteArrayType *ArrayT
4356 = Context.getAsIncompleteArrayType(Type)) {
4357 if (RequireCompleteType(Var->getLocation(),
4358 ArrayT->getElementType(),
4359 diag::err_illegal_decl_array_incomplete_type))
4360 Var->setInvalidDecl();
4361 } else if (Var->getStorageClass() == VarDecl::Static) {
4362 // C99 6.9.2p3: If the declaration of an identifier for an object is
4363 // a tentative definition and has internal linkage (C99 6.2.2p3), the
4364 // declared type shall not be an incomplete type.
4365 // NOTE: code such as the following
4366 // static struct s;
4367 // struct s { int a; };
4368 // is accepted by gcc. Hence here we issue a warning instead of
4369 // an error and we do not invalidate the static declaration.
4370 // NOTE: to avoid multiple warnings, only check the first declaration.
4371 if (Var->getPreviousDeclaration() == 0)
4372 RequireCompleteType(Var->getLocation(), Type,
4373 diag::ext_typecheck_decl_incomplete_type);
4374 }
4375 }
4376
4377 // Record the tentative definition; we're done.
4378 if (!Var->isInvalidDecl())
4379 TentativeDefinitions.push_back(Var);
4380 return;
4381 }
4382
4383 // Provide a specific diagnostic for uninitialized variable
4384 // definitions with incomplete array type.
4385 if (Type->isIncompleteArrayType()) {
Sebastian Redl6e824752009-11-05 19:47:47 +00004386 Diag(Var->getLocation(),
4387 diag::err_typecheck_incomplete_array_needs_initializer);
4388 Var->setInvalidDecl();
4389 return;
4390 }
4391
John McCallb567a8b2010-08-01 01:25:24 +00004392 // Provide a specific diagnostic for uninitialized variable
4393 // definitions with reference type.
4394 if (Type->isReferenceType()) {
4395 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
4396 << Var->getDeclName()
4397 << SourceRange(Var->getLocation(), Var->getLocation());
4398 Var->setInvalidDecl();
4399 return;
4400 }
Douglas Gregor60c93c92010-02-09 07:26:29 +00004401
4402 // Do not attempt to type-check the default initializer for a
4403 // variable with dependent type.
4404 if (Type->isDependentType())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004405 return;
Douglas Gregor39da0b82009-09-09 23:08:42 +00004406
Douglas Gregor60c93c92010-02-09 07:26:29 +00004407 if (Var->isInvalidDecl())
4408 return;
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004409
Douglas Gregor60c93c92010-02-09 07:26:29 +00004410 if (RequireCompleteType(Var->getLocation(),
4411 Context.getBaseElementType(Type),
4412 diag::err_typecheck_decl_incomplete_type)) {
4413 Var->setInvalidDecl();
4414 return;
Douglas Gregor18fe5682008-11-03 20:45:27 +00004415 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004416
Douglas Gregor60c93c92010-02-09 07:26:29 +00004417 // The variable can not have an abstract class type.
4418 if (RequireNonAbstractType(Var->getLocation(), Type,
4419 diag::err_abstract_type_in_decl,
4420 AbstractVariableType)) {
4421 Var->setInvalidDecl();
4422 return;
4423 }
4424
Douglas Gregor516a6bc2010-03-08 02:45:10 +00004425 const RecordType *Record
4426 = Context.getBaseElementType(Type)->getAs<RecordType>();
4427 if (Record && getLangOptions().CPlusPlus && !getLangOptions().CPlusPlus0x &&
4428 cast<CXXRecordDecl>(Record->getDecl())->isPOD()) {
4429 // C++03 [dcl.init]p9:
4430 // If no initializer is specified for an object, and the
4431 // object is of (possibly cv-qualified) non-POD class type (or
4432 // array thereof), the object shall be default-initialized; if
4433 // the object is of const-qualified type, the underlying class
4434 // type shall have a user-declared default
4435 // constructor. Otherwise, if no initializer is specified for
4436 // a non- static object, the object and its subobjects, if
4437 // any, have an indeterminate initial value); if the object
4438 // or any of its subobjects are of const-qualified type, the
4439 // program is ill-formed.
4440 // FIXME: DPG thinks it is very fishy that C++0x disables this.
4441 } else {
John McCalle46f62c2010-08-01 01:24:59 +00004442 // Check for jumps past the implicit initializer. C++0x
4443 // clarifies that this applies to a "variable with automatic
4444 // storage duration", not a "local variable".
4445 if (getLangOptions().CPlusPlus && Var->hasLocalStorage())
4446 setFunctionHasBranchProtectedScope();
4447
Douglas Gregor516a6bc2010-03-08 02:45:10 +00004448 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
4449 InitializationKind Kind
4450 = InitializationKind::CreateDefault(Var->getLocation());
Douglas Gregor60c93c92010-02-09 07:26:29 +00004451
Douglas Gregor516a6bc2010-03-08 02:45:10 +00004452 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
4453 OwningExprResult Init = InitSeq.Perform(*this, Entity, Kind,
4454 MultiExprArg(*this, 0, 0));
4455 if (Init.isInvalid())
4456 Var->setInvalidDecl();
John McCall626e96e2010-08-01 20:20:59 +00004457 else if (Init.get()) {
Douglas Gregor838db382010-02-11 01:19:42 +00004458 Var->setInit(MaybeCreateCXXExprWithTemporaries(Init.takeAs<Expr>()));
John McCall626e96e2010-08-01 20:20:59 +00004459
4460 if (getLangOptions().CPlusPlus && !Var->isInvalidDecl() &&
4461 Var->hasGlobalStorage() &&
4462 !Var->getDeclContext()->isDependentContext() &&
John McCall4204f072010-08-02 21:13:48 +00004463 !Var->getInit()->isConstantInitializer(Context, false))
John McCall626e96e2010-08-01 20:20:59 +00004464 Diag(Var->getLocation(), diag::warn_global_constructor);
4465 }
Douglas Gregor60c93c92010-02-09 07:26:29 +00004466 }
Douglas Gregor516a6bc2010-03-08 02:45:10 +00004467
4468 if (!Var->isInvalidDecl() && getLangOptions().CPlusPlus && Record)
4469 FinalizeVarWithDestructor(Var, Record);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004470 }
4471}
4472
Eli Friedmanc1dc6532009-05-29 01:49:24 +00004473Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
4474 DeclPtrTy *Group,
Chris Lattner682bf922009-03-29 16:50:03 +00004475 unsigned NumDecls) {
4476 llvm::SmallVector<Decl*, 8> Decls;
Eli Friedmanc1dc6532009-05-29 01:49:24 +00004477
4478 if (DS.isTypeSpecOwned())
4479 Decls.push_back((Decl*)DS.getTypeRep());
4480
Chris Lattner682bf922009-03-29 16:50:03 +00004481 for (unsigned i = 0; i != NumDecls; ++i)
4482 if (Decl *D = Group[i].getAs<Decl>())
4483 Decls.push_back(D);
Mike Stump1eb44332009-09-09 15:08:12 +00004484
Chris Lattner682bf922009-03-29 16:50:03 +00004485 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context,
Jay Foadbeaaccd2009-05-21 09:52:38 +00004486 Decls.data(), Decls.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +00004487}
Steve Naroffe1223f72007-08-28 03:03:08 +00004488
Chris Lattner682bf922009-03-29 16:50:03 +00004489
Chris Lattner04421082008-04-08 04:40:51 +00004490/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
4491/// to introduce parameters into function prototype scope.
Mike Stump1eb44332009-09-09 15:08:12 +00004492Sema::DeclPtrTy
Chris Lattner04421082008-04-08 04:40:51 +00004493Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00004494 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00004495
Chris Lattner04421082008-04-08 04:40:51 +00004496 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00004497 VarDecl::StorageClass StorageClass = VarDecl::None;
Douglas Gregor16573fa2010-04-19 22:54:31 +00004498 VarDecl::StorageClass StorageClassAsWritten = VarDecl::None;
Daniel Dunbar33ad0122008-09-03 21:54:21 +00004499 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
4500 StorageClass = VarDecl::Register;
Douglas Gregor16573fa2010-04-19 22:54:31 +00004501 StorageClassAsWritten = VarDecl::Register;
Daniel Dunbar33ad0122008-09-03 21:54:21 +00004502 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00004503 Diag(DS.getStorageClassSpecLoc(),
4504 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00004505 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00004506 }
Eli Friedman63054b32009-04-19 20:27:55 +00004507
4508 if (D.getDeclSpec().isThreadSpecified())
4509 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4510
Eli Friedman85a53192009-04-07 19:37:57 +00004511 DiagnoseFunctionSpecifiers(D);
4512
Douglas Gregor6d6eb572008-05-07 04:49:29 +00004513 // Check that there are no default arguments inside the type of this
4514 // parameter (C++ only).
4515 if (getLangOptions().CPlusPlus)
4516 CheckExtraCXXDefaultArguments(D);
Mike Stump1eb44332009-09-09 15:08:12 +00004517
Douglas Gregor402abb52009-05-28 23:31:59 +00004518 TagDecl *OwnedDecl = 0;
John McCallbf1a0282010-06-04 23:28:52 +00004519 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedDecl);
4520 QualType parmDeclType = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004521
Douglas Gregor402abb52009-05-28 23:31:59 +00004522 if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) {
4523 // C++ [dcl.fct]p6:
4524 // Types shall not be defined in return or parameter types.
4525 Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
4526 << Context.getTypeDeclType(OwnedDecl);
4527 }
4528
Chris Lattnerd84aac12010-02-22 00:40:25 +00004529 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattner04421082008-04-08 04:40:51 +00004530 IdentifierInfo *II = D.getIdentifier();
Chris Lattnercf79b012009-01-21 02:38:50 +00004531 if (II) {
John McCall10f28732010-03-18 06:42:38 +00004532 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
4533 ForRedeclaration);
4534 LookupName(R, S);
4535 if (R.isSingleResult()) {
4536 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnercf79b012009-01-21 02:38:50 +00004537 if (PrevDecl->isTemplateParameter()) {
4538 // Maybe we will complain about the shadowed template parameter.
4539 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
4540 // Just pretend that we didn't see the previous declaration.
4541 PrevDecl = 0;
Chris Lattnerb28317a2009-03-28 19:18:32 +00004542 } else if (S->isDeclScope(DeclPtrTy::make(PrevDecl))) {
Chris Lattnercf79b012009-01-21 02:38:50 +00004543 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerd84aac12010-02-22 00:40:25 +00004544 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattner04421082008-04-08 04:40:51 +00004545
Chris Lattnercf79b012009-01-21 02:38:50 +00004546 // Recover by removing the name
4547 II = 0;
4548 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00004549 D.setInvalidType(true);
Chris Lattnercf79b012009-01-21 02:38:50 +00004550 }
Chris Lattner04421082008-04-08 04:40:51 +00004551 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004552 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00004553
John McCall7a9813c2010-01-22 00:28:27 +00004554 // Temporarily put parameter variables in the translation unit, not
4555 // the enclosing context. This prevents them from accidentally
4556 // looking like class members in C++.
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00004557 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
4558 TInfo, parmDeclType, II,
Douglas Gregor16573fa2010-04-19 22:54:31 +00004559 D.getIdentifierLoc(),
4560 StorageClass, StorageClassAsWritten);
Mike Stump1eb44332009-09-09 15:08:12 +00004561
Chris Lattnereaaebc72009-04-25 08:06:05 +00004562 if (D.isInvalidType())
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00004563 New->setInvalidDecl();
4564
Chris Lattnerf97e8fa2009-04-11 19:34:56 +00004565 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
4566 if (D.getCXXScopeSpec().isSet()) {
4567 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
4568 << D.getCXXScopeSpec().getRange();
4569 New->setInvalidDecl();
4570 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00004571
Douglas Gregor44b43212008-12-11 16:49:14 +00004572 // Add the parameter declaration into this scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00004573 S->AddDecl(DeclPtrTy::make(New));
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00004574 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00004575 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00004576
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00004577 ProcessDeclAttributes(S, New, D);
Mike Stumpea000bf2009-04-30 00:19:40 +00004578
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004579 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpea000bf2009-04-30 00:19:40 +00004580 Diag(New->getLocation(), diag::err_block_on_nonlocal);
4581 }
Chris Lattnerb28317a2009-03-28 19:18:32 +00004582 return DeclPtrTy::make(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00004583}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00004584
John McCall82dc0092010-06-04 11:21:44 +00004585/// \brief Synthesizes a variable for a parameter arising from a
4586/// typedef.
4587ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
4588 SourceLocation Loc,
4589 QualType T) {
4590 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, 0,
4591 T, Context.getTrivialTypeSourceInfo(T, Loc),
4592 VarDecl::None, VarDecl::None, 0);
4593 Param->setImplicit();
4594 return Param;
4595}
4596
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00004597ParmVarDecl *Sema::CheckParameter(DeclContext *DC,
4598 TypeSourceInfo *TSInfo, QualType T,
4599 IdentifierInfo *Name,
4600 SourceLocation NameLoc,
Douglas Gregor16573fa2010-04-19 22:54:31 +00004601 VarDecl::StorageClass StorageClass,
4602 VarDecl::StorageClass StorageClassAsWritten) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00004603 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, NameLoc, Name,
4604 adjustParameterType(T), TSInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00004605 StorageClass, StorageClassAsWritten,
4606 0);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00004607
4608 // Parameters can not be abstract class types.
4609 // For record types, this is done by the AbstractClassUsageDiagnoser once
4610 // the class has been completely parsed.
4611 if (!CurContext->isRecord() &&
4612 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
4613 AbstractParamType))
4614 New->setInvalidDecl();
4615
4616 // Parameter declarators cannot be interface types. All ObjC objects are
4617 // passed by reference.
John McCallc12c5bb2010-05-15 11:32:37 +00004618 if (T->isObjCObjectType()) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00004619 Diag(NameLoc,
4620 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
4621 New->setInvalidDecl();
4622 }
4623
4624 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
4625 // duration shall not be qualified by an address-space qualifier."
4626 // Since all parameters have automatic store duration, they can not have
4627 // an address space.
4628 if (T.getAddressSpace() != 0) {
4629 Diag(NameLoc, diag::err_arg_with_address_space);
4630 New->setInvalidDecl();
4631 }
4632
4633 return New;
4634}
4635
Douglas Gregora3a83512009-04-01 23:51:29 +00004636void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
4637 SourceLocation LocAfterDecls) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004638 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4639 "Not a function declarator!");
4640 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00004641
Reid Spencer5f016e22007-07-11 17:01:13 +00004642 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
4643 // for a K&R function.
4644 if (!FTI.hasPrototype) {
Douglas Gregor26103482009-04-02 03:14:12 +00004645 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
4646 --i;
Chris Lattner04421082008-04-08 04:40:51 +00004647 if (FTI.ArgInfo[i].Param == 0) {
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00004648 llvm::SmallString<256> Code;
4649 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004650 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +00004651 << ";\n";
Chris Lattner3c73c412008-11-19 08:23:25 +00004652 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregora3a83512009-04-01 23:51:29 +00004653 << FTI.ArgInfo[i].Ident
Douglas Gregor849b2432010-03-31 17:46:05 +00004654 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregora3a83512009-04-01 23:51:29 +00004655
Reid Spencer5f016e22007-07-11 17:01:13 +00004656 // Implicitly declare the argument as type 'int' for lack of a better
4657 // type.
Chris Lattner04421082008-04-08 04:40:51 +00004658 DeclSpec DS;
4659 const char* PrevSpec; // unused
John McCallfec54012009-08-03 20:12:06 +00004660 unsigned DiagID; // unused
Mike Stump1eb44332009-09-09 15:08:12 +00004661 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCallfec54012009-08-03 20:12:06 +00004662 PrevSpec, DiagID);
Chris Lattner04421082008-04-08 04:40:51 +00004663 Declarator ParamD(DS, Declarator::KNRTypeListContext);
4664 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregorbe109b32009-01-23 16:23:13 +00004665 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00004666 }
4667 }
Mike Stump1eb44332009-09-09 15:08:12 +00004668 }
Douglas Gregorbe109b32009-01-23 16:23:13 +00004669}
4670
Chris Lattnerb28317a2009-03-28 19:18:32 +00004671Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
4672 Declarator &D) {
Douglas Gregorbe109b32009-01-23 16:23:13 +00004673 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4674 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4675 "Not a function declarator!");
4676 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
4677
4678 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00004679 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00004680 }
Mike Stump1eb44332009-09-09 15:08:12 +00004681
Douglas Gregor584049d2008-12-15 23:53:10 +00004682 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00004683
Mike Stump1eb44332009-09-09 15:08:12 +00004684 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregore542c862009-06-23 23:11:28 +00004685 MultiTemplateParamsArg(*this),
4686 /*IsFunctionDefinition=*/true);
Chris Lattner682bf922009-03-29 16:50:03 +00004687 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004688}
4689
Anders Carlsson9f89dd72009-12-09 03:30:09 +00004690static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
4691 // Don't warn about invalid declarations.
4692 if (FD->isInvalidDecl())
4693 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00004694
Anders Carlsson9f89dd72009-12-09 03:30:09 +00004695 // Or declarations that aren't global.
4696 if (!FD->isGlobal())
4697 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00004698
Anders Carlsson9f89dd72009-12-09 03:30:09 +00004699 // Don't warn about C++ member functions.
4700 if (isa<CXXMethodDecl>(FD))
4701 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00004702
Anders Carlsson9f89dd72009-12-09 03:30:09 +00004703 // Don't warn about 'main'.
4704 if (FD->isMain())
4705 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00004706
Anders Carlsson9f89dd72009-12-09 03:30:09 +00004707 // Don't warn about inline functions.
4708 if (FD->isInlineSpecified())
4709 return false;
Anders Carlsson63fb6732009-12-09 03:44:46 +00004710
4711 // Don't warn about function templates.
4712 if (FD->getDescribedFunctionTemplate())
4713 return false;
4714
4715 // Don't warn about function template specializations.
4716 if (FD->isFunctionTemplateSpecialization())
4717 return false;
4718
Anders Carlsson9f89dd72009-12-09 03:30:09 +00004719 bool MissingPrototype = true;
4720 for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
4721 Prev; Prev = Prev->getPreviousDeclaration()) {
4722 // Ignore any declarations that occur in function or method
4723 // scope, because they aren't visible from the header.
4724 if (Prev->getDeclContext()->isFunctionOrMethod())
4725 continue;
4726
4727 MissingPrototype = !Prev->getType()->isFunctionProtoType();
4728 break;
4729 }
4730
4731 return MissingPrototype;
4732}
4733
Chris Lattnerb28317a2009-03-28 19:18:32 +00004734Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) {
Anders Carlsson0ebb6d32009-10-29 15:46:07 +00004735 // Clear the last template instantiation error context.
4736 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
4737
Douglas Gregor52591bf2009-06-24 00:54:41 +00004738 if (!D)
4739 return D;
Douglas Gregord83d0402009-08-22 00:34:47 +00004740 FunctionDecl *FD = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004741
4742 if (FunctionTemplateDecl *FunTmpl
Douglas Gregord83d0402009-08-22 00:34:47 +00004743 = dyn_cast<FunctionTemplateDecl>(D.getAs<Decl>()))
4744 FD = FunTmpl->getTemplatedDecl();
4745 else
4746 FD = cast<FunctionDecl>(D.getAs<Decl>());
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00004747
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00004748 // Enter a new function scope
4749 PushFunctionScope();
Mike Stump1eb44332009-09-09 15:08:12 +00004750
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00004751 // See if this is a redefinition.
Charles Davisf3f8d2a2010-02-18 02:00:42 +00004752 // But don't complain if we're in GNU89 mode and the previous definition
4753 // was an extern inline function.
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00004754 const FunctionDecl *Definition;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00004755 if (FD->hasBody(Definition) &&
Charles Davisf3f8d2a2010-02-18 02:00:42 +00004756 !canRedefineFunction(Definition, getLangOptions())) {
Chris Lattner08631c52008-11-23 21:45:46 +00004757 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00004758 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00004759 }
4760
Douglas Gregorcda9c672009-02-16 17:45:42 +00004761 // Builtin functions cannot be defined.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00004762 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor655753a2009-02-17 16:03:01 +00004763 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00004764 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor655753a2009-02-17 16:03:01 +00004765 FD->setInvalidDecl();
4766 }
Douglas Gregorcda9c672009-02-16 17:45:42 +00004767 }
4768
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00004769 // The return type of a function definition must be complete
Douglas Gregore7450f52009-03-24 19:52:54 +00004770 // (C99 6.9.1p3, C++ [dcl.fct]p6).
4771 QualType ResultType = FD->getResultType();
4772 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner65e6a092009-04-29 05:12:23 +00004773 !FD->isInvalidDecl() &&
Douglas Gregore7450f52009-03-24 19:52:54 +00004774 RequireCompleteType(FD->getLocation(), ResultType,
4775 diag::err_func_def_incomplete_result))
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00004776 FD->setInvalidDecl();
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00004777
Douglas Gregor8499f3f2009-03-31 16:35:03 +00004778 // GNU warning -Wmissing-prototypes:
4779 // Warn if a global function is defined without a previous
4780 // prototype declaration. This warning is issued even if the
4781 // definition itself provides a prototype. The aim is to detect
4782 // global functions that fail to be declared in header files.
Anders Carlsson9f89dd72009-12-09 03:30:09 +00004783 if (ShouldWarnAboutMissingPrototype(FD))
4784 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Douglas Gregor8499f3f2009-03-31 16:35:03 +00004785
Douglas Gregore2c31ff2009-05-15 17:59:04 +00004786 if (FnBodyScope)
4787 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00004788
Chris Lattner04421082008-04-08 04:40:51 +00004789 // Check the validity of our function parameters
4790 CheckParmsForFunctionDef(FD);
4791
John McCall053f4bd2010-03-22 09:20:08 +00004792 bool ShouldCheckShadow =
4793 Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored;
4794
Chris Lattner04421082008-04-08 04:40:51 +00004795 // Introduce our parameters into the function scope
4796 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
4797 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00004798 Param->setOwningFunction(FD);
4799
Chris Lattner04421082008-04-08 04:40:51 +00004800 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00004801 if (Param->getIdentifier() && FnBodyScope) {
4802 if (ShouldCheckShadow)
4803 CheckShadow(FnBodyScope, Param);
4804
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00004805 PushOnScopeChains(Param, FnBodyScope);
John McCall053f4bd2010-03-22 09:20:08 +00004806 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004807 }
Chris Lattner04421082008-04-08 04:40:51 +00004808
Anton Korobeynikov2f402702008-12-26 00:52:02 +00004809 // Checking attributes of current function definition
4810 // dllimport attribute.
Sean Huntcf807c42010-08-18 23:23:40 +00004811 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
4812 if (DA && (!FD->getAttr<DLLExportAttr>())) {
4813 // dllimport attribute cannot be directly applied to definition.
4814 if (!DA->isInherited()) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00004815 Diag(FD->getLocation(),
4816 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
4817 << "dllimport";
4818 FD->setInvalidDecl();
Chris Lattnerb28317a2009-03-28 19:18:32 +00004819 return DeclPtrTy::make(FD);
Ted Kremenek12911a82010-02-21 05:12:53 +00004820 }
4821
4822 // Visual C++ appears to not think this is an issue, so only issue
4823 // a warning when Microsoft extensions are disabled.
4824 if (!LangOpts.Microsoft) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +00004825 // If a symbol previously declared dllimport is later defined, the
4826 // attribute is ignored in subsequent references, and a warning is
4827 // emitted.
4828 Diag(FD->getLocation(),
4829 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Daniel Dunbar4087f272010-08-17 22:39:59 +00004830 << FD->getName() << "dllimport";
Anton Korobeynikov2f402702008-12-26 00:52:02 +00004831 }
4832 }
Chris Lattnerb28317a2009-03-28 19:18:32 +00004833 return DeclPtrTy::make(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00004834}
4835
Douglas Gregor5077c382010-05-15 06:01:05 +00004836/// \brief Given the set of return statements within a function body,
4837/// compute the variables that are subject to the named return value
4838/// optimization.
4839///
4840/// Each of the variables that is subject to the named return value
4841/// optimization will be marked as NRVO variables in the AST, and any
4842/// return statement that has a marked NRVO variable as its NRVO candidate can
4843/// use the named return value optimization.
4844///
4845/// This function applies a very simplistic algorithm for NRVO: if every return
4846/// statement in the function has the same NRVO candidate, that candidate is
4847/// the NRVO variable.
4848///
4849/// FIXME: Employ a smarter algorithm that accounts for multiple return
4850/// statements and the lifetimes of the NRVO candidates. We should be able to
4851/// find a maximal set of NRVO variables.
4852static void ComputeNRVO(Stmt *Body, ReturnStmt **Returns, unsigned NumReturns) {
4853 const VarDecl *NRVOCandidate = 0;
4854 for (unsigned I = 0; I != NumReturns; ++I) {
4855 if (!Returns[I]->getNRVOCandidate())
4856 return;
4857
4858 if (!NRVOCandidate)
4859 NRVOCandidate = Returns[I]->getNRVOCandidate();
4860 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
4861 return;
4862 }
4863
4864 if (NRVOCandidate)
4865 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
4866}
4867
Chris Lattnerb28317a2009-03-28 19:18:32 +00004868Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) {
Douglas Gregore2c31ff2009-05-15 17:59:04 +00004869 return ActOnFinishFunctionBody(D, move(BodyArg), false);
4870}
4871
4872Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg,
4873 bool IsInstantiation) {
Chris Lattnerb28317a2009-03-28 19:18:32 +00004874 Decl *dcl = D.getAs<Decl>();
Sebastian Redld3a413d2009-04-26 20:35:05 +00004875 Stmt *Body = BodyArg.takeAs<Stmt>();
Douglas Gregord83d0402009-08-22 00:34:47 +00004876
4877 FunctionDecl *FD = 0;
4878 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
4879 if (FunTmpl)
4880 FD = FunTmpl->getTemplatedDecl();
4881 else
4882 FD = dyn_cast_or_null<FunctionDecl>(dcl);
4883
Ted Kremenekd064fdc2010-03-23 00:13:23 +00004884 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00004885
Douglas Gregord83d0402009-08-22 00:34:47 +00004886 if (FD) {
Chris Lattnera5251fc2009-04-18 09:36:27 +00004887 FD->setBody(Body);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00004888 if (FD->isMain()) {
Mike Stump5f28a1e2009-07-24 02:49:01 +00004889 // C and C++ allow for main to automagically return 0.
John McCall0cfeb632009-07-28 01:00:58 +00004890 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
4891 FD->setHasImplicitReturnZero(true);
Ted Kremenekd064fdc2010-03-23 00:13:23 +00004892 WP.disableCheckFallThrough();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00004893 }
Mike Stump1eb44332009-09-09 15:08:12 +00004894
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004895 if (!FD->isInvalidDecl()) {
Douglas Gregore0762c92009-06-19 23:52:42 +00004896 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004897
4898 // If this is a constructor, we need a vtable.
4899 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
4900 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor5077c382010-05-15 06:01:05 +00004901
4902 ComputeNRVO(Body, FunctionScopes.back()->Returns.data(),
4903 FunctionScopes.back()->Returns.size());
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004904 }
4905
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00004906 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00004907 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattnerffed1632009-02-16 19:27:54 +00004908 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattnera5251fc2009-04-18 09:36:27 +00004909 MD->setBody(Body);
Argyrios Kyrtzidisa2e85ad2009-07-18 00:33:33 +00004910 MD->setEndLoc(Body->getLocEnd());
Douglas Gregore0762c92009-06-19 23:52:42 +00004911 if (!MD->isInvalidDecl())
4912 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004913 } else {
Chris Lattnerb28317a2009-03-28 19:18:32 +00004914 return DeclPtrTy();
Ted Kremenek8189cde2009-02-07 01:47:29 +00004915 }
Douglas Gregore2c31ff2009-05-15 17:59:04 +00004916
Reid Spencer5f016e22007-07-11 17:01:13 +00004917 // Verify and clean out per-function state.
Eli Friedman8f17b662009-02-28 05:41:13 +00004918
Reid Spencer5f016e22007-07-11 17:01:13 +00004919 // Check goto/label use.
Steve Naroffcaaacec2009-03-13 15:38:40 +00004920 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00004921 I = getLabelMap().begin(), E = getLabelMap().end(); I != E; ++I) {
Chris Lattnere32f74c2009-04-18 19:30:02 +00004922 LabelStmt *L = I->second;
Mike Stump1eb44332009-09-09 15:08:12 +00004923
Reid Spencer5f016e22007-07-11 17:01:13 +00004924 // Verify that we have no forward references left. If so, there was a goto
4925 // or address of a label taken, but no definition of it. Label fwd
4926 // definitions are indicated with a null substmt.
Chris Lattnere32f74c2009-04-18 19:30:02 +00004927 if (L->getSubStmt() != 0)
4928 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00004929
Chris Lattnere32f74c2009-04-18 19:30:02 +00004930 // Emit error.
4931 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00004932
Chris Lattnere32f74c2009-04-18 19:30:02 +00004933 // At this point, we have gotos that use the bogus label. Stitch it into
4934 // the function body so that they aren't leaked and that the AST is well
4935 // formed.
4936 if (Body == 0) {
Douglas Gregorff331c12010-07-25 18:17:45 +00004937 // The whole function wasn't parsed correctly.
Chris Lattnere32f74c2009-04-18 19:30:02 +00004938 continue;
Reid Spencer5f016e22007-07-11 17:01:13 +00004939 }
Mike Stump1eb44332009-09-09 15:08:12 +00004940
Chris Lattnere32f74c2009-04-18 19:30:02 +00004941 // Otherwise, the body is valid: we want to stitch the label decl into the
4942 // function somewhere so that it is properly owned and so that the goto
4943 // has a valid target. Do this by creating a new compound stmt with the
4944 // label in it.
Sebastian Redld3a413d2009-04-26 20:35:05 +00004945
Chris Lattnere32f74c2009-04-18 19:30:02 +00004946 // Give the label a sub-statement.
4947 L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
Sebastian Redld3a413d2009-04-26 20:35:05 +00004948
4949 CompoundStmt *Compound = isa<CXXTryStmt>(Body) ?
4950 cast<CXXTryStmt>(Body)->getTryBlock() :
4951 cast<CompoundStmt>(Body);
Ted Kremenek4c9f7092010-03-12 22:22:36 +00004952 llvm::SmallVector<Stmt*, 64> Elements(Compound->body_begin(),
4953 Compound->body_end());
Chris Lattnere32f74c2009-04-18 19:30:02 +00004954 Elements.push_back(L);
Ted Kremenek4c9f7092010-03-12 22:22:36 +00004955 Compound->setStmts(Context, Elements.data(), Elements.size());
Reid Spencer5f016e22007-07-11 17:01:13 +00004956 }
Eli Friedman8f17b662009-02-28 05:41:13 +00004957
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00004958 if (Body) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00004959 // C++ constructors that have function-try-blocks can't have return
4960 // statements in the handlers of that block. (C++ [except.handle]p14)
4961 // Verify this.
4962 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
4963 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
4964
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00004965 // Verify that that gotos and switch cases don't jump into scopes illegally.
4966 // Verify that that gotos and switch cases don't jump into scopes illegally.
John McCalldae69ef2010-05-20 07:05:55 +00004967 if (FunctionNeedsScopeChecking() &&
John McCall8a2ca742010-05-20 07:13:26 +00004968 !dcl->isInvalidDecl() &&
John McCalldae69ef2010-05-20 07:05:55 +00004969 !hasAnyErrorsInThisFunction())
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00004970 DiagnoseInvalidJumps(Body);
Mike Stump1eb44332009-09-09 15:08:12 +00004971
John McCall15442822010-08-04 01:04:25 +00004972 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
4973 if (!Destructor->getParent()->isDependentType())
4974 CheckDestructor(Destructor);
4975
John McCallef027fe2010-03-16 21:39:52 +00004976 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4977 Destructor->getParent());
John McCall15442822010-08-04 01:04:25 +00004978 }
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00004979
4980 // If any errors have occurred, clear out any temporaries that may have
4981 // been leftover. This ensures that these temporaries won't be picked up for
4982 // deletion in some later function.
4983 if (PP.getDiagnostics().hasErrorOccurred())
4984 ExprTemporaries.clear();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00004985 else if (!isa<FunctionTemplateDecl>(dcl)) {
4986 // Since the body is valid, issue any analysis-based warnings that are
4987 // enabled.
4988 QualType ResultType;
4989 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
4990 ResultType = FD->getResultType();
4991 }
4992 else {
4993 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(dcl);
4994 ResultType = MD->getResultType();
4995 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +00004996 AnalysisWarnings.IssueWarnings(WP, dcl);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00004997 }
4998
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00004999 assert(ExprTemporaries.empty() && "Leftover temporaries in function");
5000 }
5001
John McCall90f97892010-03-25 22:08:03 +00005002 if (!IsInstantiation)
5003 PopDeclContext();
5004
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00005005 PopFunctionOrBlockScope();
Anders Carlssonf8a9a792009-11-13 19:21:49 +00005006
Douglas Gregord5b57282009-11-15 07:07:58 +00005007 // If any errors have occurred, clear out any temporaries that may have
5008 // been leftover. This ensures that these temporaries won't be picked up for
5009 // deletion in some later function.
Chris Lattner6d97e5e2010-03-01 20:59:53 +00005010 if (getDiagnostics().hasErrorOccurred())
Douglas Gregord5b57282009-11-15 07:07:58 +00005011 ExprTemporaries.clear();
Argyrios Kyrtzidis49b96d12010-08-13 18:42:17 +00005012
Steve Naroffd6d054d2007-11-11 23:20:51 +00005013 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00005014}
5015
Reid Spencer5f016e22007-07-11 17:01:13 +00005016/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
5017/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump1eb44332009-09-09 15:08:12 +00005018NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005019 IdentifierInfo &II, Scope *S) {
Douglas Gregor63935192009-03-02 00:19:53 +00005020 // Before we produce a declaration for an implicitly defined
5021 // function, see whether there was a locally-scoped declaration of
5022 // this name as a function or variable. If so, use that
5023 // (non-visible) declaration, and complain about it.
5024 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
5025 = LocallyScopedExternalDecls.find(&II);
5026 if (Pos != LocallyScopedExternalDecls.end()) {
5027 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
5028 Diag(Pos->second->getLocation(), diag::note_previous_declaration);
5029 return Pos->second;
5030 }
5031
Chris Lattner37d10842008-05-05 21:18:06 +00005032 // Extension in C99. Legal in C90, but warn about it.
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00005033 if (II.getName().startswith("__builtin_"))
Douglas Gregor9a8c9a22009-09-28 21:14:19 +00005034 Diag(Loc, diag::warn_builtin_unknown) << &II;
5035 else if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00005036 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00005037 else
Chris Lattner3c73c412008-11-19 08:23:25 +00005038 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Mike Stump1eb44332009-09-09 15:08:12 +00005039
Reid Spencer5f016e22007-07-11 17:01:13 +00005040 // Set a Declarator for the implicit definition: int foo();
5041 const char *Dummy;
5042 DeclSpec DS;
John McCallfec54012009-08-03 20:12:06 +00005043 unsigned DiagID;
5044 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +00005045 Error = Error; // Silence warning.
5046 assert(!Error && "Error setting up implicit decl!");
5047 Declarator D(DS, Declarator::BlockContext);
Sebastian Redl7dc81342009-04-29 17:30:04 +00005048 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
Sebastian Redl3cc97262009-05-31 11:47:27 +00005049 0, 0, false, SourceLocation(),
Argyrios Kyrtzidis82bf0102009-08-19 23:14:54 +00005050 false, 0,0,0, Loc, Loc, D),
Sebastian Redlab197ba2009-02-09 18:23:29 +00005051 SourceLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00005052 D.SetIdentifier(&II, Loc);
Sebastian Redlab197ba2009-02-09 18:23:29 +00005053
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00005054 // Insert this function into translation-unit scope.
5055
5056 DeclContext *PrevDC = CurContext;
5057 CurContext = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00005058
5059 FunctionDecl *FD =
Sean Huntcf807c42010-08-18 23:23:40 +00005060 dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D).getAs<Decl>());
Steve Naroffe2ef8152008-04-04 14:32:09 +00005061 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00005062
5063 CurContext = PrevDC;
5064
Douglas Gregor3c385e52009-02-14 18:57:46 +00005065 AddKnownFunctionAttributes(FD);
5066
Steve Naroffe2ef8152008-04-04 14:32:09 +00005067 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00005068}
5069
Douglas Gregor3c385e52009-02-14 18:57:46 +00005070/// \brief Adds any function attributes that we know a priori based on
5071/// the declaration of this function.
5072///
5073/// These attributes can apply both to implicitly-declared builtins
5074/// (like __builtin___printf_chk) or to library-declared functions
5075/// like NSLog or printf.
5076void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
5077 if (FD->isInvalidDecl())
5078 return;
5079
5080 // If this is a built-in function, map its builtin attributes to
5081 // actual attributes.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00005082 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00005083 // Handle printf-formatting attributes.
5084 unsigned FormatIdx;
5085 bool HasVAListArg;
5086 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005087 if (!FD->getAttr<FormatAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00005088 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
5089 "printf", FormatIdx+1,
Ted Kremenek3d2c43e2010-02-11 05:28:37 +00005090 HasVAListArg ? 0 : FormatIdx+2));
Douglas Gregor3c385e52009-02-14 18:57:46 +00005091 }
Ted Kremenekbee05c12010-07-16 02:11:15 +00005092 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
5093 HasVAListArg)) {
5094 if (!FD->getAttr<FormatAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00005095 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
5096 "scanf", FormatIdx+1,
Ted Kremenekbee05c12010-07-16 02:11:15 +00005097 HasVAListArg ? 0 : FormatIdx+2));
5098 }
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00005099
5100 // Mark const if we don't care about errno and that is the only
5101 // thing preventing the function from being const. This allows
5102 // IRgen to use LLVM intrinsics for such functions.
5103 if (!getLangOptions().MathErrno &&
5104 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005105 if (!FD->getAttr<ConstAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00005106 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00005107 }
Mike Stump0feecbb2009-07-27 19:14:18 +00005108
5109 if (Context.BuiltinInfo.isNoReturn(BuiltinID))
John McCall04a67a62010-02-05 21:31:56 +00005110 FD->setType(Context.getNoReturnType(FD->getType()));
Chris Lattner551f7082009-12-30 22:06:22 +00005111 if (Context.BuiltinInfo.isNoThrow(BuiltinID))
Sean Huntcf807c42010-08-18 23:23:40 +00005112 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
Chris Lattner551f7082009-12-30 22:06:22 +00005113 if (Context.BuiltinInfo.isConst(BuiltinID))
Sean Huntcf807c42010-08-18 23:23:40 +00005114 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Douglas Gregor3c385e52009-02-14 18:57:46 +00005115 }
5116
5117 IdentifierInfo *Name = FD->getIdentifier();
5118 if (!Name)
5119 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005120 if ((!getLangOptions().CPlusPlus &&
Douglas Gregor3c385e52009-02-14 18:57:46 +00005121 FD->getDeclContext()->isTranslationUnit()) ||
5122 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00005123 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregor3c385e52009-02-14 18:57:46 +00005124 LinkageSpecDecl::lang_c)) {
5125 // Okay: this could be a libc/libm/Objective-C function we know
5126 // about.
5127 } else
5128 return;
5129
Douglas Gregor21e072b2009-04-22 20:56:09 +00005130 if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
Mike Stump523a8fd2009-07-28 00:07:08 +00005131 // FIXME: NSLog and NSLogv should be target specific
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005132 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00005133 // FIXME: We known better than our headers.
Ted Kremenek3d2c43e2010-02-11 05:28:37 +00005134 const_cast<FormatAttr *>(Format)->setType(Context, "printf");
Mike Stump1eb44332009-09-09 15:08:12 +00005135 } else
Sean Huntcf807c42010-08-18 23:23:40 +00005136 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
5137 "printf", 1,
Eli Friedmand7dad722009-06-10 04:01:38 +00005138 Name->isStr("NSLogv") ? 0 : 2));
Douglas Gregor21e072b2009-04-22 20:56:09 +00005139 } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump523a8fd2009-07-28 00:07:08 +00005140 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump1eb44332009-09-09 15:08:12 +00005141 // target-specific builtins, perhaps?
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005142 if (!FD->getAttr<FormatAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00005143 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
5144 "printf", 2,
Eli Friedmand7dad722009-06-10 04:01:38 +00005145 Name->isStr("vasprintf") ? 0 : 3));
Mike Stump782fa302009-07-28 02:25:19 +00005146 }
Douglas Gregor3c385e52009-02-14 18:57:46 +00005147}
Reid Spencer5f016e22007-07-11 17:01:13 +00005148
John McCallba6a9bd2009-10-24 08:00:42 +00005149TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCalla93c9342009-12-07 02:54:59 +00005150 TypeSourceInfo *TInfo) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005151 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00005152 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump1eb44332009-09-09 15:08:12 +00005153
John McCalla93c9342009-12-07 02:54:59 +00005154 if (!TInfo) {
John McCallba6a9bd2009-10-24 08:00:42 +00005155 assert(D.isInvalidType() && "no declarator info for valid type");
John McCalla93c9342009-12-07 02:54:59 +00005156 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCallba6a9bd2009-10-24 08:00:42 +00005157 }
5158
Reid Spencer5f016e22007-07-11 17:01:13 +00005159 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00005160 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
5161 D.getIdentifierLoc(),
Mike Stump1eb44332009-09-09 15:08:12 +00005162 D.getIdentifier(),
John McCalla93c9342009-12-07 02:54:59 +00005163 TInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00005164
John McCall2191b202009-09-05 06:31:47 +00005165 if (const TagType *TT = T->getAs<TagType>()) {
Anders Carlsson4843e582009-03-10 17:07:44 +00005166 TagDecl *TD = TT->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00005167
Anders Carlsson4843e582009-03-10 17:07:44 +00005168 // If the TagDecl that the TypedefDecl points to is an anonymous decl
5169 // keep track of the TypedefDecl.
5170 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
5171 TD->setTypedefForAnonDecl(NewTD);
5172 }
5173
Chris Lattnereaaebc72009-04-25 08:06:05 +00005174 if (D.isInvalidType())
Steve Naroff5912a352007-08-28 20:14:24 +00005175 NewTD->setInvalidDecl();
5176 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00005177}
5178
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005179
5180/// \brief Determine whether a tag with a given kind is acceptable
5181/// as a redeclaration of the given tag declaration.
5182///
5183/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00005184bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005185 TagTypeKind NewTag,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005186 SourceLocation NewTagLoc,
5187 const IdentifierInfo &Name) {
5188 // C++ [dcl.type.elab]p3:
5189 // The class-key or enum keyword present in the
5190 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005191 // declaration to which the name in the elaborated-type-specifier
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005192 // refers. This rule also applies to the form of
5193 // elaborated-type-specifier that declares a class-name or
5194 // friend class since it can be construed as referring to the
5195 // definition of the class. Thus, in any
5196 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005197 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005198 // used to refer to a union (clause 9), and either the class or
5199 // struct class-key shall be used to refer to a class (clause 9)
5200 // declared using the class or struct class-key.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005201 TagTypeKind OldTag = Previous->getTagKind();
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005202 if (OldTag == NewTag)
5203 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005204
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005205 if ((OldTag == TTK_Struct || OldTag == TTK_Class) &&
5206 (NewTag == TTK_Struct || NewTag == TTK_Class)) {
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005207 // Warn about the struct/class tag mismatch.
5208 bool isTemplate = false;
5209 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
5210 isTemplate = Record->getDescribedClassTemplate();
5211
5212 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005213 << (NewTag == TTK_Class)
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005214 << isTemplate << &Name
Douglas Gregor849b2432010-03-31 17:46:05 +00005215 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005216 OldTag == TTK_Class? "class" : "struct");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005217 Diag(Previous->getLocation(), diag::note_previous_use);
5218 return true;
5219 }
5220 return false;
5221}
5222
Steve Naroff08d92e42007-09-15 18:49:24 +00005223/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00005224/// former case, Name will be non-null. In the later case, Name will be null.
John McCall0f434ec2009-07-31 02:45:11 +00005225/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Reid Spencer5f016e22007-07-11 17:01:13 +00005226/// reference/declaration/definition of a tag.
John McCall0f434ec2009-07-31 02:45:11 +00005227Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005228 SourceLocation KWLoc, CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005229 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregor402abb52009-05-28 23:31:59 +00005230 AttributeList *Attr, AccessSpecifier AS,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00005231 MultiTemplateParamsArg TemplateParameterLists,
John McCallc4e70192009-09-11 04:59:25 +00005232 bool &OwnedDecl, bool &IsDependent) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005233 // If this is not a definition, it must have a name.
John McCall0f434ec2009-07-31 02:45:11 +00005234 assert((Name != 0 || TUK == TUK_Definition) &&
Reid Spencer5f016e22007-07-11 17:01:13 +00005235 "Nameless record must be a definition!");
Douglas Gregoraaba5e32009-02-04 19:02:06 +00005236
Douglas Gregor402abb52009-05-28 23:31:59 +00005237 OwnedDecl = false;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005238 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00005239
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005240 // FIXME: Check explicit specializations more carefully.
5241 bool isExplicitSpecialization = false;
Abramo Bagnara9b934882010-06-12 08:15:14 +00005242 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
Douglas Gregor0167f3c2010-07-14 23:14:12 +00005243 bool Invalid = false;
John McCall0f434ec2009-07-31 02:45:11 +00005244 if (TUK != TUK_Reference) {
Douglas Gregor7cdbc582009-07-22 23:48:44 +00005245 if (TemplateParameterList *TemplateParams
5246 = MatchTemplateParametersToScopeSpecifier(KWLoc, SS,
5247 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00005248 TemplateParameterLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00005249 TUK == TUK_Friend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00005250 isExplicitSpecialization,
5251 Invalid)) {
Abramo Bagnara9b934882010-06-12 08:15:14 +00005252 // All but one template parameter lists have been matching.
5253 --NumMatchedTemplateParamLists;
5254
Douglas Gregord85bea22009-09-26 06:47:28 +00005255 if (TemplateParams->size() > 0) {
Douglas Gregor7cdbc582009-07-22 23:48:44 +00005256 // This is a declaration or definition of a class template (which may
5257 // be a member of another template).
Douglas Gregor0167f3c2010-07-14 23:14:12 +00005258 if (Invalid)
5259 return DeclPtrTy();
5260
Douglas Gregor7cdbc582009-07-22 23:48:44 +00005261 OwnedDecl = false;
John McCall0f434ec2009-07-31 02:45:11 +00005262 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00005263 SS, Name, NameLoc, Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00005264 TemplateParams,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00005265 AS);
Douglas Gregor05396e22009-08-25 17:23:04 +00005266 TemplateParameterLists.release();
Douglas Gregor7cdbc582009-07-22 23:48:44 +00005267 return Result.get();
5268 } else {
Douglas Gregorf6b11852009-10-08 15:14:33 +00005269 // The "template<>" header is extraneous.
5270 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005271 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorf6b11852009-10-08 15:14:33 +00005272 isExplicitSpecialization = true;
Douglas Gregor7cdbc582009-07-22 23:48:44 +00005273 }
Mike Stump1eb44332009-09-09 15:08:12 +00005274 }
5275 }
5276
Douglas Gregor4920f1f2009-01-12 22:49:06 +00005277 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00005278 DeclContext *DC = CurContext;
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005279 bool isStdBadAlloc = false;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00005280
Chandler Carruth7bf36002010-03-01 21:17:36 +00005281 RedeclarationKind Redecl = ForRedeclaration;
5282 if (TUK == TUK_Friend || TUK == TUK_Reference)
5283 Redecl = NotForRedeclaration;
John McCall68263142009-11-18 22:49:29 +00005284
5285 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
John McCall6e247262009-10-10 05:48:19 +00005286
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00005287 if (Name && SS.isNotEmpty()) {
5288 // We have a nested-name tag ('struct foo::bar').
5289
5290 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00005291 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00005292 Name = 0;
5293 goto CreateNewDecl;
5294 }
5295
John McCallc4e70192009-09-11 04:59:25 +00005296 // If this is a friend or a reference to a class in a dependent
5297 // context, don't try to make a decl for it.
5298 if (TUK == TUK_Friend || TUK == TUK_Reference) {
5299 DC = computeDeclContext(SS, false);
5300 if (!DC) {
5301 IsDependent = true;
5302 return DeclPtrTy();
5303 }
John McCall77bb1aa2010-05-01 00:40:08 +00005304 } else {
5305 DC = computeDeclContext(SS, true);
5306 if (!DC) {
5307 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
5308 << SS.getRange();
5309 return DeclPtrTy();
5310 }
John McCallc4e70192009-09-11 04:59:25 +00005311 }
5312
John McCall77bb1aa2010-05-01 00:40:08 +00005313 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005314 return DeclPtrTy::make((Decl *)0);
5315
Douglas Gregor1931b442009-02-03 00:34:39 +00005316 SearchDC = DC;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00005317 // Look-up name inside 'foo::'.
John McCall68263142009-11-18 22:49:29 +00005318 LookupQualifiedName(Previous, DC);
John McCall6e247262009-10-10 05:48:19 +00005319
John McCall68263142009-11-18 22:49:29 +00005320 if (Previous.isAmbiguous())
John McCall6e247262009-10-10 05:48:19 +00005321 return DeclPtrTy();
John McCall6e247262009-10-10 05:48:19 +00005322
John McCall68263142009-11-18 22:49:29 +00005323 if (Previous.empty()) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +00005324 // Name lookup did not find anything. However, if the
5325 // nested-name-specifier refers to the current instantiation,
5326 // and that current instantiation has any dependent base
5327 // classes, we might find something at instantiation time: treat
5328 // this as a dependent elaborated-type-specifier.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00005329 if (Previous.wasNotFoundInCurrentInstantiation()) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +00005330 IsDependent = true;
5331 return DeclPtrTy();
5332 }
5333
5334 // A tag 'foo::bar' must already exist.
Douglas Gregor1eabb7d2010-03-31 23:17:41 +00005335 Diag(NameLoc, diag::err_not_tag_in_scope)
5336 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00005337 Name = 0;
Douglas Gregord0c87372009-05-27 17:30:49 +00005338 Invalid = true;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00005339 goto CreateNewDecl;
5340 }
Chris Lattnercf79b012009-01-21 02:38:50 +00005341 } else if (Name) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00005342 // If this is a named struct, check to see if there was a previous forward
5343 // declaration or definition.
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005344 // FIXME: We're looking into outer scopes here, even when we
5345 // shouldn't be. Doing so can result in ambiguities that we
5346 // shouldn't be diagnosing.
John McCall68263142009-11-18 22:49:29 +00005347 LookupName(Previous, S);
5348
5349 // Note: there used to be some attempt at recovery here.
5350 if (Previous.isAmbiguous())
5351 return DeclPtrTy();
Douglas Gregor72de6672009-01-08 20:45:30 +00005352
John McCall0f434ec2009-07-31 02:45:11 +00005353 if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor72de6672009-01-08 20:45:30 +00005354 // FIXME: This makes sure that we ignore the contexts associated
5355 // with C structs, unions, and enums when looking for a matching
5356 // tag declaration or definition. See the similar lookup tweak
Douglas Gregor4c921ae2009-01-30 01:04:22 +00005357 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregor4920f1f2009-01-12 22:49:06 +00005358 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
5359 SearchDC = SearchDC->getParent();
Douglas Gregor72de6672009-01-08 20:45:30 +00005360 }
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00005361 }
5362
John McCall68263142009-11-18 22:49:29 +00005363 if (Previous.isSingleResult() &&
5364 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00005365 // Maybe we will complain about the shadowed template parameter.
John McCall68263142009-11-18 22:49:29 +00005366 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor72c3f312008-12-05 18:15:24 +00005367 // Just pretend that we didn't see the previous declaration.
John McCall68263142009-11-18 22:49:29 +00005368 Previous.clear();
Douglas Gregor72c3f312008-12-05 18:15:24 +00005369 }
5370
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005371 if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005372 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005373 // This is a declaration of or a reference to "std::bad_alloc".
5374 isStdBadAlloc = true;
5375
John McCall68263142009-11-18 22:49:29 +00005376 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005377 // std::bad_alloc has been implicitly declared (but made invisible to
5378 // name lookup). Fill in this implicit declaration as the previous
5379 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005380 Previous.addDecl(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005381 }
5382 }
John McCall68263142009-11-18 22:49:29 +00005383
John McCall9c86b512010-03-25 21:28:06 +00005384 // If we didn't find a previous declaration, and this is a reference
5385 // (or friend reference), move to the correct scope. In C++, we
5386 // also need to do a redeclaration lookup there, just in case
5387 // there's a shadow friend decl.
5388 if (Name && Previous.empty() &&
5389 (TUK == TUK_Reference || TUK == TUK_Friend)) {
5390 if (Invalid) goto CreateNewDecl;
5391 assert(SS.isEmpty());
5392
5393 if (TUK == TUK_Reference) {
5394 // C++ [basic.scope.pdecl]p5:
5395 // -- for an elaborated-type-specifier of the form
5396 //
5397 // class-key identifier
5398 //
5399 // if the elaborated-type-specifier is used in the
5400 // decl-specifier-seq or parameter-declaration-clause of a
5401 // function defined in namespace scope, the identifier is
5402 // declared as a class-name in the namespace that contains
5403 // the declaration; otherwise, except as a friend
5404 // declaration, the identifier is declared in the smallest
5405 // non-class, non-function-prototype scope that contains the
5406 // declaration.
5407 //
5408 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
5409 // C structs and unions.
5410 //
5411 // It is an error in C++ to declare (rather than define) an enum
5412 // type, including via an elaborated type specifier. We'll
5413 // diagnose that later; for now, declare the enum in the same
5414 // scope as we would have picked for any other tag type.
5415 //
5416 // GNU C also supports this behavior as part of its incomplete
5417 // enum types extension, while GNU C++ does not.
5418 //
5419 // Find the context where we'll be declaring the tag.
5420 // FIXME: We would like to maintain the current DeclContext as the
5421 // lexical context,
5422 while (SearchDC->isRecord())
5423 SearchDC = SearchDC->getParent();
5424
5425 // Find the scope where we'll be declaring the tag.
5426 while (S->isClassScope() ||
5427 (getLangOptions().CPlusPlus &&
5428 S->isFunctionPrototypeScope()) ||
5429 ((S->getFlags() & Scope::DeclScope) == 0) ||
5430 (S->getEntity() &&
5431 ((DeclContext *)S->getEntity())->isTransparentContext()))
5432 S = S->getParent();
5433 } else {
5434 assert(TUK == TUK_Friend);
5435 // C++ [namespace.memdef]p3:
5436 // If a friend declaration in a non-local class first declares a
5437 // class or function, the friend class or function is a member of
5438 // the innermost enclosing namespace.
5439 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCall9c86b512010-03-25 21:28:06 +00005440 }
5441
John McCall0d6b1642010-04-23 18:46:30 +00005442 // In C++, we need to do a redeclaration lookup to properly
5443 // diagnose some problems.
John McCall9c86b512010-03-25 21:28:06 +00005444 if (getLangOptions().CPlusPlus) {
5445 Previous.setRedeclarationKind(ForRedeclaration);
5446 LookupQualifiedName(Previous, SearchDC);
5447 }
5448 }
5449
John McCall68263142009-11-18 22:49:29 +00005450 if (!Previous.empty()) {
Douglas Gregor57265e32010-04-12 16:00:01 +00005451 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
John McCall0d6b1642010-04-23 18:46:30 +00005452
5453 // It's okay to have a tag decl in the same scope as a typedef
5454 // which hides a tag decl in the same scope. Finding this
5455 // insanity with a redeclaration lookup can only actually happen
5456 // in C++.
5457 //
5458 // This is also okay for elaborated-type-specifiers, which is
5459 // technically forbidden by the current standard but which is
5460 // okay according to the likely resolution of an open issue;
5461 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
5462 if (getLangOptions().CPlusPlus) {
5463 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(PrevDecl)) {
5464 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
5465 TagDecl *Tag = TT->getDecl();
5466 if (Tag->getDeclName() == Name &&
Douglas Gregorc8fd2da2010-04-27 16:26:47 +00005467 Tag->getDeclContext()->getLookupContext()
5468 ->Equals(TD->getDeclContext()->getLookupContext())) {
John McCall0d6b1642010-04-23 18:46:30 +00005469 PrevDecl = Tag;
5470 Previous.clear();
5471 Previous.addDecl(Tag);
5472 }
5473 }
5474 }
5475 }
5476
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005477 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00005478 // If this is a use of a previous tag, or if the tag is already declared
5479 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005480 // rementions the tag), reuse the decl.
John McCall67d1a672009-08-06 02:15:43 +00005481 if (TUK == TUK_Reference || TUK == TUK_Friend ||
5482 isDeclInScope(PrevDecl, SearchDC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00005483 // Make sure that this wasn't declared as an enum and now used as a
5484 // struct or something similar.
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005485 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +00005486 bool SafeToContinue
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005487 = (PrevTagDecl->getTagKind() != TTK_Enum &&
5488 Kind != TTK_Enum);
Douglas Gregora3a83512009-04-01 23:51:29 +00005489 if (SafeToContinue)
Mike Stump1eb44332009-09-09 15:08:12 +00005490 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00005491 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +00005492 << FixItHint::CreateReplacement(SourceRange(KWLoc),
5493 PrevTagDecl->getKindName());
Douglas Gregora3a83512009-04-01 23:51:29 +00005494 else
5495 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall68263142009-11-18 22:49:29 +00005496 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +00005497
Mike Stump1eb44332009-09-09 15:08:12 +00005498 if (SafeToContinue)
Douglas Gregora3a83512009-04-01 23:51:29 +00005499 Kind = PrevTagDecl->getTagKind();
5500 else {
5501 // Recover by making this an anonymous redefinition.
5502 Name = 0;
John McCall68263142009-11-18 22:49:29 +00005503 Previous.clear();
Douglas Gregora3a83512009-04-01 23:51:29 +00005504 Invalid = true;
5505 }
5506 }
5507
5508 if (!Invalid) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005509 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +00005510
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005511 // FIXME: In the future, return a variant or some other clue
5512 // for the consumer of this Decl to know it doesn't own it.
5513 // For our current ASTs this shouldn't be a problem, but will
5514 // need to be changed with DeclGroups.
Douglas Gregore1aa9f32010-06-08 21:27:36 +00005515 if ((TUK == TUK_Reference && !PrevTagDecl->getFriendObjectKind()) ||
5516 TUK == TUK_Friend)
John McCall68263142009-11-18 22:49:29 +00005517 return DeclPtrTy::make(PrevTagDecl);
Douglas Gregoraaba5e32009-02-04 19:02:06 +00005518
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005519 // Diagnose attempts to redefine a tag.
John McCall0f434ec2009-07-31 02:45:11 +00005520 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00005521 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005522 // If we're defining a specialization and the previous definition
5523 // is from an implicit instantiation, don't emit an error
5524 // here; we'll catch this in the general case below.
5525 if (!isExplicitSpecialization ||
5526 !isa<CXXRecordDecl>(Def) ||
5527 cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
5528 == TSK_ExplicitSpecialization) {
5529 Diag(NameLoc, diag::err_redefinition) << Name;
5530 Diag(Def->getLocation(), diag::note_previous_definition);
5531 // If this is a redefinition, recover by making this
5532 // struct be anonymous, which will make any later
5533 // references get the previous definition.
5534 Name = 0;
John McCall68263142009-11-18 22:49:29 +00005535 Previous.clear();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00005536 Invalid = true;
5537 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +00005538 } else {
5539 // If the type is currently being defined, complain
5540 // about a nested redefinition.
5541 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
5542 if (Tag->isBeingDefined()) {
5543 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump1eb44332009-09-09 15:08:12 +00005544 Diag(PrevTagDecl->getLocation(),
Douglas Gregor0b7a1582009-01-17 00:42:38 +00005545 diag::note_previous_definition);
5546 Name = 0;
John McCall68263142009-11-18 22:49:29 +00005547 Previous.clear();
Douglas Gregor0b7a1582009-01-17 00:42:38 +00005548 Invalid = true;
5549 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005550 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +00005551
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005552 // Okay, this is definition of a previously declared or referenced
5553 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00005554 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005555 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005556 // If we get here we have (another) forward declaration or we
John McCall67d1a672009-08-06 02:15:43 +00005557 // have a definition. Just create a new decl.
5558
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005559 } else {
5560 // If we get here, this is a definition of a new tag type in a nested
Mike Stump1eb44332009-09-09 15:08:12 +00005561 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005562 // new decl/type. We set PrevDecl to NULL so that the entities
5563 // have distinct types.
John McCall68263142009-11-18 22:49:29 +00005564 Previous.clear();
Reid Spencer5f016e22007-07-11 17:01:13 +00005565 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005566 // If we get here, we're going to create a new Decl. If PrevDecl
5567 // is non-NULL, it's a definition of the tag declared by
5568 // PrevDecl. If it's NULL, we have a new definition.
John McCall0d6b1642010-04-23 18:46:30 +00005569
5570
5571 // Otherwise, PrevDecl is not a tag, but was found with tag
5572 // lookup. This is only actually possible in C++, where a few
5573 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005574 } else {
John McCall0d6b1642010-04-23 18:46:30 +00005575 assert(getLangOptions().CPlusPlus);
5576
5577 // Use a better diagnostic if an elaborated-type-specifier
5578 // found the wrong kind of type on the first
5579 // (non-redeclaration) lookup.
5580 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
5581 !Previous.isForRedeclaration()) {
5582 unsigned Kind = 0;
5583 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
5584 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 2;
5585 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
5586 Diag(PrevDecl->getLocation(), diag::note_declared_at);
5587 Invalid = true;
5588
5589 // Otherwise, only diagnose if the declaration is in scope.
5590 } else if (!isDeclInScope(PrevDecl, SearchDC, S)) {
5591 // do nothing
5592
5593 // Diagnose implicit declarations introduced by elaborated types.
5594 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
5595 unsigned Kind = 0;
5596 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
5597 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 2;
5598 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
5599 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
5600 Invalid = true;
5601
5602 // Otherwise it's a declaration. Call out a particularly common
5603 // case here.
5604 } else if (isa<TypedefDecl>(PrevDecl)) {
5605 Diag(NameLoc, diag::err_tag_definition_of_typedef)
5606 << Name
5607 << cast<TypedefDecl>(PrevDecl)->getUnderlyingType();
5608 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
5609 Invalid = true;
5610
5611 // Otherwise, diagnose.
5612 } else {
5613 // The tag name clashes with something else in the target scope,
5614 // issue an error and recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00005615 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00005616 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00005617 Name = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00005618 Invalid = true;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00005619 }
John McCall0d6b1642010-04-23 18:46:30 +00005620
5621 // The existing declaration isn't relevant to us; we're in a
5622 // new scope, so clear out the previous declaration.
5623 Previous.clear();
Reid Spencer5f016e22007-07-11 17:01:13 +00005624 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005625 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00005626
Chris Lattnercc98eac2008-12-17 07:13:27 +00005627CreateNewDecl:
Mike Stump1eb44332009-09-09 15:08:12 +00005628
John McCall68263142009-11-18 22:49:29 +00005629 TagDecl *PrevDecl = 0;
5630 if (Previous.isSingleResult())
5631 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
5632
Reid Spencer5f016e22007-07-11 17:01:13 +00005633 // If there is an identifier, use the location of the identifier as the
5634 // location of the decl, otherwise use the location of the struct/union
5635 // keyword.
5636 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00005637
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005638 // Otherwise, create a new declaration. If there is a previous
5639 // declaration of the same entity, the two will be linked via
5640 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +00005641 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00005642
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005643 if (Kind == TTK_Enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005644 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
5645 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor741dd9a2009-07-21 14:46:17 +00005646 New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005647 cast_or_null<EnumDecl>(PrevDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00005648 // If this is an undefined enum, warn.
Douglas Gregorf3a7b7c2010-06-22 14:26:35 +00005649 if (TUK != TUK_Definition && !Invalid) {
5650 TagDecl *Def;
5651 if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
5652 Diag(Loc, diag::ext_forward_ref_enum_def)
5653 << New;
5654 Diag(Def->getLocation(), diag::note_previous_definition);
5655 } else {
5656 Diag(Loc,
5657 getLangOptions().CPlusPlus? diag::err_forward_ref_enum
5658 : diag::ext_forward_ref_enum);
5659 }
Douglas Gregor80711a22009-03-06 18:34:03 +00005660 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00005661 } else {
5662 // struct/union/class
5663
Reid Spencer5f016e22007-07-11 17:01:13 +00005664 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
5665 // struct X { int A; } D; D should chain to X.
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005666 if (getLangOptions().CPlusPlus) {
Ted Kremenek2b345eb2008-09-05 17:39:33 +00005667 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor741dd9a2009-07-21 14:46:17 +00005668 New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005669 cast_or_null<CXXRecordDecl>(PrevDecl));
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005670
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005671 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005672 StdBadAlloc = cast<CXXRecordDecl>(New);
5673 } else
Douglas Gregor741dd9a2009-07-21 14:46:17 +00005674 New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005675 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005676 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005677
John McCallb6217662010-03-15 10:12:16 +00005678 // Maybe add qualifier info.
5679 if (SS.isNotEmpty()) {
Fariborz Jahanian4fb20532010-05-14 21:35:02 +00005680 if (SS.isSet()) {
5681 NestedNameSpecifier *NNS
5682 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5683 New->setQualifierInfo(NNS, SS.getRange());
Abramo Bagnara9b934882010-06-12 08:15:14 +00005684 if (NumMatchedTemplateParamLists > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00005685 New->setTemplateParameterListsInfo(Context,
5686 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00005687 (TemplateParameterList**) TemplateParameterLists.release());
5688 }
Fariborz Jahanian4fb20532010-05-14 21:35:02 +00005689 }
5690 else
5691 Invalid = true;
John McCallb6217662010-03-15 10:12:16 +00005692 }
5693
Daniel Dunbar9f21f892010-05-27 01:53:40 +00005694 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
5695 // Add alignment attributes if necessary; these attributes are checked when
5696 // the ASTContext lays out the structure.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005697 //
5698 // It is important for implementing the correct semantics that this
5699 // happen here (in act on tag decl). The #pragma pack stack is
5700 // maintained as a result of parser callbacks which can occur at
5701 // many points during the parsing of a struct declaration (because
5702 // the #pragma tokens are effectively skipped over during the
5703 // parsing of the struct).
Daniel Dunbar9f21f892010-05-27 01:53:40 +00005704 AddAlignmentAttributesForRecord(RD);
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005705 }
5706
Douglas Gregorf6b11852009-10-08 15:14:33 +00005707 // If this is a specialization of a member class (of a class template),
5708 // check the specialization.
John McCall68263142009-11-18 22:49:29 +00005709 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorf6b11852009-10-08 15:14:33 +00005710 Invalid = true;
Daniel Dunbar9f21f892010-05-27 01:53:40 +00005711
Douglas Gregor0b7a1582009-01-17 00:42:38 +00005712 if (Invalid)
5713 New->setInvalidDecl();
5714
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005715 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005716 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005717
Douglas Gregor0b7a1582009-01-17 00:42:38 +00005718 // If we're declaring or defining a tag in function prototype scope
5719 // in C, note that this type can only be used within the function.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00005720 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
5721 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
5722
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00005723 // Set the lexical context. If the tag has a C++ scope specifier, the
5724 // lexical context will be different from the semantic context.
Douglas Gregor1931b442009-02-03 00:34:39 +00005725 New->setLexicalDeclContext(CurContext);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00005726
John McCall02cace72009-08-28 07:59:38 +00005727 // Mark this as a friend decl if applicable.
5728 if (TUK == TUK_Friend)
John McCall68263142009-11-18 22:49:29 +00005729 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty());
John McCall02cace72009-08-28 07:59:38 +00005730
Anders Carlsson0cf88302009-03-26 01:19:02 +00005731 // Set the access specifier.
John McCall9c86b512010-03-25 21:28:06 +00005732 if (!Invalid && SearchDC->isRecord())
Douglas Gregord0c87372009-05-27 17:30:49 +00005733 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor06c0fec2009-03-25 22:00:53 +00005734
John McCall0f434ec2009-07-31 02:45:11 +00005735 if (TUK == TUK_Definition)
Douglas Gregor0b7a1582009-01-17 00:42:38 +00005736 New->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00005737
Reid Spencer5f016e22007-07-11 17:01:13 +00005738 // If this has an identifier, add it to the scope stack.
John McCalld7eff682009-09-02 00:55:30 +00005739 if (TUK == TUK_Friend) {
John McCall82b9fb82009-09-02 19:32:14 +00005740 // We might be replacing an existing declaration in the lookup tables;
5741 // if so, borrow its access specifier.
5742 if (PrevDecl)
5743 New->setAccess(PrevDecl->getAccess());
5744
John McCall9c86b512010-03-25 21:28:06 +00005745 DeclContext *DC = New->getDeclContext()->getLookupContext();
5746 DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
5747 if (Name) // can be null along some error paths
John McCalld7eff682009-09-02 00:55:30 +00005748 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
5749 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCalld7eff682009-09-02 00:55:30 +00005750 } else if (Name) {
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00005751 S = getNonFieldDeclScope(S);
Douglas Gregor1931b442009-02-03 00:34:39 +00005752 PushOnScopeChains(New, S);
Douglas Gregor4920f1f2009-01-12 22:49:06 +00005753 } else {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005754 CurContext->addDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00005755 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00005756
Douglas Gregorc29f77b2009-07-07 16:35:42 +00005757 // If this is the C FILE type, notify the AST context.
5758 if (IdentifierInfo *II = New->getIdentifier())
5759 if (!New->isInvalidDecl() &&
Mike Stump782fa302009-07-28 02:25:19 +00005760 New->getDeclContext()->getLookupContext()->isTranslationUnit() &&
Douglas Gregorc29f77b2009-07-07 16:35:42 +00005761 II->isStr("FILE"))
5762 Context.setFILEDecl(New);
Mike Stump1eb44332009-09-09 15:08:12 +00005763
Douglas Gregor402abb52009-05-28 23:31:59 +00005764 OwnedDecl = true;
Chris Lattnerb28317a2009-03-28 19:18:32 +00005765 return DeclPtrTy::make(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00005766}
5767
Chris Lattnerb28317a2009-03-28 19:18:32 +00005768void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +00005769 AdjustDeclIfTemplate(TagD);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005770 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
Douglas Gregor48c89f42010-04-24 16:38:41 +00005771
Douglas Gregor72de6672009-01-08 20:45:30 +00005772 // Enter the tag context.
5773 PushDeclContext(S, Tag);
John McCallf9368152009-12-20 07:58:13 +00005774}
Douglas Gregor72de6672009-01-08 20:45:30 +00005775
John McCallf9368152009-12-20 07:58:13 +00005776void Sema::ActOnStartCXXMemberDeclarations(Scope *S, DeclPtrTy TagD,
5777 SourceLocation LBraceLoc) {
5778 AdjustDeclIfTemplate(TagD);
5779 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD.getAs<Decl>());
Douglas Gregor72de6672009-01-08 20:45:30 +00005780
John McCallf9368152009-12-20 07:58:13 +00005781 FieldCollector->StartClass();
5782
5783 if (!Record->getIdentifier())
5784 return;
5785
5786 // C++ [class]p2:
5787 // [...] The class-name is also inserted into the scope of the
5788 // class itself; this is known as the injected-class-name. For
5789 // purposes of access checking, the injected-class-name is treated
5790 // as if it were a public member name.
5791 CXXRecordDecl *InjectedClassName
5792 = CXXRecordDecl::Create(Context, Record->getTagKind(),
5793 CurContext, Record->getLocation(),
5794 Record->getIdentifier(),
5795 Record->getTagKeywordLoc(),
5796 Record);
5797 InjectedClassName->setImplicit();
5798 InjectedClassName->setAccess(AS_public);
5799 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
5800 InjectedClassName->setDescribedClassTemplate(Template);
5801 PushOnScopeChains(InjectedClassName, S);
5802 assert(InjectedClassName->isInjectedClassName() &&
5803 "Broken injected-class-name");
Douglas Gregor72de6672009-01-08 20:45:30 +00005804}
5805
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +00005806void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD,
5807 SourceLocation RBraceLoc) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +00005808 AdjustDeclIfTemplate(TagD);
Chris Lattnerb28317a2009-03-28 19:18:32 +00005809 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
Argyrios Kyrtzidis07a5b282009-07-14 03:17:52 +00005810 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor72de6672009-01-08 20:45:30 +00005811
5812 if (isa<CXXRecordDecl>(Tag))
5813 FieldCollector->FinishClass();
5814
5815 // Exit this scope of this tag's definition.
5816 PopDeclContext();
Douglas Gregoradda8462010-01-06 17:00:51 +00005817
Douglas Gregor72de6672009-01-08 20:45:30 +00005818 // Notify the consumer that we've defined a tag.
5819 Consumer.HandleTagDeclDefinition(Tag);
5820}
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00005821
John McCalldb7bb4a2010-03-17 00:38:33 +00005822void Sema::ActOnTagDefinitionError(Scope *S, DeclPtrTy TagD) {
5823 AdjustDeclIfTemplate(TagD);
5824 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
John McCalldb7bb4a2010-03-17 00:38:33 +00005825 Tag->setInvalidDecl();
5826
John McCalla8cab012010-03-17 19:25:57 +00005827 // We're undoing ActOnTagStartDefinition here, not
5828 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
5829 // the FieldCollector.
John McCalldb7bb4a2010-03-17 00:38:33 +00005830
5831 PopDeclContext();
5832}
5833
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00005834// Note that FieldName may be null for anonymous bitfields.
Mike Stump1eb44332009-09-09 15:08:12 +00005835bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Eli Friedman1d954f62009-08-15 21:55:26 +00005836 QualType FieldTy, const Expr *BitWidth,
5837 bool *ZeroWidth) {
5838 // Default to true; that shouldn't confuse checks for emptiness
5839 if (ZeroWidth)
5840 *ZeroWidth = true;
5841
Chris Lattner24793662009-03-05 22:45:59 +00005842 // C99 6.7.2.1p4 - verify the field type.
Chris Lattner8b963ef2009-03-05 23:01:03 +00005843 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregor2ade35e2010-06-16 00:17:44 +00005844 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner24793662009-03-05 22:45:59 +00005845 // Handle incomplete types with specific error.
Douglas Gregora03aca82009-03-10 21:58:27 +00005846 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
5847 return true;
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00005848 if (FieldName)
5849 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
5850 << FieldName << FieldTy << BitWidth->getSourceRange();
5851 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
5852 << FieldTy << BitWidth->getSourceRange();
Chris Lattner24793662009-03-05 22:45:59 +00005853 }
Douglas Gregor3cf538d2009-03-11 18:59:21 +00005854
5855 // If the bit-width is type- or value-dependent, don't try to check
5856 // it now.
5857 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
5858 return false;
5859
Anders Carlsson9f1e5722008-12-06 20:33:04 +00005860 llvm::APSInt Value;
5861 if (VerifyIntegerConstantExpression(BitWidth, &Value))
5862 return true;
5863
Eli Friedman1d954f62009-08-15 21:55:26 +00005864 if (Value != 0 && ZeroWidth)
5865 *ZeroWidth = false;
5866
Chris Lattnercd087072008-12-12 04:56:04 +00005867 // Zero-width bitfield is ok for anonymous field.
5868 if (Value == 0 && FieldName)
5869 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00005870
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00005871 if (Value.isSigned() && Value.isNegative()) {
5872 if (FieldName)
Mike Stump1eb44332009-09-09 15:08:12 +00005873 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00005874 << FieldName << Value.toString(10);
5875 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
5876 << Value.toString(10);
5877 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00005878
Douglas Gregor3cf538d2009-03-11 18:59:21 +00005879 if (!FieldTy->isDependentType()) {
5880 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00005881 if (Value.getZExtValue() > TypeSize) {
Anders Carlsson72468ec2010-04-16 15:16:32 +00005882 if (!getLangOptions().CPlusPlus) {
5883 if (FieldName)
5884 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
5885 << FieldName << (unsigned)Value.getZExtValue()
5886 << (unsigned)TypeSize;
5887
5888 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
5889 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
5890 }
5891
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00005892 if (FieldName)
Anders Carlsson72468ec2010-04-16 15:16:32 +00005893 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
5894 << FieldName << (unsigned)Value.getZExtValue()
5895 << (unsigned)TypeSize;
5896 else
5897 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
5898 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerdf9bcd52009-04-20 17:29:38 +00005899 }
Douglas Gregor3cf538d2009-03-11 18:59:21 +00005900 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00005901
5902 return false;
5903}
5904
Steve Naroff08d92e42007-09-15 18:49:24 +00005905/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00005906/// to create a FieldDecl object for it.
Chris Lattnerb28317a2009-03-28 19:18:32 +00005907Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD,
Mike Stump1eb44332009-09-09 15:08:12 +00005908 SourceLocation DeclStart,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005909 Declarator &D, ExprTy *BitfieldWidth) {
5910 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()),
5911 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
5912 AS_public);
5913 return DeclPtrTy::make(Res);
Chris Lattner24793662009-03-05 22:45:59 +00005914}
5915
5916/// HandleField - Analyze a field of a C struct or a C++ data member.
5917///
5918FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
5919 SourceLocation DeclStart,
Douglas Gregor4dd55f52009-03-11 20:50:30 +00005920 Declarator &D, Expr *BitWidth,
5921 AccessSpecifier AS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005922 IdentifierInfo *II = D.getIdentifier();
Reid Spencer5f016e22007-07-11 17:01:13 +00005923 SourceLocation Loc = DeclStart;
5924 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00005925
John McCallbf1a0282010-06-04 23:28:52 +00005926 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5927 QualType T = TInfo->getType();
Chris Lattner6491f472009-04-12 22:15:02 +00005928 if (getLangOptions().CPlusPlus)
Douglas Gregor3cf538d2009-03-11 18:59:21 +00005929 CheckExtraCXXDefaultArguments(D);
Douglas Gregor021c3b32009-03-11 23:00:04 +00005930
Eli Friedman85a53192009-04-07 19:37:57 +00005931 DiagnoseFunctionSpecifiers(D);
5932
Eli Friedman63054b32009-04-19 20:27:55 +00005933 if (D.getDeclSpec().isThreadSpecified())
5934 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
5935
Douglas Gregorc83c6872010-04-15 22:33:43 +00005936 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall7d384dd2009-11-18 07:57:50 +00005937 ForRedeclaration);
Douglas Gregorc19ee3e2009-06-17 23:37:01 +00005938
5939 if (PrevDecl && PrevDecl->isTemplateParameter()) {
5940 // Maybe we will complain about the shadowed template parameter.
5941 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5942 // Just pretend that we didn't see the previous declaration.
5943 PrevDecl = 0;
5944 }
5945
Douglas Gregor3cf538d2009-03-11 18:59:21 +00005946 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
5947 PrevDecl = 0;
5948
Steve Naroffea218b82009-07-14 14:58:18 +00005949 bool Mutable
5950 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
5951 SourceLocation TSSL = D.getSourceRange().getBegin();
5952 FieldDecl *NewFD
John McCalla93c9342009-12-07 02:54:59 +00005953 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, TSSL,
Steve Naroffea218b82009-07-14 14:58:18 +00005954 AS, PrevDecl, &D);
Rafael Espindola01620702010-03-21 22:56:43 +00005955
5956 if (NewFD->isInvalidDecl())
5957 Record->setInvalidDecl();
5958
Douglas Gregor3cf538d2009-03-11 18:59:21 +00005959 if (NewFD->isInvalidDecl() && PrevDecl) {
5960 // Don't introduce NewFD into scope; there's already something
5961 // with the same name in the same scope.
5962 } else if (II) {
5963 PushOnScopeChains(NewFD, S);
5964 } else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005965 Record->addDecl(NewFD);
Douglas Gregor3cf538d2009-03-11 18:59:21 +00005966
5967 return NewFD;
5968}
5969
5970/// \brief Build a new FieldDecl and check its well-formedness.
5971///
5972/// This routine builds a new FieldDecl given the fields name, type,
5973/// record, etc. \p PrevDecl should refer to any previous declaration
5974/// with the same name and in the same scope as the field to be
5975/// created.
5976///
5977/// \returns a new FieldDecl.
5978///
Mike Stump1eb44332009-09-09 15:08:12 +00005979/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00005980FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCalla93c9342009-12-07 02:54:59 +00005981 TypeSourceInfo *TInfo,
Douglas Gregor3cf538d2009-03-11 18:59:21 +00005982 RecordDecl *Record, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00005983 bool Mutable, Expr *BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +00005984 SourceLocation TSSL,
Douglas Gregor4dd55f52009-03-11 20:50:30 +00005985 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor3cf538d2009-03-11 18:59:21 +00005986 Declarator *D) {
5987 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Naroff5912a352007-08-28 20:14:24 +00005988 bool InvalidDecl = false;
Chris Lattnereaaebc72009-04-25 08:06:05 +00005989 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redl64b45f72009-01-05 20:52:13 +00005990
Douglas Gregor3cf538d2009-03-11 18:59:21 +00005991 // If we receive a broken type, recover by assuming 'int' and
5992 // marking this declaration as invalid.
5993 if (T.isNull()) {
5994 InvalidDecl = true;
5995 T = Context.IntTy;
5996 }
5997
Eli Friedman721e77d2009-12-07 00:22:08 +00005998 QualType EltTy = Context.getBaseElementType(T);
5999 if (!EltTy->isDependentType() &&
John McCall2d7d2d92010-08-16 23:42:35 +00006000 RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
6001 // Fields of incomplete type force their record to be invalid.
6002 Record->setInvalidDecl();
Eli Friedman721e77d2009-12-07 00:22:08 +00006003 InvalidDecl = true;
John McCall2d7d2d92010-08-16 23:42:35 +00006004 }
Eli Friedman721e77d2009-12-07 00:22:08 +00006005
Reid Spencer5f016e22007-07-11 17:01:13 +00006006 // C99 6.7.2.1p8: A member of a structure or union may have any type other
6007 // than a variably modified type.
Eli Friedman721e77d2009-12-07 00:22:08 +00006008 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedman1ca48132009-02-21 00:44:51 +00006009 bool SizeIsNegative;
Douglas Gregor2767ce22010-08-18 00:39:00 +00006010 llvm::APSInt Oversized;
Eli Friedman1ca48132009-02-21 00:44:51 +00006011 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
Douglas Gregor2767ce22010-08-18 00:39:00 +00006012 SizeIsNegative,
6013 Oversized);
Eli Friedman1ca48132009-02-21 00:44:51 +00006014 if (!FixedTy.isNull()) {
6015 Diag(Loc, diag::warn_illegal_constant_array_size);
6016 T = FixedTy;
6017 } else {
6018 if (SizeIsNegative)
6019 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregor2767ce22010-08-18 00:39:00 +00006020 else if (Oversized.getBoolValue())
6021 Diag(Loc, diag::err_array_too_large)
6022 << Oversized.toString(10);
Eli Friedman1ca48132009-02-21 00:44:51 +00006023 else
6024 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedman1ca48132009-02-21 00:44:51 +00006025 InvalidDecl = true;
6026 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006027 }
Mike Stump1eb44332009-09-09 15:08:12 +00006028
Anders Carlsson4681ebd2009-03-22 20:18:17 +00006029 // Fields can not have abstract class types
Eli Friedman721e77d2009-12-07 00:22:08 +00006030 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
6031 diag::err_abstract_type_in_decl,
6032 AbstractFieldType))
Anders Carlsson4681ebd2009-03-22 20:18:17 +00006033 InvalidDecl = true;
Mike Stump1eb44332009-09-09 15:08:12 +00006034
Eli Friedman1d954f62009-08-15 21:55:26 +00006035 bool ZeroWidth = false;
Douglas Gregor3cf538d2009-03-11 18:59:21 +00006036 // If this is declared as a bit-field, check the bit-field.
Eli Friedman721e77d2009-12-07 00:22:08 +00006037 if (!InvalidDecl && BitWidth &&
6038 VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
Douglas Gregor3cf538d2009-03-11 18:59:21 +00006039 InvalidDecl = true;
6040 DeleteExpr(BitWidth);
6041 BitWidth = 0;
Eli Friedman1d954f62009-08-15 21:55:26 +00006042 ZeroWidth = false;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00006043 }
Mike Stump1eb44332009-09-09 15:08:12 +00006044
John McCall4bde1e12010-06-04 08:34:12 +00006045 // Check that 'mutable' is consistent with the type of the declaration.
6046 if (!InvalidDecl && Mutable) {
6047 unsigned DiagID = 0;
6048 if (T->isReferenceType())
6049 DiagID = diag::err_mutable_reference;
6050 else if (T.isConstQualified())
6051 DiagID = diag::err_mutable_const;
6052
6053 if (DiagID) {
6054 SourceLocation ErrLoc = Loc;
6055 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
6056 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
6057 Diag(ErrLoc, DiagID);
6058 Mutable = false;
6059 InvalidDecl = true;
6060 }
6061 }
6062
John McCalla93c9342009-12-07 02:54:59 +00006063 FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, TInfo,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00006064 BitWidth, Mutable);
Chris Lattnereaaebc72009-04-25 08:06:05 +00006065 if (InvalidDecl)
6066 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00006067
Douglas Gregor3cf538d2009-03-11 18:59:21 +00006068 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
6069 Diag(Loc, diag::err_duplicate_member) << II;
6070 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
6071 NewFD->setInvalidDecl();
Douglas Gregor72de6672009-01-08 20:45:30 +00006072 }
6073
John McCall86ff3082010-02-04 22:26:26 +00006074 if (!InvalidDecl && getLangOptions().CPlusPlus) {
Eli Friedman1d954f62009-08-15 21:55:26 +00006075 CXXRecordDecl* CXXRecord = cast<CXXRecordDecl>(Record);
6076
6077 if (!T->isPODType())
6078 CXXRecord->setPOD(false);
6079 if (!ZeroWidth)
6080 CXXRecord->setEmpty(false);
6081
Ted Kremenek6217b802009-07-29 21:53:49 +00006082 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006083 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
Douglas Gregord27e50c2010-06-16 16:54:04 +00006084 if (RDecl->getDefinition()) {
6085 if (!RDecl->hasTrivialConstructor())
6086 CXXRecord->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006087 if (!RDecl->hasTrivialCopyConstructor())
Douglas Gregord27e50c2010-06-16 16:54:04 +00006088 CXXRecord->setHasTrivialCopyConstructor(false);
6089 if (!RDecl->hasTrivialCopyAssignment())
6090 CXXRecord->setHasTrivialCopyAssignment(false);
6091 if (!RDecl->hasTrivialDestructor())
6092 CXXRecord->setHasTrivialDestructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006093
Douglas Gregord27e50c2010-06-16 16:54:04 +00006094 // C++ 9.5p1: An object of a class with a non-trivial
6095 // constructor, a non-trivial copy constructor, a non-trivial
6096 // destructor, or a non-trivial copy assignment operator
6097 // cannot be a member of a union, nor can an array of such
6098 // objects.
6099 // TODO: C++0x alters this restriction significantly.
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +00006100 if (Record->isUnion() && CheckNontrivialField(NewFD))
6101 NewFD->setInvalidDecl();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006102 }
6103 }
6104 }
6105
Douglas Gregor3cf538d2009-03-11 18:59:21 +00006106 // FIXME: We need to pass in the attributes given an AST
6107 // representation, not a parser representation.
6108 if (D)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006109 // FIXME: What to pass instead of TUScope?
6110 ProcessDeclAttributes(TUScope, NewFD, *D);
Douglas Gregor3cf538d2009-03-11 18:59:21 +00006111
Fariborz Jahanianf6123ca2009-02-19 00:22:47 +00006112 if (T.isObjCGCWeak())
Fariborz Jahanianed7e9ef2009-02-18 18:14:41 +00006113 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlssonad148062008-02-16 00:29:18 +00006114
Douglas Gregor4dd55f52009-03-11 20:50:30 +00006115 NewFD->setAccess(AS);
6116
6117 // C++ [dcl.init.aggr]p1:
6118 // An aggregate is an array or a class (clause 9) with [...] no
6119 // private or protected non-static data members (clause 11).
6120 // A POD must be an aggregate.
6121 if (getLangOptions().CPlusPlus &&
6122 (AS == AS_private || AS == AS_protected)) {
6123 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
6124 CXXRecord->setAggregate(false);
6125 CXXRecord->setPOD(false);
6126 }
6127
Steve Naroff5912a352007-08-28 20:14:24 +00006128 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00006129}
6130
Argyrios Kyrtzidisdd7744d2010-08-16 17:27:08 +00006131bool Sema::CheckNontrivialField(FieldDecl *FD) {
6132 assert(FD);
6133 assert(getLangOptions().CPlusPlus && "valid check only for C++");
6134
6135 if (FD->isInvalidDecl())
6136 return true;
6137
6138 QualType EltTy = Context.getBaseElementType(FD->getType());
6139 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
6140 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
6141 if (RDecl->getDefinition()) {
6142 // We check for copy constructors before constructors
6143 // because otherwise we'll never get complaints about
6144 // copy constructors.
6145
6146 CXXSpecialMember member = CXXInvalid;
6147 if (!RDecl->hasTrivialCopyConstructor())
6148 member = CXXCopyConstructor;
6149 else if (!RDecl->hasTrivialConstructor())
6150 member = CXXConstructor;
6151 else if (!RDecl->hasTrivialCopyAssignment())
6152 member = CXXCopyAssignment;
6153 else if (!RDecl->hasTrivialDestructor())
6154 member = CXXDestructor;
6155
6156 if (member != CXXInvalid) {
6157 Diag(FD->getLocation(), diag::err_illegal_union_or_anon_struct_member)
6158 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
6159 DiagnoseNontrivial(RT, member);
6160 return true;
6161 }
6162 }
6163 }
6164
6165 return false;
6166}
6167
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006168/// DiagnoseNontrivial - Given that a class has a non-trivial
6169/// special member, figure out why.
6170void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
6171 QualType QT(T, 0U);
6172 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
6173
6174 // Check whether the member was user-declared.
6175 switch (member) {
Douglas Gregor66dd9392010-04-22 14:36:26 +00006176 case CXXInvalid:
6177 break;
6178
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00006179 case CXXConstructor:
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006180 if (RD->hasUserDeclaredConstructor()) {
6181 typedef CXXRecordDecl::ctor_iterator ctor_iter;
Sebastian Redl38fd4d02009-10-25 22:31:45 +00006182 for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
6183 const FunctionDecl *body = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00006184 ci->hasBody(body);
Anders Carlsson10dc0f82010-04-20 23:32:58 +00006185 if (!body || !cast<CXXConstructorDecl>(body)->isImplicitlyDefined()) {
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006186 SourceLocation CtorLoc = ci->getLocation();
6187 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
6188 return;
6189 }
Sebastian Redl38fd4d02009-10-25 22:31:45 +00006190 }
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006191
6192 assert(0 && "found no user-declared constructors");
6193 return;
6194 }
6195 break;
6196
6197 case CXXCopyConstructor:
6198 if (RD->hasUserDeclaredCopyConstructor()) {
6199 SourceLocation CtorLoc =
6200 RD->getCopyConstructor(Context, 0)->getLocation();
6201 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
6202 return;
6203 }
6204 break;
6205
6206 case CXXCopyAssignment:
6207 if (RD->hasUserDeclaredCopyAssignment()) {
6208 // FIXME: this should use the location of the copy
6209 // assignment, not the type.
6210 SourceLocation TyLoc = RD->getSourceRange().getBegin();
6211 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
6212 return;
6213 }
6214 break;
6215
6216 case CXXDestructor:
6217 if (RD->hasUserDeclaredDestructor()) {
Douglas Gregordb89f282010-07-01 22:47:18 +00006218 SourceLocation DtorLoc = LookupDestructor(RD)->getLocation();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006219 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
6220 return;
6221 }
6222 break;
6223 }
6224
6225 typedef CXXRecordDecl::base_class_iterator base_iter;
6226
6227 // Virtual bases and members inhibit trivial copying/construction,
6228 // but not trivial destruction.
6229 if (member != CXXDestructor) {
6230 // Check for virtual bases. vbases includes indirect virtual bases,
6231 // so we just iterate through the direct bases.
6232 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
6233 if (bi->isVirtual()) {
6234 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
6235 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
6236 return;
6237 }
6238
6239 // Check for virtual methods.
6240 typedef CXXRecordDecl::method_iterator meth_iter;
6241 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
6242 ++mi) {
6243 if (mi->isVirtual()) {
6244 SourceLocation MLoc = mi->getSourceRange().getBegin();
6245 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
6246 return;
6247 }
6248 }
6249 }
Mike Stump1eb44332009-09-09 15:08:12 +00006250
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006251 bool (CXXRecordDecl::*hasTrivial)() const;
6252 switch (member) {
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00006253 case CXXConstructor:
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006254 hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break;
6255 case CXXCopyConstructor:
6256 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
6257 case CXXCopyAssignment:
6258 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
6259 case CXXDestructor:
6260 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
6261 default:
6262 assert(0 && "unexpected special member"); return;
6263 }
6264
6265 // Check for nontrivial bases (and recurse).
6266 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
Ted Kremenek6217b802009-07-29 21:53:49 +00006267 const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
Sebastian Redl9994a342009-10-25 17:03:50 +00006268 assert(BaseRT && "Don't know how to handle dependent bases");
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006269 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
6270 if (!(BaseRecTy->*hasTrivial)()) {
6271 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
6272 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
6273 DiagnoseNontrivial(BaseRT, member);
6274 return;
6275 }
6276 }
Mike Stump1eb44332009-09-09 15:08:12 +00006277
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006278 // Check for nontrivial members (and recurse).
6279 typedef RecordDecl::field_iterator field_iter;
6280 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
6281 ++fi) {
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00006282 QualType EltTy = Context.getBaseElementType((*fi)->getType());
Ted Kremenek6217b802009-07-29 21:53:49 +00006283 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
Douglas Gregor1f2023a2009-07-22 18:25:24 +00006284 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
6285
6286 if (!(EltRD->*hasTrivial)()) {
6287 SourceLocation FLoc = (*fi)->getLocation();
6288 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
6289 DiagnoseNontrivial(EltRT, member);
6290 return;
6291 }
6292 }
6293 }
6294
6295 assert(0 && "found no explanation for non-trivial member");
6296}
6297
Mike Stump1eb44332009-09-09 15:08:12 +00006298/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanian89204a12007-10-01 16:53:59 +00006299/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006300static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00006301TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00006302 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00006303 default: assert(0 && "Unknown visitibility kind");
6304 case tok::objc_private: return ObjCIvarDecl::Private;
6305 case tok::objc_public: return ObjCIvarDecl::Public;
6306 case tok::objc_protected: return ObjCIvarDecl::Protected;
6307 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00006308 }
6309}
6310
Mike Stump1eb44332009-09-09 15:08:12 +00006311/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00006312/// in order to create an IvarDecl object for it.
Chris Lattnerb28317a2009-03-28 19:18:32 +00006313Sema::DeclPtrTy Sema::ActOnIvar(Scope *S,
Mike Stump1eb44332009-09-09 15:08:12 +00006314 SourceLocation DeclStart,
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00006315 DeclPtrTy IntfDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006316 Declarator &D, ExprTy *BitfieldWidth,
6317 tok::ObjCKeywordKind Visibility) {
Mike Stump1eb44332009-09-09 15:08:12 +00006318
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00006319 IdentifierInfo *II = D.getIdentifier();
6320 Expr *BitWidth = (Expr*)BitfieldWidth;
6321 SourceLocation Loc = DeclStart;
6322 if (II) Loc = D.getIdentifierLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00006323
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00006324 // FIXME: Unnamed fields can be handled in various different ways, for
6325 // example, unnamed unions inject all members into the struct namespace!
Mike Stump1eb44332009-09-09 15:08:12 +00006326
John McCallbf1a0282010-06-04 23:28:52 +00006327 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6328 QualType T = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00006329
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00006330 if (BitWidth) {
Steve Naroff63359c82009-02-20 17:57:11 +00006331 // 6.7.2.1p3, 6.7.2.1p4
Chris Lattner24793662009-03-05 22:45:59 +00006332 if (VerifyBitField(Loc, II, T, BitWidth)) {
Chris Lattnereaaebc72009-04-25 08:06:05 +00006333 D.setInvalidType();
Chris Lattner24793662009-03-05 22:45:59 +00006334 DeleteExpr(BitWidth);
6335 BitWidth = 0;
6336 }
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00006337 } else {
6338 // Not a bitfield.
Mike Stump1eb44332009-09-09 15:08:12 +00006339
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00006340 // validate II.
Mike Stump1eb44332009-09-09 15:08:12 +00006341
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00006342 }
Fariborz Jahanian0b7bc8e2010-04-26 22:07:03 +00006343 if (T->isReferenceType()) {
6344 Diag(Loc, diag::err_ivar_reference_type);
6345 D.setInvalidType();
6346 }
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00006347 // C99 6.7.2.1p8: A member of a structure or union may have any type other
6348 // than a variably modified type.
Fariborz Jahanian0b7bc8e2010-04-26 22:07:03 +00006349 else if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00006350 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnereaaebc72009-04-25 08:06:05 +00006351 D.setInvalidType();
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00006352 }
Mike Stump1eb44332009-09-09 15:08:12 +00006353
Ted Kremenekb8db21d2008-07-23 18:04:17 +00006354 // Get the visibility (access control) for this ivar.
Mike Stump1eb44332009-09-09 15:08:12 +00006355 ObjCIvarDecl::AccessControl ac =
Ted Kremenekb8db21d2008-07-23 18:04:17 +00006356 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
6357 : ObjCIvarDecl::None;
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00006358 // Must set ivar's DeclContext to its enclosing interface.
Daniel Dunbara19331f2010-04-02 18:29:09 +00006359 ObjCContainerDecl *EnclosingDecl = IntfDecl.getAs<ObjCContainerDecl>();
6360 ObjCContainerDecl *EnclosingContext;
Mike Stump1eb44332009-09-09 15:08:12 +00006361 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00006362 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
6363 // Case of ivar declared in an implementation. Context is that of its class.
Daniel Dunbara19331f2010-04-02 18:29:09 +00006364 EnclosingContext = IMPDecl->getClassInterface();
6365 assert(EnclosingContext && "Implementation has no class interface!");
Fariborz Jahanian0bd04592010-04-06 22:43:48 +00006366 } else {
6367 if (ObjCCategoryDecl *CDecl =
6368 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
6369 if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) {
6370 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
6371 return DeclPtrTy();
6372 }
6373 }
Daniel Dunbara19331f2010-04-02 18:29:09 +00006374 EnclosingContext = EnclosingDecl;
Fariborz Jahanian0bd04592010-04-06 22:43:48 +00006375 }
Mike Stump1eb44332009-09-09 15:08:12 +00006376
Ted Kremenekb8db21d2008-07-23 18:04:17 +00006377 // Construct the decl.
Mike Stump1eb44332009-09-09 15:08:12 +00006378 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00006379 EnclosingContext, Loc, II, T,
John McCalla93c9342009-12-07 02:54:59 +00006380 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump1eb44332009-09-09 15:08:12 +00006381
Douglas Gregor72de6672009-01-08 20:45:30 +00006382 if (II) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00006383 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall7d384dd2009-11-18 07:57:50 +00006384 ForRedeclaration);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00006385 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor72de6672009-01-08 20:45:30 +00006386 && !isa<TagDecl>(PrevDecl)) {
6387 Diag(Loc, diag::err_duplicate_member) << II;
6388 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
6389 NewID->setInvalidDecl();
6390 }
6391 }
6392
Ted Kremenekb8db21d2008-07-23 18:04:17 +00006393 // Process attributes attached to the ivar.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006394 ProcessDeclAttributes(S, NewID, D);
Mike Stump1eb44332009-09-09 15:08:12 +00006395
Chris Lattnereaaebc72009-04-25 08:06:05 +00006396 if (D.isInvalidType())
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00006397 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00006398
Douglas Gregor72de6672009-01-08 20:45:30 +00006399 if (II) {
6400 // FIXME: When interfaces are DeclContexts, we'll need to add
6401 // these to the interface.
Chris Lattnerb28317a2009-03-28 19:18:32 +00006402 S->AddDecl(DeclPtrTy::make(NewID));
Douglas Gregor72de6672009-01-08 20:45:30 +00006403 IdResolver.AddDecl(NewID);
6404 }
6405
Chris Lattnerb28317a2009-03-28 19:18:32 +00006406 return DeclPtrTy::make(NewID);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00006407}
6408
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00006409void Sema::ActOnFields(Scope* S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006410 SourceLocation RecLoc, DeclPtrTy RecDecl,
6411 DeclPtrTy *Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00006412 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00006413 AttributeList *Attr) {
Chris Lattnerb28317a2009-03-28 19:18:32 +00006414 Decl *EnclosingDecl = RecDecl.getAs<Decl>();
Steve Naroff74216642007-09-14 22:20:54 +00006415 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump1eb44332009-09-09 15:08:12 +00006416
Chris Lattner1829a6d2009-02-23 22:00:08 +00006417 // If the decl this is being inserted into is invalid, then it may be a
6418 // redeclaration or some other bogus case. Don't try to add fields to it.
6419 if (EnclosingDecl->isInvalidDecl()) {
6420 // FIXME: Deallocate fields?
6421 return;
6422 }
6423
Mike Stump1eb44332009-09-09 15:08:12 +00006424
Reid Spencer5f016e22007-07-11 17:01:13 +00006425 // Verify that all the fields are okay.
6426 unsigned NumNamedMembers = 0;
6427 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00006428
Chris Lattner1829a6d2009-02-23 22:00:08 +00006429 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00006430 for (unsigned i = 0; i != NumFields; ++i) {
Chris Lattnerb28317a2009-03-28 19:18:32 +00006431 FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>());
Mike Stump1eb44332009-09-09 15:08:12 +00006432
Reid Spencer5f016e22007-07-11 17:01:13 +00006433 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00006434 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00006435
Douglas Gregor72de6672009-01-08 20:45:30 +00006436 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00006437 // Remember all fields written by the user.
6438 RecFields.push_back(FD);
6439 }
Mike Stump1eb44332009-09-09 15:08:12 +00006440
Chris Lattner24793662009-03-05 22:45:59 +00006441 // If the field is already invalid for some reason, don't emit more
6442 // diagnostics about it.
Eli Friedman721e77d2009-12-07 00:22:08 +00006443 if (FD->isInvalidDecl()) {
6444 EnclosingDecl->setInvalidDecl();
Chris Lattner24793662009-03-05 22:45:59 +00006445 continue;
Eli Friedman721e77d2009-12-07 00:22:08 +00006446 }
Mike Stump1eb44332009-09-09 15:08:12 +00006447
Douglas Gregore7450f52009-03-24 19:52:54 +00006448 // C99 6.7.2.1p2:
6449 // A structure or union shall not contain a member with
6450 // incomplete or function type (hence, a structure shall not
6451 // contain an instance of itself, but may contain a pointer to
6452 // an instance of itself), except that the last member of a
6453 // structure with more than one named member may have incomplete
6454 // array type; such a structure (and any union containing,
6455 // possibly recursively, a member that is such a structure)
6456 // shall not be a member of a structure or an element of an
6457 // array.
Chris Lattner02c642e2007-07-31 21:33:24 +00006458 if (FDTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006459 // Field declared as a function.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006460 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006461 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00006462 FD->setInvalidDecl();
6463 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00006464 continue;
Douglas Gregore7450f52009-03-24 19:52:54 +00006465 } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 &&
6466 Record && Record->isStruct()) {
6467 // Flexible array member.
6468 if (NumNamedMembers < 1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00006469 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00006470 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00006471 FD->setInvalidDecl();
6472 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00006473 continue;
6474 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00006475 if (!FD->getType()->isDependentType() &&
6476 !Context.getBaseElementType(FD->getType())->isPODType()) {
6477 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
Fariborz Jahanian2c0a5402010-05-26 20:46:24 +00006478 << FD->getDeclName() << FD->getType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00006479 FD->setInvalidDecl();
6480 EnclosingDecl->setInvalidDecl();
6481 continue;
6482 }
6483
Reid Spencer5f016e22007-07-11 17:01:13 +00006484 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00006485 if (Record)
6486 Record->setHasFlexibleArrayMember(true);
Douglas Gregore7450f52009-03-24 19:52:54 +00006487 } else if (!FDTy->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00006488 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregore7450f52009-03-24 19:52:54 +00006489 diag::err_field_incomplete)) {
6490 // Incomplete type
6491 FD->setInvalidDecl();
6492 EnclosingDecl->setInvalidDecl();
6493 continue;
Ted Kremenek6217b802009-07-29 21:53:49 +00006494 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006495 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
6496 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00006497 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006498 Record->setHasFlexibleArrayMember(true);
6499 } else {
6500 // If this is a struct/class and this is not the last element, reject
6501 // it. Note that GCC supports variable sized arrays in the middle of
6502 // structures.
Douglas Gregore4f3e062009-03-06 23:41:27 +00006503 if (i != NumFields-1)
6504 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattner740782a2009-04-25 18:52:45 +00006505 << FD->getDeclName() << FD->getType();
Douglas Gregore4f3e062009-03-06 23:41:27 +00006506 else {
6507 // We support flexible arrays at the end of structs in
6508 // other structs as an extension.
6509 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
6510 << FD->getDeclName();
6511 if (Record)
6512 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00006513 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006514 }
6515 }
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00006516 if (Record && FDTTy->getDecl()->hasObjectMember())
6517 Record->setHasObjectMember(true);
John McCallc12c5bb2010-05-15 11:32:37 +00006518 } else if (FDTy->isObjCObjectType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00006519 /// A field cannot be an Objective-c object
Steve Naroffccef3712009-02-20 22:59:16 +00006520 Diag(FD->getLocation(), diag::err_statically_allocated_object);
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00006521 FD->setInvalidDecl();
6522 EnclosingDecl->setInvalidDecl();
6523 continue;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006524 } else if (getLangOptions().ObjC1 &&
6525 getLangOptions().getGCMode() != LangOptions::NonGC &&
6526 Record &&
6527 (FD->getType()->isObjCObjectPointerType() ||
6528 FD->getType().isObjCGCStrong()))
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00006529 Record->setHasObjectMember(true);
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00006530 else if (Context.getAsArrayType(FD->getType())) {
6531 QualType BaseType = Context.getBaseElementType(FD->getType());
6532 if (Record && BaseType->isRecordType() &&
6533 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
6534 Record->setHasObjectMember(true);
6535 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006536 // Keep track of the number of named members.
Douglas Gregor72de6672009-01-08 20:45:30 +00006537 if (FD->getIdentifier())
Reid Spencer5f016e22007-07-11 17:01:13 +00006538 ++NumNamedMembers;
Reid Spencer5f016e22007-07-11 17:01:13 +00006539 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00006540
Reid Spencer5f016e22007-07-11 17:01:13 +00006541 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00006542 if (Record) {
Douglas Gregor838db382010-02-11 01:19:42 +00006543 Record->completeDefinition();
Chris Lattnere1e79852008-02-06 00:51:33 +00006544 } else {
Jay Foadbeaaccd2009-05-21 09:52:38 +00006545 ObjCIvarDecl **ClsFields =
6546 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00006547 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattner38af2de2009-02-20 21:35:13 +00006548 ID->setLocEnd(RBrac);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00006549 // Add ivar's to class's DeclContext.
6550 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
6551 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006552 ID->addDecl(ClsFields[i]);
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00006553 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00006554 // Must enforce the rule that ivars in the base classes may not be
6555 // duplicates.
Fariborz Jahanianf914b972010-02-23 23:41:11 +00006556 if (ID->getSuperClass())
6557 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump1eb44332009-09-09 15:08:12 +00006558 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattner1829a6d2009-02-23 22:00:08 +00006559 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00006560 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian496b5a82009-06-05 18:16:35 +00006561 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
6562 // Ivar declared in @implementation never belongs to the implementation.
6563 // Only it is in implementation's lexical context.
Douglas Gregor8f36aba2009-04-23 03:23:08 +00006564 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00006565 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian83c481a2010-02-22 23:04:20 +00006566 } else if (ObjCCategoryDecl *CDecl =
6567 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian0bd04592010-04-06 22:43:48 +00006568 // case of ivars in class extension; all other cases have been
6569 // reported as errors elsewhere.
6570 // FIXME. Class extension does not have a LocEnd field.
6571 // CDecl->setLocEnd(RBrac);
6572 // Add ivar's to class extension's DeclContext.
6573 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
6574 ClsFields[i]->setLexicalDeclContext(CDecl);
6575 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian83c481a2010-02-22 23:04:20 +00006576 }
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00006577 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00006578 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00006579
6580 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006581 ProcessDeclAttributeList(S, Record, Attr);
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006582
6583 // If there's a #pragma GCC visibility in scope, and this isn't a subclass,
6584 // set the visibility of this record.
6585 if (Record && !Record->getDeclContext()->isRecord())
6586 AddPushedVisibilityAttribute(Record);
Reid Spencer5f016e22007-07-11 17:01:13 +00006587}
6588
Douglas Gregor677e4fe2010-02-01 23:36:03 +00006589/// \brief Determine whether the given integral value is representable within
6590/// the given type T.
6591static bool isRepresentableIntegerValue(ASTContext &Context,
6592 llvm::APSInt &Value,
6593 QualType T) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00006594 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregoraf68d4e2010-04-15 15:53:31 +00006595 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor677e4fe2010-02-01 23:36:03 +00006596
6597 if (Value.isUnsigned() || Value.isNonNegative())
6598 return Value.getActiveBits() < BitWidth;
6599
6600 return Value.getMinSignedBits() <= BitWidth;
6601}
6602
6603// \brief Given an integral type, return the next larger integral type
6604// (or a NULL type of no such type exists).
6605static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
6606 // FIXME: Int128/UInt128 support, which also needs to be introduced into
6607 // enum checking below.
Douglas Gregor9d3347a2010-06-16 00:35:25 +00006608 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor677e4fe2010-02-01 23:36:03 +00006609 const unsigned NumTypes = 4;
6610 QualType SignedIntegralTypes[NumTypes] = {
6611 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
6612 };
6613 QualType UnsignedIntegralTypes[NumTypes] = {
6614 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
6615 Context.UnsignedLongLongTy
6616 };
6617
6618 unsigned BitWidth = Context.getTypeSize(T);
6619 QualType *Types = T->isSignedIntegerType()? SignedIntegralTypes
6620 : UnsignedIntegralTypes;
6621 for (unsigned I = 0; I != NumTypes; ++I)
6622 if (Context.getTypeSize(Types[I]) > BitWidth)
6623 return Types[I];
6624
6625 return QualType();
6626}
6627
Douglas Gregor879fd492009-03-17 19:05:46 +00006628EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
6629 EnumConstantDecl *LastEnumConst,
6630 SourceLocation IdLoc,
6631 IdentifierInfo *Id,
6632 ExprArg val) {
6633 Expr *Val = (Expr *)val.get();
6634
Douglas Gregor677e4fe2010-02-01 23:36:03 +00006635 unsigned IntWidth = Context.Target.getIntWidth();
6636 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor879fd492009-03-17 19:05:46 +00006637 QualType EltTy;
Douglas Gregor4912c342009-11-06 00:03:12 +00006638 if (Val) {
Douglas Gregor9b9edd62010-03-02 17:53:14 +00006639 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregor4912c342009-11-06 00:03:12 +00006640 EltTy = Context.DependentTy;
6641 else {
Douglas Gregor4912c342009-11-06 00:03:12 +00006642 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
6643 SourceLocation ExpLoc;
Douglas Gregor9b9edd62010-03-02 17:53:14 +00006644 if (!Val->isValueDependent() &&
6645 VerifyIntegerConstantExpression(Val, &EnumVal)) {
Douglas Gregor4912c342009-11-06 00:03:12 +00006646 Val = 0;
Douglas Gregor677e4fe2010-02-01 23:36:03 +00006647 } else {
6648 if (!getLangOptions().CPlusPlus) {
6649 // C99 6.7.2.2p2:
6650 // The expression that defines the value of an enumeration constant
6651 // shall be an integer constant expression that has a value
6652 // representable as an int.
6653
6654 // Complain if the value is not representable in an int.
6655 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
6656 Diag(IdLoc, diag::ext_enum_value_not_int)
6657 << EnumVal.toString(10) << Val->getSourceRange()
Douglas Gregor19c15252010-02-17 22:40:11 +00006658 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
Douglas Gregor677e4fe2010-02-01 23:36:03 +00006659 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
6660 // Force the type of the expression to 'int'.
6661 ImpCastExprToType(Val, Context.IntTy, CastExpr::CK_IntegralCast);
6662
6663 if (Val != val.get()) {
6664 val.release();
6665 val = Val;
6666 }
6667 }
6668 }
6669
6670 // C++0x [dcl.enum]p5:
6671 // If the underlying type is not fixed, the type of each enumerator
6672 // is the type of its initializing value:
6673 // - If an initializer is specified for an enumerator, the
6674 // initializing value has the same type as the expression.
Douglas Gregor4912c342009-11-06 00:03:12 +00006675 EltTy = Val->getType();
6676 }
Douglas Gregor879fd492009-03-17 19:05:46 +00006677 }
6678 }
Mike Stump1eb44332009-09-09 15:08:12 +00006679
Douglas Gregor879fd492009-03-17 19:05:46 +00006680 if (!Val) {
Eli Friedmaned0716b2009-12-11 01:34:50 +00006681 if (Enum->isDependentType())
6682 EltTy = Context.DependentTy;
Douglas Gregor677e4fe2010-02-01 23:36:03 +00006683 else if (!LastEnumConst) {
6684 // C++0x [dcl.enum]p5:
6685 // If the underlying type is not fixed, the type of each enumerator
6686 // is the type of its initializing value:
6687 // - If no initializer is specified for the first enumerator, the
6688 // initializing value has an unspecified integral type.
6689 //
6690 // GCC uses 'int' for its unspecified integral type, as does
6691 // C99 6.7.2.2p3.
6692 EltTy = Context.IntTy;
6693 } else {
Douglas Gregor879fd492009-03-17 19:05:46 +00006694 // Assign the last value + 1.
6695 EnumVal = LastEnumConst->getInitVal();
6696 ++EnumVal;
Douglas Gregor677e4fe2010-02-01 23:36:03 +00006697 EltTy = LastEnumConst->getType();
Douglas Gregor879fd492009-03-17 19:05:46 +00006698
6699 // Check for overflow on increment.
Douglas Gregor677e4fe2010-02-01 23:36:03 +00006700 if (EnumVal < LastEnumConst->getInitVal()) {
6701 // C++0x [dcl.enum]p5:
6702 // If the underlying type is not fixed, the type of each enumerator
6703 // is the type of its initializing value:
6704 //
6705 // - Otherwise the type of the initializing value is the same as
6706 // the type of the initializing value of the preceding enumerator
6707 // unless the incremented value is not representable in that type,
6708 // in which case the type is an unspecified integral type
6709 // sufficient to contain the incremented value. If no such type
6710 // exists, the program is ill-formed.
6711 QualType T = getNextLargerIntegralType(Context, EltTy);
6712 if (T.isNull()) {
6713 // There is no integral type larger enough to represent this
6714 // value. Complain, then allow the value to wrap around.
6715 EnumVal = LastEnumConst->getInitVal();
6716 EnumVal.zext(EnumVal.getBitWidth() * 2);
6717 Diag(IdLoc, diag::warn_enumerator_too_large)
6718 << EnumVal.toString(10);
6719 } else {
6720 EltTy = T;
6721 }
6722
6723 // Retrieve the last enumerator's value, extent that type to the
6724 // type that is supposed to be large enough to represent the incremented
6725 // value, then increment.
6726 EnumVal = LastEnumConst->getInitVal();
6727 EnumVal.setIsSigned(EltTy->isSignedIntegerType());
Douglas Gregoraf68d4e2010-04-15 15:53:31 +00006728 EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor677e4fe2010-02-01 23:36:03 +00006729 ++EnumVal;
6730
6731 // If we're not in C++, diagnose the overflow of enumerator values,
6732 // which in C99 means that the enumerator value is not representable in
6733 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
6734 // permits enumerator values that are representable in some larger
6735 // integral type.
6736 if (!getLangOptions().CPlusPlus && !T.isNull())
6737 Diag(IdLoc, diag::warn_enum_value_overflow);
6738 } else if (!getLangOptions().CPlusPlus &&
6739 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
6740 // Enforce C99 6.7.2.2p2 even when we compute the next value.
6741 Diag(IdLoc, diag::ext_enum_value_not_int)
6742 << EnumVal.toString(10) << 1;
6743 }
Douglas Gregor879fd492009-03-17 19:05:46 +00006744 }
6745 }
Mike Stump1eb44332009-09-09 15:08:12 +00006746
Douglas Gregor9b9edd62010-03-02 17:53:14 +00006747 if (!EltTy->isDependentType()) {
Douglas Gregor677e4fe2010-02-01 23:36:03 +00006748 // Make the enumerator value match the signedness and size of the
6749 // enumerator's type.
Douglas Gregoraf68d4e2010-04-15 15:53:31 +00006750 EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor677e4fe2010-02-01 23:36:03 +00006751 EnumVal.setIsSigned(EltTy->isSignedIntegerType());
6752 }
Douglas Gregor4912c342009-11-06 00:03:12 +00006753
Douglas Gregor879fd492009-03-17 19:05:46 +00006754 val.release();
6755 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump1eb44332009-09-09 15:08:12 +00006756 Val, EnumVal);
Douglas Gregor879fd492009-03-17 19:05:46 +00006757}
6758
6759
Chris Lattnerb28317a2009-03-28 19:18:32 +00006760Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl,
6761 DeclPtrTy lastEnumConst,
6762 SourceLocation IdLoc,
6763 IdentifierInfo *Id,
6764 SourceLocation EqualLoc, ExprTy *val) {
6765 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00006766 EnumConstantDecl *LastEnumConst =
Chris Lattnerb28317a2009-03-28 19:18:32 +00006767 cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00006768 Expr *Val = static_cast<Expr*>(val);
6769
Chris Lattner31e05722007-08-26 06:24:45 +00006770 // The scope passed in may not be a decl scope. Zip up the scope tree until
6771 // we find one that is.
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00006772 S = getNonFieldDeclScope(S);
Mike Stump1eb44332009-09-09 15:08:12 +00006773
Reid Spencer5f016e22007-07-11 17:01:13 +00006774 // Verify that there isn't already something declared with this name in this
6775 // scope.
Douglas Gregorc83c6872010-04-15 22:33:43 +00006776 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregore39fe722010-01-19 06:06:57 +00006777 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +00006778 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00006779 // Maybe we will complain about the shadowed template parameter.
6780 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
6781 // Just pretend that we didn't see the previous declaration.
6782 PrevDecl = 0;
6783 }
6784
6785 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00006786 // When in C++, we may get a TagDecl with the same name; in this case the
6787 // enum constant will 'hide' the tag.
6788 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
6789 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00006790 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006791 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00006792 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00006793 else
Chris Lattner3c73c412008-11-19 08:23:25 +00006794 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00006795 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00006796 return DeclPtrTy();
Reid Spencer5f016e22007-07-11 17:01:13 +00006797 }
6798 }
6799
Douglas Gregor879fd492009-03-17 19:05:46 +00006800 EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst,
6801 IdLoc, Id, Owned(Val));
Chris Lattner421a23d2007-08-27 21:16:18 +00006802
Reid Spencer5f016e22007-07-11 17:01:13 +00006803 // Register this decl in the current scope stack.
John McCall92f88312010-01-23 00:46:32 +00006804 if (New) {
6805 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor879fd492009-03-17 19:05:46 +00006806 PushOnScopeChains(New, S);
John McCall92f88312010-01-23 00:46:32 +00006807 }
Douglas Gregor45579f52008-12-17 02:04:30 +00006808
Chris Lattnerb28317a2009-03-28 19:18:32 +00006809 return DeclPtrTy::make(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00006810}
6811
Mike Stumpc6e35aa2009-05-16 07:06:02 +00006812void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
6813 SourceLocation RBraceLoc, DeclPtrTy EnumDeclX,
Edward O'Callaghanfee13812009-08-08 14:36:57 +00006814 DeclPtrTy *Elements, unsigned NumElements,
6815 Scope *S, AttributeList *Attr) {
Chris Lattnerb28317a2009-03-28 19:18:32 +00006816 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>());
Douglas Gregor074149e2009-01-05 19:45:36 +00006817 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanfee13812009-08-08 14:36:57 +00006818
6819 if (Attr)
6820 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump1eb44332009-09-09 15:08:12 +00006821
Eli Friedmaned0716b2009-12-11 01:34:50 +00006822 if (Enum->isDependentType()) {
6823 for (unsigned i = 0; i != NumElements; ++i) {
6824 EnumConstantDecl *ECD =
6825 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
6826 if (!ECD) continue;
6827
6828 ECD->setType(EnumType);
6829 }
6830
John McCall1b5a6182010-05-06 08:49:23 +00006831 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmaned0716b2009-12-11 01:34:50 +00006832 return;
6833 }
6834
Chris Lattnere37f0be2007-08-28 05:10:31 +00006835 // TODO: If the result value doesn't fit in an int, it must be a long or long
6836 // long value. ISO C does not support this, but GCC does as an extension,
6837 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00006838 unsigned IntWidth = Context.Target.getIntWidth();
Edward O'Callaghanfee13812009-08-08 14:36:57 +00006839 unsigned CharWidth = Context.Target.getCharWidth();
6840 unsigned ShortWidth = Context.Target.getShortWidth();
Mike Stump1eb44332009-09-09 15:08:12 +00006841
Chris Lattnerac609682007-08-28 06:15:15 +00006842 // Verify that all the values are okay, compute the size of the values, and
6843 // reverse the list.
6844 unsigned NumNegativeBits = 0;
6845 unsigned NumPositiveBits = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006846
Chris Lattnerac609682007-08-28 06:15:15 +00006847 // Keep track of whether all elements have type int.
6848 bool AllElementsInt = true;
Mike Stump1eb44332009-09-09 15:08:12 +00006849
Reid Spencer5f016e22007-07-11 17:01:13 +00006850 for (unsigned i = 0; i != NumElements; ++i) {
6851 EnumConstantDecl *ECD =
Chris Lattnerb28317a2009-03-28 19:18:32 +00006852 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00006853 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump1eb44332009-09-09 15:08:12 +00006854
Chris Lattner211a30e2007-08-28 05:27:00 +00006855 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump1eb44332009-09-09 15:08:12 +00006856
Chris Lattnerac609682007-08-28 06:15:15 +00006857 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00006858 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00006859 NumPositiveBits = std::max(NumPositiveBits,
6860 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00006861 else
Chris Lattner21dd8212008-01-14 21:47:29 +00006862 NumNegativeBits = std::max(NumNegativeBits,
6863 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00006864
Chris Lattnerac609682007-08-28 06:15:15 +00006865 // Keep track of whether every enum element has type int (very commmon).
6866 if (AllElementsInt)
Mike Stump1eb44332009-09-09 15:08:12 +00006867 AllElementsInt = ECD->getType() == Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006868 }
Mike Stump1eb44332009-09-09 15:08:12 +00006869
Chris Lattnerac609682007-08-28 06:15:15 +00006870 // Figure out the type that should be used for this enum.
Edward O'Callaghanfee13812009-08-08 14:36:57 +00006871 // FIXME: Support -fshort-enums.
Chris Lattnerac609682007-08-28 06:15:15 +00006872 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00006873 unsigned BestWidth;
Edward O'Callaghanfee13812009-08-08 14:36:57 +00006874
John McCall842aef82009-12-09 09:09:27 +00006875 // C++0x N3000 [conv.prom]p3:
6876 // An rvalue of an unscoped enumeration type whose underlying
6877 // type is not fixed can be converted to an rvalue of the first
6878 // of the following types that can represent all the values of
6879 // the enumeration: int, unsigned int, long int, unsigned long
6880 // int, long long int, or unsigned long long int.
6881 // C99 6.4.4.3p2:
6882 // An identifier declared as an enumeration constant has type int.
6883 // The C99 rule is modified by a gcc extension
6884 QualType BestPromotionType;
6885
Edward O'Callaghanfee13812009-08-08 14:36:57 +00006886 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
6887
Chris Lattnerac609682007-08-28 06:15:15 +00006888 if (NumNegativeBits) {
Mike Stump1eb44332009-09-09 15:08:12 +00006889 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerac609682007-08-28 06:15:15 +00006890 // int/long/longlong) that fits.
Edward O'Callaghanfee13812009-08-08 14:36:57 +00006891 // If it's packed, check also if it fits a char or a short.
6892 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall842aef82009-12-09 09:09:27 +00006893 BestType = Context.SignedCharTy;
6894 BestWidth = CharWidth;
Mike Stump1eb44332009-09-09 15:08:12 +00006895 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanfee13812009-08-08 14:36:57 +00006896 NumPositiveBits < ShortWidth) {
John McCall842aef82009-12-09 09:09:27 +00006897 BestType = Context.ShortTy;
6898 BestWidth = ShortWidth;
6899 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00006900 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00006901 BestWidth = IntWidth;
6902 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00006903 BestWidth = Context.Target.getLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +00006904
John McCall842aef82009-12-09 09:09:27 +00006905 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00006906 BestType = Context.LongTy;
John McCall842aef82009-12-09 09:09:27 +00006907 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00006908 BestWidth = Context.Target.getLongLongWidth();
Mike Stump1eb44332009-09-09 15:08:12 +00006909
Chris Lattnerb7f6e082007-08-29 17:31:48 +00006910 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00006911 Diag(Enum->getLocation(), diag::warn_enum_too_large);
6912 BestType = Context.LongLongTy;
6913 }
6914 }
John McCall842aef82009-12-09 09:09:27 +00006915 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerac609682007-08-28 06:15:15 +00006916 } else {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00006917 // If there is no negative value, figure out the smallest type that fits
6918 // all of the enumerator values.
Edward O'Callaghanfee13812009-08-08 14:36:57 +00006919 // If it's packed, check also if it fits a char or a short.
6920 if (Packed && NumPositiveBits <= CharWidth) {
John McCall842aef82009-12-09 09:09:27 +00006921 BestType = Context.UnsignedCharTy;
6922 BestPromotionType = Context.IntTy;
6923 BestWidth = CharWidth;
Edward O'Callaghanfee13812009-08-08 14:36:57 +00006924 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall842aef82009-12-09 09:09:27 +00006925 BestType = Context.UnsignedShortTy;
6926 BestPromotionType = Context.IntTy;
6927 BestWidth = ShortWidth;
6928 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00006929 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00006930 BestWidth = IntWidth;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00006931 BestPromotionType
6932 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6933 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00006934 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00006935 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00006936 BestType = Context.UnsignedLongTy;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00006937 BestPromotionType
6938 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6939 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00006940 } else {
6941 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00006942 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00006943 "How could an initializer get larger than ULL?");
6944 BestType = Context.UnsignedLongLongTy;
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00006945 BestPromotionType
6946 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6947 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerac609682007-08-28 06:15:15 +00006948 }
6949 }
Mike Stump1eb44332009-09-09 15:08:12 +00006950
Chris Lattnerb7f6e082007-08-29 17:31:48 +00006951 // Loop over all of the enumerator constants, changing their types to match
6952 // the type of the enum if needed.
6953 for (unsigned i = 0; i != NumElements; ++i) {
6954 EnumConstantDecl *ECD =
Chris Lattnerb28317a2009-03-28 19:18:32 +00006955 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
Chris Lattnerb7f6e082007-08-29 17:31:48 +00006956 if (!ECD) continue; // Already issued a diagnostic.
6957
6958 // Standard C says the enumerators have int type, but we allow, as an
6959 // extension, the enumerators to be larger than int size. If each
6960 // enumerator value fits in an int, type it as an int, otherwise type it the
6961 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
6962 // that X has type 'int', not 'unsigned'.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00006963
6964 // Determine whether the value fits into an int.
6965 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00006966
6967 // If it fits into an integer type, force it. Otherwise force it to match
6968 // the enum decl type.
6969 QualType NewTy;
6970 unsigned NewWidth;
6971 bool NewSign;
Douglas Gregor677e4fe2010-02-01 23:36:03 +00006972 if (!getLangOptions().CPlusPlus &&
6973 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00006974 NewTy = Context.IntTy;
6975 NewWidth = IntWidth;
6976 NewSign = true;
6977 } else if (ECD->getType() == BestType) {
6978 // Already the right type!
Douglas Gregorc9467cf2008-12-12 02:00:36 +00006979 if (getLangOptions().CPlusPlus)
6980 // C++ [dcl.enum]p4: Following the closing brace of an
6981 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +00006982 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +00006983 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00006984 continue;
6985 } else {
6986 NewTy = BestType;
6987 NewWidth = BestWidth;
6988 NewSign = BestType->isSignedIntegerType();
6989 }
6990
6991 // Adjust the APSInt value.
6992 InitVal.extOrTrunc(NewWidth);
6993 InitVal.setIsSigned(NewSign);
6994 ECD->setInitVal(InitVal);
Mike Stump1eb44332009-09-09 15:08:12 +00006995
Chris Lattnerb7f6e082007-08-29 17:31:48 +00006996 // Adjust the Expr initializer and type.
Chris Lattner13fd4162009-01-15 19:19:42 +00006997 if (ECD->getInitExpr())
John McCallf871d0c2010-08-07 06:22:56 +00006998 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
6999 CastExpr::CK_IntegralCast,
7000 ECD->getInitExpr(),
7001 /*base paths*/ 0,
7002 ImplicitCastExpr::RValue));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00007003 if (getLangOptions().CPlusPlus)
7004 // C++ [dcl.enum]p4: Following the closing brace of an
7005 // enum-specifier, each enumerator has the type of its
Mike Stump1eb44332009-09-09 15:08:12 +00007006 // enumeration.
Douglas Gregorc9467cf2008-12-12 02:00:36 +00007007 ECD->setType(EnumType);
7008 else
7009 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00007010 }
Mike Stump1eb44332009-09-09 15:08:12 +00007011
John McCall1b5a6182010-05-06 08:49:23 +00007012 Enum->completeDefinition(BestType, BestPromotionType,
7013 NumPositiveBits, NumNegativeBits);
Reid Spencer5f016e22007-07-11 17:01:13 +00007014}
7015
Chris Lattnerb28317a2009-03-28 19:18:32 +00007016Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
7017 ExprArg expr) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00007018 StringLiteral *AsmString = cast<StringLiteral>(expr.takeAs<Expr>());
Sebastian Redl798d1192008-12-13 16:23:55 +00007019
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +00007020 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
7021 Loc, AsmString);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00007022 CurContext->addDecl(New);
Douglas Gregor4fe0c8e2009-05-30 00:08:05 +00007023 return DeclPtrTy::make(New);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00007024}
Eli Friedmanc49f19b2009-06-05 02:44:36 +00007025
7026void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
7027 SourceLocation PragmaLoc,
7028 SourceLocation NameLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00007029 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedmanc49f19b2009-06-05 02:44:36 +00007030
Eli Friedmanc49f19b2009-06-05 02:44:36 +00007031 if (PrevDecl) {
Sean Huntcf807c42010-08-18 23:23:40 +00007032 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
Ryan Flynne25ff832009-07-30 03:15:39 +00007033 } else {
7034 (void)WeakUndeclaredIdentifiers.insert(
7035 std::pair<IdentifierInfo*,WeakInfo>
7036 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedmanc49f19b2009-06-05 02:44:36 +00007037 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +00007038}
7039
7040void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
7041 IdentifierInfo* AliasName,
7042 SourceLocation PragmaLoc,
7043 SourceLocation NameLoc,
7044 SourceLocation AliasNameLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00007045 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
7046 LookupOrdinaryName);
Ryan Flynne25ff832009-07-30 03:15:39 +00007047 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedmanc49f19b2009-06-05 02:44:36 +00007048
Eli Friedmanc49f19b2009-06-05 02:44:36 +00007049 if (PrevDecl) {
Ryan Flynne25ff832009-07-30 03:15:39 +00007050 if (!PrevDecl->hasAttr<AliasAttr>())
7051 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynn7b1fdbd2009-07-31 02:52:19 +00007052 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynne25ff832009-07-30 03:15:39 +00007053 } else {
7054 (void)WeakUndeclaredIdentifiers.insert(
7055 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedmanc49f19b2009-06-05 02:44:36 +00007056 }
Eli Friedmanc49f19b2009-06-05 02:44:36 +00007057}