blob: dab4bf7fbe36a9176f1af429c3a8bbeb189a49aa [file] [log] [blame]
Chris Lattner697e5d62006-11-09 06:32:27 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner697e5d62006-11-09 06:32:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
John McCallcc14d1f2010-08-24 08:50:51 +000017#include "clang/Sema/CXXFieldCollector.h"
18#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
Douglas Gregor844cb502011-03-01 18:12:44 +000020#include "TypeLocBuilder.h"
Anders Carlsson7a241ba2008-07-03 04:20:39 +000021#include "clang/AST/APValue.h"
Chris Lattner622c1932008-02-06 00:51:33 +000022#include "clang/AST/ASTConsumer.h"
Chris Lattner5c5fbcc2006-12-03 08:41:30 +000023#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000024#include "clang/AST/CXXInheritance.h"
John McCall28a0cf72010-08-25 07:42:41 +000025#include "clang/AST/DeclCXX.h"
John McCallde6836a2010-08-24 07:21:54 +000026#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000027#include "clang/AST/DeclTemplate.h"
Chris Lattner2c6fcf52008-06-26 18:38:35 +000028#include "clang/AST/ExprCXX.h"
Sebastian Redla7b98a72009-04-26 20:35:05 +000029#include "clang/AST/StmtCXX.h"
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +000030#include "clang/AST/CharUnits.h"
John McCall8b0666c2010-08-20 18:27:03 +000031#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/ParsedTemplate.h"
Douglas Gregor15e56022009-10-13 23:27:22 +000033#include "clang/Parse/ParseDiagnostic.h"
Anders Carlssond624e162009-08-26 23:45:07 +000034#include "clang/Basic/PartialDiagnostic.h"
Steve Naroffe101f952008-01-30 23:46:05 +000035#include "clang/Basic/SourceManager.h"
Anders Carlssond624e162009-08-26 23:45:07 +000036#include "clang/Basic/TargetInfo.h"
Steve Naroffe101f952008-01-30 23:46:05 +000037// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattner622c1932008-02-06 00:51:33 +000038#include "clang/Lex/Preprocessor.h"
Mike Stump11289f42009-09-09 15:08:12 +000039#include "clang/Lex/HeaderSearch.h"
John McCall0e21fcc2009-12-24 09:58:38 +000040#include "llvm/ADT/Triple.h"
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000041#include <algorithm>
Douglas Gregor56fbc372009-09-28 21:14:19 +000042#include <cstring>
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000043#include <functional>
Chris Lattner697e5d62006-11-09 06:32:27 +000044using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000045using namespace sema;
Chris Lattner697e5d62006-11-09 06:32:27 +000046
John McCall48871652010-08-21 09:40:31 +000047Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr) {
48 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
Chris Lattner5bbb3c82009-03-29 16:50:03 +000049}
50
Douglas Gregorec6e1892009-02-04 19:16:12 +000051/// \brief If the identifier refers to a type name within this scope,
52/// return the declaration of that type.
53///
54/// This routine performs ordinary name lookup of the identifier II
55/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor9817f4a2009-02-09 15:09:02 +000056/// determine whether the name refers to a type. If so, returns an
57/// opaque pointer (actually a QualType) corresponding to that
58/// type. Otherwise, returns NULL.
Douglas Gregorec6e1892009-02-04 19:16:12 +000059///
60/// If name lookup results in an ambiguity, this routine will complain
61/// and then return NULL.
John McCallba7bf592010-08-24 05:47:05 +000062ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
63 Scope *S, CXXScopeSpec *SS,
Fariborz Jahanian87967422011-02-08 18:05:59 +000064 bool isClassName, bool HasTrailingDot,
Douglas Gregor844cb502011-03-01 18:12:44 +000065 ParsedType ObjectTypePtr,
66 bool WantNontrivialTypeSourceInfo) {
Douglas Gregora25d65d2009-11-20 22:03:38 +000067 // Determine where we will perform name lookup.
68 DeclContext *LookupCtx = 0;
69 if (ObjectTypePtr) {
John McCallba7bf592010-08-24 05:47:05 +000070 QualType ObjectType = ObjectTypePtr.get();
Douglas Gregora25d65d2009-11-20 22:03:38 +000071 if (ObjectType->isRecordType())
72 LookupCtx = computeDeclContext(ObjectType);
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +000073 } else if (SS && SS->isNotEmpty()) {
Douglas Gregora25d65d2009-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)
John McCallba7bf592010-08-24 05:47:05 +000088 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +000089
John McCallc392f372010-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 Gregor844cb502011-03-01 18:12:44 +000092 if (WantNontrivialTypeSourceInfo)
93 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
94
95 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
John McCallba7bf592010-08-24 05:47:05 +000096 QualType T =
Douglas Gregor844cb502011-03-01 18:12:44 +000097 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000098 II, NameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000099
100 return ParsedType::make(T);
Douglas Gregora25d65d2009-11-20 22:03:38 +0000101 }
102
John McCallba7bf592010-08-24 05:47:05 +0000103 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000104 }
105
John McCall0b66eb32010-05-01 00:40:08 +0000106 if (!LookupCtx->isDependentContext() &&
107 RequireCompleteDeclContext(*SS, LookupCtx))
John McCallba7bf592010-08-24 05:47:05 +0000108 return ParsedType();
Douglas Gregor5e0962f2009-08-26 18:27:52 +0000109 }
Eli Friedman9025ec22009-12-21 01:42:38 +0000110
111 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
112 // lookup for class-names.
113 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
114 LookupOrdinaryName;
115 LookupResult Result(*this, &II, NameLoc, Kind);
Douglas Gregora25d65d2009-11-20 22:03:38 +0000116 if (LookupCtx) {
117 // Perform "qualified" name lookup into the declaration context we
118 // computed, which is either the type of the base of a member access
119 // expression or the declaration context associated with a prior
120 // nested-name-specifier.
121 LookupQualifiedName(Result, LookupCtx);
Douglas Gregorc9f9b862009-05-11 19:58:34 +0000122
Douglas Gregora25d65d2009-11-20 22:03:38 +0000123 if (ObjectTypePtr && Result.empty()) {
124 // C++ [basic.lookup.classref]p3:
125 // If the unqualified-id is ~type-name, the type-name is looked up
126 // in the context of the entire postfix-expression. If the type T of
127 // the object expression is of a class type C, the type-name is also
128 // looked up in the scope of class C. At least one of the lookups shall
129 // find a name that refers to (possibly cv-qualified) T.
130 LookupName(Result, S);
131 }
132 } else {
133 // Perform unqualified name lookup.
134 LookupName(Result, S);
135 }
136
Chris Lattnera3778332009-02-16 22:07:16 +0000137 NamedDecl *IIDecl = 0;
John McCall27b18f82009-11-17 02:14:36 +0000138 switch (Result.getResultKind()) {
Chris Lattnera3778332009-02-16 22:07:16 +0000139 case LookupResult::NotFound:
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000140 case LookupResult::NotFoundInCurrentInstantiation:
Chris Lattnera3778332009-02-16 22:07:16 +0000141 case LookupResult::FoundOverloaded:
John McCalle61f2ba2009-11-18 02:36:19 +0000142 case LookupResult::FoundUnresolvedValue:
John McCall58cc69d2010-01-27 01:50:18 +0000143 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000144 return ParsedType();
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000145
Chris Lattnere40853a2009-10-25 22:09:09 +0000146 case LookupResult::Ambiguous:
John McCall6538c932009-10-10 05:48:19 +0000147 // Recover from type-hiding ambiguities by hiding the type. We'll
148 // do the lookup again when looking for an object, and we can
149 // diagnose the error then. If we don't do this, then the error
150 // about hiding the type will be immediately followed by an error
151 // that only makes sense if the identifier was treated like a type.
John McCall27b18f82009-11-17 02:14:36 +0000152 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
153 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000154 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000155 }
John McCall6538c932009-10-10 05:48:19 +0000156
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000157 // Look to see if we have a type anywhere in the list of results.
158 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
159 Res != ResEnd; ++Res) {
160 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
Mike Stump11289f42009-09-09 15:08:12 +0000161 if (!IIDecl ||
162 (*Res)->getLocation().getRawEncoding() <
Douglas Gregor712a3512009-04-13 15:14:38 +0000163 IIDecl->getLocation().getRawEncoding())
164 IIDecl = *Res;
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000165 }
166 }
167
168 if (!IIDecl) {
169 // None of the entities we found is a type, so there is no way
170 // to even assume that the result is a type. In this case, don't
171 // complain about the ambiguity. The parser will either try to
172 // perform this lookup again (e.g., as an object name), which
173 // will produce the ambiguity, or will complain that it expected
174 // a type name.
John McCall27b18f82009-11-17 02:14:36 +0000175 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000176 return ParsedType();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000177 }
178
179 // We found a type within the ambiguous lookup; diagnose the
180 // ambiguity and then return that type. This might be the right
181 // answer, or it might not be, but it suppresses any attempt to
182 // perform the name lookup again.
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000183 break;
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000184
Chris Lattnera3778332009-02-16 22:07:16 +0000185 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +0000186 IIDecl = Result.getFoundDecl();
Chris Lattnera3778332009-02-16 22:07:16 +0000187 break;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000188 }
189
Chris Lattner17e15f12009-10-25 17:16:46 +0000190 assert(IIDecl && "Didn't find decl");
John McCall28a6aea2009-11-04 02:18:39 +0000191
Chris Lattner17e15f12009-10-25 17:16:46 +0000192 QualType T;
193 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
John McCall28a6aea2009-11-04 02:18:39 +0000194 DiagnoseUseOfDecl(IIDecl, NameLoc);
John McCall27b18f82009-11-17 02:14:36 +0000195
Chris Lattner17e15f12009-10-25 17:16:46 +0000196 if (T.isNull())
197 T = Context.getTypeDeclType(TD);
198
Douglas Gregor844cb502011-03-01 18:12:44 +0000199 if (SS && SS->isNotEmpty()) {
200 if (WantNontrivialTypeSourceInfo) {
201 // Construct a type with type-source information.
202 TypeLocBuilder Builder;
203 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
204
205 T = getElaboratedType(ETK_None, *SS, T);
206 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
207 ElabTL.setKeywordLoc(SourceLocation());
208 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
209 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
210 } else {
211 T = getElaboratedType(ETK_None, *SS, T);
212 }
213 }
Chris Lattner17e15f12009-10-25 17:16:46 +0000214 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
Fariborz Jahanian08891f52011-03-08 19:12:46 +0000215 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
Fariborz Jahanian87967422011-02-08 18:05:59 +0000216 if (!HasTrailingDot)
217 T = Context.getObjCInterfaceType(IDecl);
218 }
219
220 if (T.isNull()) {
John McCall27b18f82009-11-17 02:14:36 +0000221 // If it's not plausibly a type, suppress diagnostics.
222 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000223 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000224 }
John McCallba7bf592010-08-24 05:47:05 +0000225 return ParsedType::make(T);
Chris Lattnere168f762006-11-10 05:29:30 +0000226}
227
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000228/// isTagName() - This method is called *for error recovery purposes only*
229/// to determine if the specified name is a valid tag name ("struct foo"). If
230/// so, this returns the TST for the tag corresponding to it (TST_enum,
231/// TST_union, TST_struct, TST_class). This is used to diagnose cases in C
232/// where the user forgot to specify the tag.
233DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
234 // Do a tag name lookup in this scope.
John McCall27b18f82009-11-17 02:14:36 +0000235 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
236 LookupName(R, S, false);
237 R.suppressDiagnostics();
238 if (R.getResultKind() == LookupResult::Found)
John McCall67c00872009-12-02 08:25:40 +0000239 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000240 switch (TD->getTagKind()) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000241 default: return DeclSpec::TST_unspecified;
242 case TTK_Struct: return DeclSpec::TST_struct;
243 case TTK_Union: return DeclSpec::TST_union;
244 case TTK_Class: return DeclSpec::TST_class;
245 case TTK_Enum: return DeclSpec::TST_enum;
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000246 }
247 }
Mike Stump11289f42009-09-09 15:08:12 +0000248
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000249 return DeclSpec::TST_unspecified;
250}
251
Douglas Gregor15e56022009-10-13 23:27:22 +0000252bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
253 SourceLocation IILoc,
254 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000255 CXXScopeSpec *SS,
John McCallba7bf592010-08-24 05:47:05 +0000256 ParsedType &SuggestedType) {
Douglas Gregor15e56022009-10-13 23:27:22 +0000257 // We don't have anything to suggest (yet).
John McCallba7bf592010-08-24 05:47:05 +0000258 SuggestedType = ParsedType();
Douglas Gregor15e56022009-10-13 23:27:22 +0000259
Douglas Gregor2d435302009-12-30 17:04:44 +0000260 // There may have been a typo in the name of the type. Look up typo
261 // results, in case we have something that we can suggest.
262 LookupResult Lookup(*this, &II, IILoc, LookupOrdinaryName,
263 NotForRedeclaration);
264
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000265 if (DeclarationName Corrected = CorrectTypo(Lookup, S, SS, 0, 0, CTC_Type)) {
266 if (NamedDecl *Result = Lookup.getAsSingle<NamedDecl>()) {
267 if ((isa<TypeDecl>(Result) || isa<ObjCInterfaceDecl>(Result)) &&
268 !Result->isInvalidDecl()) {
269 // We found a similarly-named type or interface; suggest that.
270 if (!SS || !SS->isSet())
271 Diag(IILoc, diag::err_unknown_typename_suggest)
272 << &II << Lookup.getLookupName()
273 << FixItHint::CreateReplacement(SourceRange(IILoc),
274 Result->getNameAsString());
275 else if (DeclContext *DC = computeDeclContext(*SS, false))
276 Diag(IILoc, diag::err_unknown_nested_typename_suggest)
277 << &II << DC << Lookup.getLookupName() << SS->getRange()
278 << FixItHint::CreateReplacement(SourceRange(IILoc),
279 Result->getNameAsString());
280 else
281 llvm_unreachable("could not have corrected a typo here");
Douglas Gregor2d435302009-12-30 17:04:44 +0000282
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000283 Diag(Result->getLocation(), diag::note_previous_decl)
284 << Result->getDeclName();
285
Douglas Gregor844cb502011-03-01 18:12:44 +0000286 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS,
287 false, false, ParsedType(),
288 /*NonTrivialTypeSourceInfo=*/true);
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000289 return true;
290 }
291 } else if (Lookup.empty()) {
292 // We corrected to a keyword.
293 // FIXME: Actually recover with the keyword we suggest, and emit a fix-it.
294 Diag(IILoc, diag::err_unknown_typename_suggest)
295 << &II << Corrected;
296 return true;
Douglas Gregor2d435302009-12-30 17:04:44 +0000297 }
298 }
299
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000300 if (getLangOptions().CPlusPlus) {
301 // See if II is a class template that the user forgot to pass arguments to.
302 UnqualifiedId Name;
303 Name.setIdentifier(&II, IILoc);
304 CXXScopeSpec EmptySS;
305 TemplateTy TemplateResult;
Douglas Gregor786123d2010-05-21 23:18:07 +0000306 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000307 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
John McCallba7bf592010-08-24 05:47:05 +0000308 Name, ParsedType(), true, TemplateResult,
Douglas Gregor786123d2010-05-21 23:18:07 +0000309 MemberOfUnknownSpecialization) == TNK_Type_template) {
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000310 TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
311 Diag(IILoc, diag::err_template_missing_args) << TplName;
312 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
313 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
314 << TplDecl->getTemplateParameters()->getSourceRange();
315 }
316 return true;
317 }
318 }
319
Douglas Gregor15e56022009-10-13 23:27:22 +0000320 // FIXME: Should we move the logic that tries to recover from a missing tag
321 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
322
Douglas Gregor2d435302009-12-30 17:04:44 +0000323 if (!SS || (!SS->isSet() && !SS->isInvalid()))
Douglas Gregor15e56022009-10-13 23:27:22 +0000324 Diag(IILoc, diag::err_unknown_typename) << &II;
325 else if (DeclContext *DC = computeDeclContext(*SS, false))
326 Diag(IILoc, diag::err_typename_nested_not_found)
327 << &II << DC << SS->getRange();
328 else if (isDependentScopeSpecifier(*SS)) {
329 Diag(SS->getRange().getBegin(), diag::err_typename_missing)
Daniel Dunbar07d07852009-10-18 21:17:35 +0000330 << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
Douglas Gregor15e56022009-10-13 23:27:22 +0000331 << SourceRange(SS->getRange().getBegin(), IILoc)
Douglas Gregora771f462010-03-31 17:46:05 +0000332 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
Douglas Gregorf7d77712010-06-16 22:31:08 +0000333 SuggestedType = ActOnTypenameType(S, SourceLocation(), *SS, II, IILoc).get();
Douglas Gregor15e56022009-10-13 23:27:22 +0000334 } else {
335 assert(SS && SS->isInvalid() &&
336 "Invalid scope specifier has already been diagnosed");
337 }
338
339 return true;
340}
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000341
John McCall5ed6e8f2009-08-18 00:00:49 +0000342// Determines the context to return to after temporarily entering a
343// context. This depends in an unnecessarily complicated way on the
344// exact ordering of callbacks from the parser.
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000345DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000346
John McCall5ed6e8f2009-08-18 00:00:49 +0000347 // Functions defined inline within classes aren't parsed until we've
348 // finished parsing the top-level class, so the top-level class is
349 // the context we'll need to return to.
350 if (isa<FunctionDecl>(DC)) {
351 DC = DC->getLexicalParent();
352
353 // A function not defined within a class will always return to its
354 // lexical context.
355 if (!isa<CXXRecordDecl>(DC))
356 return DC;
357
358 // A C++ inline method/friend is parsed *after* the topmost class
359 // it was declared in is fully parsed ("complete"); the topmost
360 // class is the context we need to return to.
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000361 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000362 DC = RD;
363
364 // Return the declaration context of the topmost class the inline method is
365 // declared in.
366 return DC;
367 }
368
John McCalldc9796e2010-08-06 00:46:05 +0000369 // ObjCMethodDecls are parsed (for some reason) outside the context
370 // of the class.
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +0000371 if (isa<ObjCMethodDecl>(DC))
John McCalldc9796e2010-08-06 00:46:05 +0000372 return DC->getLexicalParent()->getLexicalParent();
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +0000373
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000374 return DC->getLexicalParent();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000375}
376
Douglas Gregor91f84212008-12-11 16:49:14 +0000377void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000378 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu17a37eb2008-12-08 07:14:51 +0000379 "The next DeclContext should be lexically contained in the current one.");
Chris Lattnerbec41342008-04-22 18:39:57 +0000380 CurContext = DC;
Douglas Gregor91f84212008-12-11 16:49:14 +0000381 S->setEntity(DC);
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000382}
383
Chris Lattner0a5ff0d2008-04-06 04:47:34 +0000384void Sema::PopDeclContext() {
385 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor91f84212008-12-11 16:49:14 +0000386
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000387 CurContext = getContainingDC(CurContext);
John McCalldd762d12010-07-23 22:45:07 +0000388 assert(CurContext && "Popped translation unit!");
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000389}
390
Argyrios Kyrtzidis9941a4d2009-06-17 23:19:02 +0000391/// EnterDeclaratorContext - Used when we must lookup names in the context
392/// of a declarator's nested name specifier.
John McCall6df5fef2009-12-19 10:49:29 +0000393///
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000394void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall6df5fef2009-12-19 10:49:29 +0000395 // C++0x [basic.lookup.unqual]p13:
396 // A name used in the definition of a static data member of class
397 // X (after the qualified-id of the static member) is looked up as
398 // if the name was used in a member function of X.
399 // C++0x [basic.lookup.unqual]p14:
400 // If a variable member of a namespace is defined outside of the
401 // scope of its namespace then any name used in the definition of
402 // the variable member (after the declarator-id) is looked up as
403 // if the definition of the variable member occurred in its
404 // namespace.
405 // Both of these imply that we should push a scope whose context
406 // is the semantic context of the declaration. We can't use
407 // PushDeclContext here because that context is not necessarily
408 // lexically contained in the current context. Fortunately,
409 // the containing scope should have the appropriate information.
410
411 assert(!S->getEntity() && "scope already has entity");
412
413#ifndef NDEBUG
414 Scope *Ancestor = S->getParent();
415 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
416 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
417#endif
418
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000419 CurContext = DC;
John McCall6df5fef2009-12-19 10:49:29 +0000420 S->setEntity(DC);
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000421}
422
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000423void Sema::ExitDeclaratorContext(Scope *S) {
John McCall6df5fef2009-12-19 10:49:29 +0000424 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000425
John McCall6df5fef2009-12-19 10:49:29 +0000426 // Switch back to the lexical context. The safety of this is
427 // enforced by an assert in EnterDeclaratorContext.
428 Scope *Ancestor = S->getParent();
429 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
430 CurContext = (DeclContext*) Ancestor->getEntity();
431
432 // We don't need to do anything with the scope, which is going to
433 // disappear.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000434}
435
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000436/// \brief Determine whether we allow overloading of the function
437/// PrevDecl with another declaration.
438///
439/// This routine determines whether overloading is possible, not
440/// whether some new function is actually an overload. It will return
441/// true in C++ (where we can always provide overloads) or, as an
442/// extension, in C when the previous function is already an
443/// overloaded function declaration or has the "overloadable"
444/// attribute.
John McCall1f82f242009-11-18 22:49:29 +0000445static bool AllowOverloadingOfFunction(LookupResult &Previous,
446 ASTContext &Context) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000447 if (Context.getLangOptions().CPlusPlus)
448 return true;
449
John McCall1f82f242009-11-18 22:49:29 +0000450 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000451 return true;
452
John McCall1f82f242009-11-18 22:49:29 +0000453 return (Previous.getResultKind() == LookupResult::Found
454 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000455}
456
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +0000457/// Add this decl to the scope shadowed decl chains.
John McCall759e32b2009-08-31 22:39:49 +0000458void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor07665a62009-01-05 19:45:36 +0000459 // Move up the scope chain until we find the nearest enclosing
460 // non-transparent context. The declaration will be introduced into this
461 // scope.
Mike Stump11289f42009-09-09 15:08:12 +0000462 while (S->getEntity() &&
Douglas Gregor07665a62009-01-05 19:45:36 +0000463 ((DeclContext *)S->getEntity())->isTransparentContext())
464 S = S->getParent();
465
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000466 // Add scoped declarations into their context, so that they can be
467 // found later. Declarations without a context won't be inserted
468 // into any context.
John McCall759e32b2009-08-31 22:39:49 +0000469 if (AddToContext)
470 CurContext->addDecl(D);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000471
Chandler Carruthf50ef6e2010-02-21 07:08:09 +0000472 // Out-of-line definitions shouldn't be pushed into scope in C++.
473 // Out-of-line variable and function definitions shouldn't even in C.
474 if ((getLangOptions().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
475 D->isOutOfLine())
476 return;
477
478 // Template instantiations should also not be pushed into scope.
479 if (isa<FunctionDecl>(D) &&
480 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregor5ad7c542009-09-28 18:41:37 +0000481 return;
482
John McCall9f3059a2009-10-09 21:13:30 +0000483 // If this replaces anything in the current scope,
484 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
485 IEnd = IdResolver.end();
486 for (; I != IEnd; ++I) {
John McCall48871652010-08-21 09:40:31 +0000487 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
488 S->RemoveDecl(*I);
John McCall9f3059a2009-10-09 21:13:30 +0000489 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000490
John McCall9f3059a2009-10-09 21:13:30 +0000491 // Should only need to replace one decl.
492 break;
Douglas Gregor38feed82009-04-24 02:57:34 +0000493 }
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000494 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000495
John McCall48871652010-08-21 09:40:31 +0000496 S->AddDecl(D);
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000497 IdResolver.AddDecl(D);
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +0000498}
499
Douglas Gregordb446112011-03-07 16:54:27 +0000500bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S,
501 bool ExplicitInstantiationOrSpecialization) {
502 return IdResolver.isDeclInScope(D, Ctx, Context, S,
503 ExplicitInstantiationOrSpecialization);
Douglas Gregor505ad492009-09-28 00:47:05 +0000504}
505
John McCallcc14d1f2010-08-24 08:50:51 +0000506Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
507 DeclContext *TargetDC = DC->getPrimaryContext();
508 do {
509 if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
510 if (ScopeDC->getPrimaryContext() == TargetDC)
511 return S;
512 } while ((S = S->getParent()));
513
514 return 0;
515}
516
John McCall1f82f242009-11-18 22:49:29 +0000517static bool isOutOfScopePreviousDeclaration(NamedDecl *,
518 DeclContext*,
519 ASTContext&);
520
521/// Filters out lookup results that don't fall within the given scope
522/// as determined by isDeclInScope.
523static void FilterLookupForScope(Sema &SemaRef, LookupResult &R,
524 DeclContext *Ctx, Scope *S,
Douglas Gregordb446112011-03-07 16:54:27 +0000525 bool ConsiderLinkage,
526 bool ExplicitInstantiationOrSpecialization) {
John McCall1f82f242009-11-18 22:49:29 +0000527 LookupResult::Filter F = R.makeFilter();
528 while (F.hasNext()) {
529 NamedDecl *D = F.next();
530
Douglas Gregordb446112011-03-07 16:54:27 +0000531 if (SemaRef.isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
John McCall1f82f242009-11-18 22:49:29 +0000532 continue;
533
534 if (ConsiderLinkage &&
535 isOutOfScopePreviousDeclaration(D, Ctx, SemaRef.Context))
536 continue;
537
538 F.erase();
539 }
540
541 F.done();
542}
543
544static bool isUsingDecl(NamedDecl *D) {
545 return isa<UsingShadowDecl>(D) ||
546 isa<UnresolvedUsingTypenameDecl>(D) ||
547 isa<UnresolvedUsingValueDecl>(D);
548}
549
550/// Removes using shadow declarations from the lookup results.
551static void RemoveUsingDecls(LookupResult &R) {
552 LookupResult::Filter F = R.makeFilter();
553 while (F.hasNext())
554 if (isUsingDecl(F.next()))
555 F.erase();
556
557 F.done();
558}
559
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000560/// \brief Check for this common pattern:
561/// @code
562/// class S {
563/// S(const S&); // DO NOT IMPLEMENT
564/// void operator=(const S&); // DO NOT IMPLEMENT
565/// };
566/// @endcode
567static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
568 // FIXME: Should check for private access too but access is set after we get
569 // the decl here.
570 if (D->isThisDeclarationADefinition())
571 return false;
572
573 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
574 return CD->isCopyConstructor();
Douglas Gregora1ce1f82010-09-27 22:06:20 +0000575 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
576 return Method->isCopyAssignmentOperator();
577 return false;
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000578}
579
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000580bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
581 assert(D);
Argyrios Kyrtzidis540bc012010-08-13 18:42:29 +0000582
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000583 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
584 return false;
585
586 // Ignore class templates.
Chandler Carruth8e666512011-01-03 19:27:19 +0000587 if (D->getDeclContext()->isDependentContext() ||
588 D->getLexicalDeclContext()->isDependentContext())
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000589 return false;
590
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000591 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000592 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
593 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000594
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000595 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
596 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
597 return false;
598 } else {
599 // 'static inline' functions are used in headers; don't warn.
John McCall8e7d6562010-08-26 03:08:43 +0000600 if (FD->getStorageClass() == SC_Static &&
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000601 FD->isInlineSpecified())
602 return false;
603 }
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000604
John McCalld37d35b2010-10-27 01:41:35 +0000605 if (FD->isThisDeclarationADefinition() &&
606 Context.DeclMustBeEmitted(FD))
607 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000608
John McCalld37d35b2010-10-27 01:41:35 +0000609 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
610 if (!VD->isFileVarDecl() ||
611 VD->getType().isConstant(Context) ||
612 Context.DeclMustBeEmitted(VD))
613 return false;
614
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000615 if (VD->isStaticDataMember() &&
616 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
617 return false;
618
John McCalld37d35b2010-10-27 01:41:35 +0000619 } else {
620 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000621 }
622
John McCalld37d35b2010-10-27 01:41:35 +0000623 // Only warn for unused decls internal to the translation unit.
624 if (D->getLinkage() == ExternalLinkage)
625 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000626
John McCalld37d35b2010-10-27 01:41:35 +0000627 return true;
628}
629
630void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000631 if (!D)
632 return;
633
634 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
635 const FunctionDecl *First = FD->getFirstDeclaration();
636 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
637 return; // First should already be in the vector.
638 }
639
640 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
641 const VarDecl *First = VD->getFirstDeclaration();
642 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
643 return; // First should already be in the vector.
644 }
645
646 if (ShouldWarnIfUnusedFileScopedDecl(D))
647 UnusedFileScopedDecls.push_back(D);
648 }
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +0000649
Anders Carlsson2889e0e2009-11-07 07:18:14 +0000650static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall67da35c2010-02-04 22:26:26 +0000651 if (D->isInvalidDecl())
652 return false;
653
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +0000654 if (D->isUsed() || D->hasAttr<UnusedAttr>())
655 return false;
John McCall67da35c2010-02-04 22:26:26 +0000656
Chris Lattnercab02a62011-02-17 20:34:02 +0000657 if (isa<LabelDecl>(D))
658 return true;
659
John McCall67da35c2010-02-04 22:26:26 +0000660 // White-list anything that isn't a local variable.
661 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
662 !D->getDeclContext()->isFunctionOrMethod())
663 return false;
664
665 // Types of valid local variables should be complete, so this should succeed.
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +0000666 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
John McCallcef15822010-03-31 02:47:45 +0000667
668 // White-list anything with an __attribute__((unused)) type.
669 QualType Ty = VD->getType();
670
671 // Only look at the outermost level of typedef.
672 if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) {
673 if (TT->getDecl()->hasAttr<UnusedAttr>())
674 return false;
675 }
676
Douglas Gregor14f232e2010-05-08 23:05:03 +0000677 // If we failed to complete the type for some reason, or if the type is
678 // dependent, don't diagnose the variable.
679 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregor19defcd2010-04-27 16:20:13 +0000680 return false;
681
John McCallcef15822010-03-31 02:47:45 +0000682 if (const TagType *TT = Ty->getAs<TagType>()) {
683 const TagDecl *Tag = TT->getDecl();
684 if (Tag->hasAttr<UnusedAttr>())
685 return false;
686
687 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Douglas Gregor14f232e2010-05-08 23:05:03 +0000688 // FIXME: Checking for the presence of a user-declared constructor
689 // isn't completely accurate; we'd prefer to check that the initializer
690 // has no side effects.
691 if (RD->hasUserDeclaredConstructor() || !RD->hasTrivialDestructor())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +0000692 return false;
693 }
694 }
John McCallcef15822010-03-31 02:47:45 +0000695
696 // TODO: __attribute__((unused)) templates?
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +0000697 }
698
John McCall67da35c2010-02-04 22:26:26 +0000699 return true;
Anders Carlsson2889e0e2009-11-07 07:18:14 +0000700}
701
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000702/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
703/// unless they are marked attr(unused).
Douglas Gregor14f232e2010-05-08 23:05:03 +0000704void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
705 if (!ShouldDiagnoseUnusedDecl(D))
706 return;
707
Chris Lattnercab02a62011-02-17 20:34:02 +0000708 unsigned DiagID;
Douglas Gregor14f232e2010-05-08 23:05:03 +0000709 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
Chris Lattnercab02a62011-02-17 20:34:02 +0000710 DiagID = diag::warn_unused_exception_param;
711 else if (isa<LabelDecl>(D))
712 DiagID = diag::warn_unused_label;
Douglas Gregor14f232e2010-05-08 23:05:03 +0000713 else
Chris Lattnercab02a62011-02-17 20:34:02 +0000714 DiagID = diag::warn_unused_variable;
715
716 Diag(D->getLocation(), DiagID) << D->getDeclName();
Douglas Gregor14f232e2010-05-08 23:05:03 +0000717}
718
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000719static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
720 // Verify that we have no forward references left. If so, there was a goto
721 // or address of a label taken, but no definition of it. Label fwd
722 // definitions are indicated with a null substmt.
723 if (L->getStmt() == 0)
724 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
725}
726
Steve Naroffc62adb62007-10-09 22:01:59 +0000727void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000728 if (S->decl_empty()) return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000729 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump11289f42009-09-09 15:08:12 +0000730 "Scope shouldn't contain decls!");
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000731
Chris Lattner302b4be2006-11-19 02:31:38 +0000732 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
733 I != E; ++I) {
John McCall48871652010-08-21 09:40:31 +0000734 Decl *TmpD = (*I);
Steve Naroff9324db12007-09-13 18:10:37 +0000735 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +0000736
Douglas Gregor91f84212008-12-11 16:49:14 +0000737 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
738 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +0000739
Douglas Gregor91f84212008-12-11 16:49:14 +0000740 if (!D->getDeclName()) continue;
Chris Lattnerc5c95b52008-04-11 07:00:53 +0000741
Douglas Gregor3beaf9b2009-10-08 21:35:42 +0000742 // Diagnose unused variables in this scope.
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +0000743 if (!S->hasErrorOccurred())
Douglas Gregor14f232e2010-05-08 23:05:03 +0000744 DiagnoseUnusedDecl(D);
745
Chris Lattnerebb5c6c2011-02-18 01:27:55 +0000746 // If this was a forward reference to a label, verify it was defined.
747 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
748 CheckPoppedLabel(LD, *this);
749
Douglas Gregor91f84212008-12-11 16:49:14 +0000750 // Remove this name from our lexical scope.
751 IdResolver.RemoveDecl(D);
Chris Lattner302b4be2006-11-19 02:31:38 +0000752 }
753}
754
Douglas Gregor1c283312010-08-11 12:19:30 +0000755/// \brief Look for an Objective-C class in the translation unit.
756///
757/// \param Id The name of the Objective-C class we're looking for. If
758/// typo-correction fixes this name, the Id will be updated
759/// to the fixed name.
760///
761/// \param IdLoc The location of the name in the translation unit.
762///
763/// \param TypoCorrection If true, this routine will attempt typo correction
764/// if there is no class with the given name.
765///
766/// \returns The declaration of the named Objective-C class, or NULL if the
767/// class could not be found.
768ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
769 SourceLocation IdLoc,
770 bool TypoCorrection) {
771 // The third "scope" argument is 0 since we aren't enabling lazy built-in
772 // creation from this context.
773 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
774
775 if (!IDecl && TypoCorrection) {
776 // Perform typo correction at the given location, but only if we
777 // find an Objective-C class name.
778 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName);
779 if (CorrectTypo(R, TUScope, 0, 0, false, CTC_NoKeywords) &&
780 (IDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
781 Diag(IdLoc, diag::err_undef_interface_suggest)
782 << Id << IDecl->getDeclName()
783 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
784 Diag(IDecl->getLocation(), diag::note_previous_decl)
785 << IDecl->getDeclName();
786
787 Id = IDecl->getIdentifier();
788 }
789 }
790
791 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
792}
793
Douglas Gregor45a33ec2009-01-12 18:45:55 +0000794/// getNonFieldDeclScope - Retrieves the innermost scope, starting
795/// from S, where a non-field would be declared. This routine copes
796/// with the difference between C and C++ scoping rules in structs and
797/// unions. For example, the following code is well-formed in C but
798/// ill-formed in C++:
799/// @code
800/// struct S6 {
801/// enum { BAR } e;
802/// };
Mike Stump11289f42009-09-09 15:08:12 +0000803///
Douglas Gregor45a33ec2009-01-12 18:45:55 +0000804/// void test_S6() {
805/// struct S6 a;
806/// a.e = BAR;
807/// }
808/// @endcode
809/// For the declaration of BAR, this routine will return a different
810/// scope. The scope S will be the scope of the unnamed enumeration
811/// within S6. In C++, this routine will return the scope associated
812/// with S6, because the enumeration's scope is a transparent
813/// context but structures can contain non-field names. In C, this
814/// routine will return the translation unit scope, since the
815/// enumeration's scope is a transparent context and structures cannot
816/// contain non-field names.
817Scope *Sema::getNonFieldDeclScope(Scope *S) {
818 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Mike Stump11289f42009-09-09 15:08:12 +0000819 (S->getEntity() &&
Douglas Gregor45a33ec2009-01-12 18:45:55 +0000820 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
821 (S->isClassScope() && !getLangOptions().CPlusPlus))
822 S = S->getParent();
823 return S;
824}
825
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000826/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
827/// file scope. lazily create a decl for it. ForRedeclaration is true
828/// if we're creating this built-in in anticipation of redeclaring the
829/// built-in.
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000830NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000831 Scope *S, bool ForRedeclaration,
832 SourceLocation Loc) {
Chris Lattner9561a0b2007-01-28 08:20:04 +0000833 Builtin::ID BID = (Builtin::ID)bid;
834
Chris Lattnerecd79c62009-06-14 00:45:47 +0000835 ASTContext::GetBuiltinTypeError Error;
Mike Stump11289f42009-09-09 15:08:12 +0000836 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor538c3d82009-02-14 01:52:53 +0000837 switch (Error) {
Chris Lattnerecd79c62009-06-14 00:45:47 +0000838 case ASTContext::GE_None:
Douglas Gregor538c3d82009-02-14 01:52:53 +0000839 // Okay
840 break;
841
Mike Stump93246cc2009-07-28 23:57:15 +0000842 case ASTContext::GE_Missing_stdio:
Douglas Gregor538c3d82009-02-14 01:52:53 +0000843 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000844 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
Douglas Gregor538c3d82009-02-14 01:52:53 +0000845 << Context.BuiltinInfo.GetName(BID);
846 return 0;
Mike Stumpa4de80b2009-07-28 02:25:19 +0000847
Mike Stump93246cc2009-07-28 23:57:15 +0000848 case ASTContext::GE_Missing_setjmp:
Mike Stumpa4de80b2009-07-28 02:25:19 +0000849 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +0000850 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
Mike Stumpa4de80b2009-07-28 02:25:19 +0000851 << Context.BuiltinInfo.GetName(BID);
852 return 0;
Douglas Gregor538c3d82009-02-14 01:52:53 +0000853 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000854
855 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
856 Diag(Loc, diag::ext_implicit_lib_function_decl)
857 << Context.BuiltinInfo.GetName(BID)
858 << R;
Douglas Gregor9eebd972009-02-16 21:58:21 +0000859 if (Context.BuiltinInfo.getHeaderName(BID) &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000860 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
Chris Lattneraf73cf62009-04-16 03:59:32 +0000861 != Diagnostic::Ignored)
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000862 Diag(Loc, diag::note_please_include_header)
863 << Context.BuiltinInfo.getHeaderName(BID)
864 << Context.BuiltinInfo.GetName(BID);
865 }
866
Argyrios Kyrtzidis6d053032008-04-17 14:47:13 +0000867 FunctionDecl *New = FunctionDecl::Create(Context,
868 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000869 Loc, Loc, II, R, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +0000870 SC_Extern,
871 SC_None, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +0000872 /*hasPrototype=*/true);
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000873 New->setImplicit();
874
Chris Lattner4dd27102008-05-05 22:18:14 +0000875 // Create Decl objects for each parameter, adding them to the
876 // FunctionDecl.
John McCall424cec92011-01-19 06:33:43 +0000877 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner4dd27102008-05-05 22:18:14 +0000878 llvm::SmallVector<ParmVarDecl*, 16> Params;
879 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
Abramo Bagnaradff19302011-03-08 08:55:46 +0000880 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(),
881 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +0000882 FT->getArgType(i), /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +0000883 SC_None, SC_None, 0));
Douglas Gregord5058122010-02-11 01:19:42 +0000884 New->setParams(Params.data(), Params.size());
Chris Lattner4dd27102008-05-05 22:18:14 +0000885 }
Mike Stump11289f42009-09-09 15:08:12 +0000886
887 AddKnownFunctionAttributes(New);
888
Chris Lattnerc5c95b52008-04-11 07:00:53 +0000889 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregorc72e6452009-01-09 18:51:29 +0000890 // FIXME: This is hideous. We need to teach PushOnScopeChains to
891 // relate Scopes to DeclContexts, and probably eliminate CurContext
892 // entirely, but we're not there yet.
893 DeclContext *SavedContext = CurContext;
894 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000895 PushOnScopeChains(New, TUScope);
Douglas Gregorc72e6452009-01-09 18:51:29 +0000896 CurContext = SavedContext;
Chris Lattner9561a0b2007-01-28 08:20:04 +0000897 return New;
898}
899
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000900/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
901/// same name and scope as a previous declaration 'Old'. Figure out
902/// how to resolve this situation, merging decls or emitting
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000903/// diagnostics as appropriate. If there was an error, set New to be invalid.
Chris Lattner01564d92007-01-27 19:27:06 +0000904///
John McCall1f82f242009-11-18 22:49:29 +0000905void Sema::MergeTypeDefDecl(TypedefDecl *New, LookupResult &OldDecls) {
906 // If the new decl is known invalid already, don't bother doing any
907 // merging checks.
908 if (New->isInvalidDecl()) return;
Mike Stump11289f42009-09-09 15:08:12 +0000909
Steve Naroff44cfcb62008-09-09 14:32:20 +0000910 // Allow multiple definitions for ObjC built-in typedefs.
911 // FIXME: Verify the underlying types are equivalent!
912 if (getLangOptions().ObjC1) {
Chris Lattner66e32812008-11-20 05:41:43 +0000913 const IdentifierInfo *TypeID = New->getIdentifier();
914 switch (TypeID->getLength()) {
915 default: break;
Mike Stump11289f42009-09-09 15:08:12 +0000916 case 2:
Chris Lattner66e32812008-11-20 05:41:43 +0000917 if (!TypeID->isStr("id"))
918 break;
David Chisnall9f57c292009-08-17 16:35:33 +0000919 Context.ObjCIdRedefinitionType = New->getUnderlyingType();
Steve Naroff7cae42b2009-07-10 23:34:53 +0000920 // Install the built-in type for 'id', ignoring the current definition.
921 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
922 return;
Chris Lattner66e32812008-11-20 05:41:43 +0000923 case 5:
924 if (!TypeID->isStr("Class"))
925 break;
David Chisnall9f57c292009-08-17 16:35:33 +0000926 Context.ObjCClassRedefinitionType = New->getUnderlyingType();
Steve Naroff7cae42b2009-07-10 23:34:53 +0000927 // Install the built-in type for 'Class', ignoring the current definition.
928 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000929 return;
Chris Lattner66e32812008-11-20 05:41:43 +0000930 case 3:
931 if (!TypeID->isStr("SEL"))
932 break;
Fariborz Jahanian04b258c2009-11-25 23:07:42 +0000933 Context.ObjCSelRedefinitionType = New->getUnderlyingType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000934 // Install the built-in type for 'SEL', ignoring the current definition.
935 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000936 return;
Chris Lattner66e32812008-11-20 05:41:43 +0000937 case 8:
938 if (!TypeID->isStr("Protocol"))
939 break;
Steve Naroff44cfcb62008-09-09 14:32:20 +0000940 Context.setObjCProtoType(New->getUnderlyingType());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000941 return;
Steve Naroff44cfcb62008-09-09 14:32:20 +0000942 }
943 // Fall through - the typedef name was not a builtin type.
944 }
John McCall1f82f242009-11-18 22:49:29 +0000945
Douglas Gregorfb034662009-01-28 17:15:10 +0000946 // Verify the old decl was also a type.
John McCall91f1a022009-12-30 00:31:22 +0000947 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
948 if (!Old) {
Mike Stump11289f42009-09-09 15:08:12 +0000949 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000950 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +0000951
952 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000953 if (OldD->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +0000954 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall1f82f242009-11-18 22:49:29 +0000955
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000956 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +0000957 }
Douglas Gregorfb034662009-01-28 17:15:10 +0000958
John McCall1f82f242009-11-18 22:49:29 +0000959 // If the old declaration is invalid, just give up here.
960 if (Old->isInvalidDecl())
961 return New->setInvalidDecl();
962
Mike Stump11289f42009-09-09 15:08:12 +0000963 // Determine the "old" type we'll use for checking and diagnostics.
Douglas Gregorfb034662009-01-28 17:15:10 +0000964 QualType OldType;
965 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
966 OldType = OldTypedef->getUnderlyingType();
967 else
968 OldType = Context.getTypeDeclType(Old);
969
Chris Lattnerf9c49e52008-07-25 18:44:27 +0000970 // If the typedef types are not identical, reject them in all languages and
971 // with any extensions enabled.
Douglas Gregorfb034662009-01-28 17:15:10 +0000972
Mike Stump11289f42009-09-09 15:08:12 +0000973 if (OldType != New->getUnderlyingType() &&
974 Context.getCanonicalType(OldType) !=
Chris Lattnerf9c49e52008-07-25 18:44:27 +0000975 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +0000976 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Douglas Gregorfb034662009-01-28 17:15:10 +0000977 << New->getUnderlyingType() << OldType;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000978 if (Old->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +0000979 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000980 return New->setInvalidDecl();
Chris Lattnerf9c49e52008-07-25 18:44:27 +0000981 }
Mike Stump11289f42009-09-09 15:08:12 +0000982
John McCall91f1a022009-12-30 00:31:22 +0000983 // The types match. Link up the redeclaration chain if the old
984 // declaration was a typedef.
985 // FIXME: this is a potential source of wierdness if the type
986 // spellings don't match exactly.
987 if (isa<TypedefDecl>(Old))
988 New->setPreviousDeclaration(cast<TypedefDecl>(Old));
989
Steve Naroff7cae42b2009-07-10 23:34:53 +0000990 if (getLangOptions().Microsoft)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000991 return;
Eli Friedman61b529f2008-06-11 06:20:39 +0000992
Chris Lattner2581fc32009-04-17 22:04:20 +0000993 if (getLangOptions().CPlusPlus) {
Douglas Gregor9dd13ab2010-01-11 21:54:40 +0000994 // C++ [dcl.typedef]p2:
995 // In a given non-class scope, a typedef specifier can be used to
996 // redefine the name of any type declared in that scope to refer
997 // to the type to which it already refers.
Chris Lattner2581fc32009-04-17 22:04:20 +0000998 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000999 return;
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001000
1001 // C++0x [dcl.typedef]p4:
1002 // In a given class scope, a typedef specifier can be used to redefine
1003 // any class-name declared in that scope that is not also a typedef-name
1004 // to refer to the type to which it already refers.
1005 //
1006 // This wording came in via DR424, which was a correction to the
1007 // wording in DR56, which accidentally banned code like:
1008 //
1009 // struct S {
1010 // typedef struct A { } A;
1011 // };
1012 //
1013 // in the C++03 standard. We implement the C++0x semantics, which
1014 // allow the above but disallow
1015 //
1016 // struct S {
1017 // typedef int I;
1018 // typedef int I;
1019 // };
1020 //
1021 // since that was the intent of DR56.
Douglas Gregord6150262010-01-11 22:30:10 +00001022 if (!isa<TypedefDecl >(Old))
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001023 return;
1024
Chris Lattner2581fc32009-04-17 22:04:20 +00001025 Diag(New->getLocation(), diag::err_redefinition)
1026 << New->getDeclName();
1027 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001028 return New->setInvalidDecl();
Daniel Dunbar84b70f72008-09-12 18:10:20 +00001029 }
Eli Friedman61b529f2008-06-11 06:20:39 +00001030
Chris Lattner2581fc32009-04-17 22:04:20 +00001031 // If we have a redefinition of a typedef in C, emit a warning. This warning
1032 // is normally mapped to an error, but can be controlled with
Eli Friedman319ce952009-06-04 23:03:07 +00001033 // -Wtypedef-redefinition. If either the original or the redefinition is
1034 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner30d0cfd2010-03-01 20:59:53 +00001035 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman319ce952009-06-04 23:03:07 +00001036 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1037 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattner9a845892009-04-27 01:46:12 +00001038 return;
Mike Stump11289f42009-09-09 15:08:12 +00001039
Chris Lattner2581fc32009-04-17 22:04:20 +00001040 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1041 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001042 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001043 return;
Chris Lattner01564d92007-01-27 19:27:06 +00001044}
1045
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001046/// DeclhasAttr - returns true if decl Declaration already has the target
1047/// attribute.
Mike Stump11289f42009-09-09 15:08:12 +00001048static bool
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001049DeclHasAttr(const Decl *D, const Attr *A) {
1050 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1051 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1052 if ((*i)->getKind() == A->getKind()) {
1053 // FIXME: Don't hardcode this check
1054 if (OA && isa<OwnershipAttr>(*i))
1055 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
Chris Lattner84966392008-03-03 03:28:21 +00001056 return true;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001057 }
Chris Lattner84966392008-03-03 03:28:21 +00001058
1059 return false;
1060}
1061
John McCallf79e87d2011-03-02 04:00:57 +00001062/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
1063static void mergeDeclAttributes(Decl *newDecl, const Decl *oldDecl,
1064 ASTContext &C) {
1065 if (!oldDecl->hasAttrs())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001066 return;
John McCallf79e87d2011-03-02 04:00:57 +00001067
1068 bool foundAny = newDecl->hasAttrs();
1069
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001070 // Ensure that any moving of objects within the allocated map is done before
1071 // we process them.
John McCallf79e87d2011-03-02 04:00:57 +00001072 if (!foundAny) newDecl->setAttrs(AttrVec());
1073
Peter Collingbourneab8bc062011-01-21 02:08:36 +00001074 for (specific_attr_iterator<InheritableAttr>
John McCallf79e87d2011-03-02 04:00:57 +00001075 i = oldDecl->specific_attr_begin<InheritableAttr>(),
1076 e = oldDecl->specific_attr_end<InheritableAttr>(); i != e; ++i) {
1077 if (!DeclHasAttr(newDecl, *i)) {
1078 InheritableAttr *newAttr = cast<InheritableAttr>((*i)->clone(C));
1079 newAttr->setInherited(true);
1080 newDecl->addAttr(newAttr);
1081 foundAny = true;
Chris Lattner84966392008-03-03 03:28:21 +00001082 }
1083 }
John McCallf79e87d2011-03-02 04:00:57 +00001084
1085 if (!foundAny) newDecl->dropAttrs();
1086}
1087
1088/// mergeParamDeclAttributes - Copy attributes from the old parameter
1089/// to the new one.
1090static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
1091 const ParmVarDecl *oldDecl,
1092 ASTContext &C) {
1093 if (!oldDecl->hasAttrs())
1094 return;
1095
1096 bool foundAny = newDecl->hasAttrs();
1097
1098 // Ensure that any moving of objects within the allocated map is
1099 // done before we process them.
1100 if (!foundAny) newDecl->setAttrs(AttrVec());
1101
1102 for (specific_attr_iterator<InheritableParamAttr>
1103 i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
1104 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
1105 if (!DeclHasAttr(newDecl, *i)) {
1106 InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C));
1107 newAttr->setInherited(true);
1108 newDecl->addAttr(newAttr);
1109 foundAny = true;
1110 }
1111 }
1112
1113 if (!foundAny) newDecl->dropAttrs();
Chris Lattner84966392008-03-03 03:28:21 +00001114}
1115
Dan Gohman28ade552010-07-26 21:25:24 +00001116namespace {
1117
Douglas Gregora74a2972009-03-06 22:43:54 +00001118/// Used in MergeFunctionDecl to keep track of function parameters in
1119/// C.
1120struct GNUCompatibleParamWarning {
1121 ParmVarDecl *OldParm;
1122 ParmVarDecl *NewParm;
1123 QualType PromotedType;
1124};
1125
Dan Gohman28ade552010-07-26 21:25:24 +00001126}
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001127
1128/// getSpecialMember - get the special member enum for a method.
Anders Carlsson05bf0092010-04-22 05:40:53 +00001129Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001130 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Douglas Gregor507eb872009-12-22 00:34:07 +00001131 if (Ctor->isCopyConstructor())
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001132 return Sema::CXXCopyConstructor;
Anders Carlsson05bf0092010-04-22 05:40:53 +00001133
1134 return Sema::CXXConstructor;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001135 }
1136
1137 if (isa<CXXDestructorDecl>(MD))
1138 return Sema::CXXDestructor;
1139
Douglas Gregorec3bec02010-09-27 22:37:28 +00001140 assert(MD->isCopyAssignmentOperator() &&
1141 "Must have copy assignment operator");
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001142 return Sema::CXXCopyAssignment;
1143}
1144
Sebastian Redl243d9052010-06-09 21:17:41 +00001145/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisfea48452010-02-18 02:00:42 +00001146/// only extern inline functions can be redefined, and even then only in
1147/// GNU89 mode.
1148static bool canRedefineFunction(const FunctionDecl *FD,
1149 const LangOptions& LangOpts) {
1150 return (LangOpts.GNUMode && !LangOpts.C99 && !LangOpts.CPlusPlus &&
1151 FD->isInlineSpecified() &&
John McCall8e7d6562010-08-26 03:08:43 +00001152 FD->getStorageClass() == SC_Extern);
Charles Davisfea48452010-02-18 02:00:42 +00001153}
1154
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001155/// MergeFunctionDecl - We just parsed a function 'New' from
1156/// declarator D which has the same name and scope as a previous
1157/// declaration 'Old'. Figure out how to resolve this situation,
1158/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001159///
1160/// In C++, New and Old must be declarations that are not
1161/// overloaded. Use IsOverload to determine whether New and Old are
1162/// overloaded, and to select the Old declaration that New should be
1163/// merged with.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001164///
1165/// Returns true if there was an error, false otherwise.
1166bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +00001167 // Verify the old decl was also a function.
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001168 FunctionDecl *Old = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001169 if (FunctionTemplateDecl *OldFunctionTemplate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001170 = dyn_cast<FunctionTemplateDecl>(OldD))
1171 Old = OldFunctionTemplate->getTemplatedDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001172 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001173 Old = dyn_cast<FunctionDecl>(OldD);
Chris Lattnerc511efb2007-01-27 19:32:14 +00001174 if (!Old) {
John McCalle29c5cd2009-12-10 19:51:03 +00001175 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
1176 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
1177 Diag(Shadow->getTargetDecl()->getLocation(),
1178 diag::note_using_decl_target);
1179 Diag(Shadow->getUsingDecl()->getLocation(),
1180 diag::note_using_decl) << 0;
1181 return true;
1182 }
1183
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00001184 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001185 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001186 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001187 return true;
Chris Lattnerc511efb2007-01-27 19:32:14 +00001188 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001189
1190 // Determine whether the previous declaration was a definition,
1191 // implicit declaration, or a declaration.
1192 diag::kind PrevDiag;
1193 if (Old->isThisDeclarationADefinition())
Chris Lattner0369c572008-11-23 23:12:31 +00001194 PrevDiag = diag::note_previous_definition;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001195 else if (Old->isImplicit())
1196 PrevDiag = diag::note_previous_implicit_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00001197 else
Chris Lattner0369c572008-11-23 23:12:31 +00001198 PrevDiag = diag::note_previous_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00001199
Chris Lattnerfc4379f2008-04-06 23:10:54 +00001200 QualType OldQType = Context.getCanonicalType(Old->getType());
1201 QualType NewQType = Context.getCanonicalType(New->getType());
Mike Stump11289f42009-09-09 15:08:12 +00001202
Charles Davisfea48452010-02-18 02:00:42 +00001203 // Don't complain about this if we're in GNU89 mode and the old function
1204 // is an extern inline function.
Douglas Gregore62c0a42009-02-24 01:23:02 +00001205 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCall8e7d6562010-08-26 03:08:43 +00001206 New->getStorageClass() == SC_Static &&
1207 Old->getStorageClass() != SC_Static &&
Charles Davisfea48452010-02-18 02:00:42 +00001208 !canRedefineFunction(Old, getLangOptions())) {
Douglas Gregore62c0a42009-02-24 01:23:02 +00001209 Diag(New->getLocation(), diag::err_static_non_static)
1210 << New;
1211 Diag(Old->getLocation(), PrevDiag);
1212 return true;
1213 }
1214
John McCallcddbad02010-02-04 05:44:44 +00001215 // If a function is first declared with a calling convention, but is
1216 // later declared or defined without one, the second decl assumes the
1217 // calling convention of the first.
1218 //
1219 // For the new decl, we have to look at the NON-canonical type to tell the
1220 // difference between a function that really doesn't have a calling
1221 // convention and one that is declared cdecl. That's because in
1222 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
1223 // because it is the default calling convention.
1224 //
1225 // Note also that we DO NOT return at this point, because we still have
1226 // other tests to run.
John McCall4f5019e2010-12-19 02:44:49 +00001227 const FunctionType *OldType = cast<FunctionType>(OldQType);
John McCallcddbad02010-02-04 05:44:44 +00001228 const FunctionType *NewType = New->getType()->getAs<FunctionType>();
John McCall4f5019e2010-12-19 02:44:49 +00001229 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
1230 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
1231 bool RequiresAdjustment = false;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001232 if (OldTypeInfo.getCC() != CC_Default &&
1233 NewTypeInfo.getCC() == CC_Default) {
John McCall4f5019e2010-12-19 02:44:49 +00001234 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
1235 RequiresAdjustment = true;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001236 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
1237 NewTypeInfo.getCC())) {
John McCallcddbad02010-02-04 05:44:44 +00001238 // Calling conventions really aren't compatible, so complain.
John McCallab26cfa2010-02-05 21:31:56 +00001239 Diag(New->getLocation(), diag::err_cconv_change)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001240 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
1241 << (OldTypeInfo.getCC() == CC_Default)
1242 << (OldTypeInfo.getCC() == CC_Default ? "" :
1243 FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
John McCallab26cfa2010-02-05 21:31:56 +00001244 Diag(Old->getLocation(), diag::note_previous_declaration);
John McCallcddbad02010-02-04 05:44:44 +00001245 return true;
1246 }
1247
John McCallab26cfa2010-02-05 21:31:56 +00001248 // FIXME: diagnose the other way around?
John McCall4f5019e2010-12-19 02:44:49 +00001249 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
1250 NewTypeInfo = NewTypeInfo.withNoReturn(true);
1251 RequiresAdjustment = true;
John McCallab26cfa2010-02-05 21:31:56 +00001252 }
1253
Douglas Gregor77e274f2010-06-18 21:30:25 +00001254 // Merge regparm attribute.
John McCall4f5019e2010-12-19 02:44:49 +00001255 if (OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
1256 if (NewTypeInfo.getRegParm()) {
Douglas Gregor77e274f2010-06-18 21:30:25 +00001257 Diag(New->getLocation(), diag::err_regparm_mismatch)
1258 << NewType->getRegParmType()
1259 << OldType->getRegParmType();
1260 Diag(Old->getLocation(), diag::note_previous_declaration);
1261 return true;
1262 }
John McCall4f5019e2010-12-19 02:44:49 +00001263
1264 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
1265 RequiresAdjustment = true;
1266 }
1267
1268 if (RequiresAdjustment) {
1269 NewType = Context.adjustFunctionType(NewType, NewTypeInfo);
1270 New->setType(QualType(NewType, 0));
1271 NewQType = Context.getCanonicalType(New->getType());
Douglas Gregor77e274f2010-06-18 21:30:25 +00001272 }
1273
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001274 if (getLangOptions().CPlusPlus) {
1275 // (C++98 13.1p2):
1276 // Certain function declarations cannot be overloaded:
Mike Stump11289f42009-09-09 15:08:12 +00001277 // -- Function declarations that differ only in the return type
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001278 // cannot be overloaded.
John McCall4f5019e2010-12-19 02:44:49 +00001279 QualType OldReturnType = OldType->getResultType();
1280 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00001281 QualType ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001282 if (OldReturnType != NewReturnType) {
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00001283 if (NewReturnType->isObjCObjectPointerType()
1284 && OldReturnType->isObjCObjectPointerType())
1285 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
1286 if (ResQT.isNull()) {
Argyrios Kyrtzidis3d320862011-02-05 05:54:49 +00001287 if (New->isCXXClassMember() && New->isOutOfLine())
1288 Diag(New->getLocation(),
1289 diag::err_member_def_does_not_match_ret_type) << New;
1290 else
1291 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00001292 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1293 return true;
1294 }
1295 else
1296 NewQType = ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001297 }
1298
1299 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
John McCall43314ab2010-04-13 07:45:41 +00001300 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001301 if (OldMethod && NewMethod) {
John McCall43314ab2010-04-13 07:45:41 +00001302 // Preserve triviality.
1303 NewMethod->setTrivial(OldMethod->isTrivial());
1304
1305 bool isFriend = NewMethod->getFriendObjectKind();
1306
1307 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord()) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001308 // -- Member function declarations with the same name and the
1309 // same parameter types cannot be overloaded if any of them
1310 // is a static member function declaration.
1311 if (OldMethod->isStatic() || NewMethod->isStatic()) {
1312 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
1313 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1314 return true;
1315 }
1316
1317 // C++ [class.mem]p1:
1318 // [...] A member shall not be declared twice in the
1319 // member-specification, except that a nested class or member
1320 // class template can be declared and then later defined.
1321 unsigned NewDiag;
1322 if (isa<CXXConstructorDecl>(OldMethod))
1323 NewDiag = diag::err_constructor_redeclared;
1324 else if (isa<CXXDestructorDecl>(NewMethod))
1325 NewDiag = diag::err_destructor_redeclared;
1326 else if (isa<CXXConversionDecl>(NewMethod))
1327 NewDiag = diag::err_conv_function_redeclared;
1328 else
1329 NewDiag = diag::err_member_redeclared;
1330
1331 Diag(New->getLocation(), NewDiag);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001332 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
John McCall43314ab2010-04-13 07:45:41 +00001333
1334 // Complain if this is an explicit declaration of a special
1335 // member that was initially declared implicitly.
1336 //
1337 // As an exception, it's okay to befriend such methods in order
1338 // to permit the implicit constructor/destructor/operator calls.
1339 } else if (OldMethod->isImplicit()) {
1340 if (isFriend) {
1341 NewMethod->setImplicit();
1342 } else {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001343 Diag(NewMethod->getLocation(),
1344 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson05bf0092010-04-22 05:40:53 +00001345 << New << getSpecialMember(OldMethod);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001346 return true;
1347 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001348 }
1349 }
1350
1351 // (C++98 8.3.5p3):
1352 // All declarations for a function shall agree exactly in both the
1353 // return type and the parameter-type-list.
John McCall4f5019e2010-12-19 02:44:49 +00001354 // We also want to respect all the extended bits except noreturn.
1355
1356 // noreturn should now match unless the old type info didn't have it.
1357 QualType OldQTypeForComparison = OldQType;
1358 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
1359 assert(OldQType == QualType(OldType, 0));
1360 const FunctionType *OldTypeForComparison
1361 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
1362 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
1363 assert(OldQTypeForComparison.isCanonical());
1364 }
1365
1366 if (OldQTypeForComparison == NewQType)
Douglas Gregore62c0a42009-02-24 01:23:02 +00001367 return MergeCompatibleFunctionDecls(New, Old);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001368
1369 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor89f238c2008-04-21 02:02:58 +00001370 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001371
1372 // C: Function types need to be compatible, not identical. This handles
Steve Naroff012484d2008-01-14 20:51:29 +00001373 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001374 if (!getLangOptions().CPlusPlus &&
Eli Friedman47f77112008-08-22 00:56:42 +00001375 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall9dd450b2009-09-21 23:43:11 +00001376 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
1377 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001378 const FunctionProtoType *OldProto = 0;
1379 if (isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregora74a2972009-03-06 22:43:54 +00001380 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregorbcbf8632009-02-16 18:20:44 +00001381 // The old declaration provided a function prototype, but the
1382 // new declaration does not. Merge in the prototype.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001383 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Douglas Gregorbcbf8632009-02-16 18:20:44 +00001384 llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
1385 OldProto->arg_type_end());
1386 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
Jay Foad7d0479f2009-05-21 09:52:38 +00001387 ParamTypes.data(), ParamTypes.size(),
John McCalldb40c7f2010-12-14 08:05:40 +00001388 OldProto->getExtProtoInfo());
Douglas Gregorbcbf8632009-02-16 18:20:44 +00001389 New->setType(NewQType);
Anders Carlssone0dd1d52009-05-14 21:46:00 +00001390 New->setHasInheritedPrototype();
Douglas Gregorbfdd6072009-02-16 20:58:07 +00001391
1392 // Synthesize a parameter for each argument type.
1393 llvm::SmallVector<ParmVarDecl*, 16> Params;
Mike Stump11289f42009-09-09 15:08:12 +00001394 for (FunctionProtoType::arg_type_iterator
1395 ParamType = OldProto->arg_type_begin(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00001396 ParamEnd = OldProto->arg_type_end();
1397 ParamType != ParamEnd; ++ParamType) {
1398 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001399 SourceLocation(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00001400 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00001401 *ParamType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00001402 SC_None, SC_None,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001403 0);
Douglas Gregorbfdd6072009-02-16 20:58:07 +00001404 Param->setImplicit();
1405 Params.push_back(Param);
1406 }
1407
Douglas Gregord5058122010-02-11 01:19:42 +00001408 New->setParams(Params.data(), Params.size());
Mike Stump11289f42009-09-09 15:08:12 +00001409 }
Douglas Gregorbcbf8632009-02-16 18:20:44 +00001410
Douglas Gregore62c0a42009-02-24 01:23:02 +00001411 return MergeCompatibleFunctionDecls(New, Old);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001412 }
Chris Lattner45d561a2007-11-06 06:07:26 +00001413
Douglas Gregora74a2972009-03-06 22:43:54 +00001414 // GNU C permits a K&R definition to follow a prototype declaration
1415 // if the declared types of the parameters in the K&R definition
1416 // match the types in the prototype declaration, even when the
1417 // promoted types of the parameters from the K&R definition differ
1418 // from the types in the prototype. GCC then keeps the types from
1419 // the prototype.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001420 //
1421 // If a variadic prototype is followed by a non-variadic K&R definition,
1422 // the K&R definition becomes variadic. This is sort of an edge case, but
1423 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
1424 // C99 6.9.1p8.
Douglas Gregora74a2972009-03-06 22:43:54 +00001425 if (!getLangOptions().CPlusPlus &&
Douglas Gregora74a2972009-03-06 22:43:54 +00001426 Old->hasPrototype() && !New->hasPrototype() &&
John McCall9dd450b2009-09-21 23:43:11 +00001427 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregora74a2972009-03-06 22:43:54 +00001428 Old->getNumParams() == New->getNumParams()) {
1429 llvm::SmallVector<QualType, 16> ArgTypes;
1430 llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump11289f42009-09-09 15:08:12 +00001431 const FunctionProtoType *OldProto
John McCall9dd450b2009-09-21 23:43:11 +00001432 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00001433 const FunctionProtoType *NewProto
John McCall9dd450b2009-09-21 23:43:11 +00001434 = New->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00001435
Douglas Gregora74a2972009-03-06 22:43:54 +00001436 // Determine whether this is the GNU C extension.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001437 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
1438 NewProto->getResultType());
1439 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump11289f42009-09-09 15:08:12 +00001440 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001441 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregora74a2972009-03-06 22:43:54 +00001442 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
1443 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump11289f42009-09-09 15:08:12 +00001444 if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregora74a2972009-03-06 22:43:54 +00001445 NewProto->getArgType(Idx))) {
1446 ArgTypes.push_back(NewParm->getType());
1447 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor17ea3f52010-07-29 15:18:02 +00001448 NewParm->getType(),
1449 /*CompareUnqualified=*/true)) {
Mike Stump11289f42009-09-09 15:08:12 +00001450 GNUCompatibleParamWarning Warn
Douglas Gregora74a2972009-03-06 22:43:54 +00001451 = { OldParm, NewParm, NewProto->getArgType(Idx) };
1452 Warnings.push_back(Warn);
1453 ArgTypes.push_back(NewParm->getType());
1454 } else
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001455 LooseCompatible = false;
Douglas Gregora74a2972009-03-06 22:43:54 +00001456 }
1457
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001458 if (LooseCompatible) {
Douglas Gregora74a2972009-03-06 22:43:54 +00001459 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
1460 Diag(Warnings[Warn].NewParm->getLocation(),
1461 diag::ext_param_promoted_not_compatible_with_prototype)
1462 << Warnings[Warn].PromotedType
1463 << Warnings[Warn].OldParm->getType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00001464 if (Warnings[Warn].OldParm->getLocation().isValid())
1465 Diag(Warnings[Warn].OldParm->getLocation(),
1466 diag::note_previous_declaration);
Douglas Gregora74a2972009-03-06 22:43:54 +00001467 }
1468
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001469 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
1470 ArgTypes.size(),
John McCalldb40c7f2010-12-14 08:05:40 +00001471 OldProto->getExtProtoInfo()));
Douglas Gregora74a2972009-03-06 22:43:54 +00001472 return MergeCompatibleFunctionDecls(New, Old);
1473 }
1474
1475 // Fall through to diagnose conflicting types.
1476 }
1477
Steve Naroff17832a42008-01-16 15:01:34 +00001478 // A function that has already been declared has been redeclared or defined
1479 // with a different type- show appropriate diagnostic
Douglas Gregor15fc9562009-09-12 00:22:50 +00001480 if (unsigned BuiltinID = Old->getBuiltinID()) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001481 // The user has declared a builtin function with an incompatible
1482 // signature.
1483 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
1484 // The function the user is redeclaring is a library-defined
1485 // function like 'malloc' or 'printf'. Warn about the
Douglas Gregor893c2c92009-03-23 17:47:24 +00001486 // redeclaration, then pretend that we don't know about this
1487 // library built-in.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001488 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
1489 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
1490 << Old << Old->getType();
Douglas Gregor893c2c92009-03-23 17:47:24 +00001491 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
1492 Old->setInvalidDecl();
1493 return false;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001494 }
Steve Naroff17832a42008-01-16 15:01:34 +00001495
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001496 PrevDiag = diag::note_previous_builtin_declaration;
1497 }
1498
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001499 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001500 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001501 return true;
Chris Lattner01564d92007-01-27 19:27:06 +00001502}
1503
Douglas Gregore62c0a42009-02-24 01:23:02 +00001504/// \brief Completes the merge of two function declarations that are
Mike Stump11289f42009-09-09 15:08:12 +00001505/// known to be compatible.
Douglas Gregore62c0a42009-02-24 01:23:02 +00001506///
1507/// This routine handles the merging of attributes and other
1508/// properties of function declarations form the old declaration to
1509/// the new declaration, once we know that New is in fact a
1510/// redeclaration of Old.
1511///
1512/// \returns false
1513bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
1514 // Merge the attributes
John McCallf79e87d2011-03-02 04:00:57 +00001515 mergeDeclAttributes(New, Old, Context);
Douglas Gregore62c0a42009-02-24 01:23:02 +00001516
1517 // Merge the storage class.
John McCall8e7d6562010-08-26 03:08:43 +00001518 if (Old->getStorageClass() != SC_Extern &&
1519 Old->getStorageClass() != SC_None)
Douglas Gregor76fe50c2009-04-28 06:37:30 +00001520 New->setStorageClass(Old->getStorageClass());
Douglas Gregore62c0a42009-02-24 01:23:02 +00001521
Douglas Gregore62c0a42009-02-24 01:23:02 +00001522 // Merge "pure" flag.
1523 if (Old->isPure())
1524 New->setPure();
1525
1526 // Merge the "deleted" flag.
1527 if (Old->isDeleted())
1528 New->setDeleted();
Mike Stump11289f42009-09-09 15:08:12 +00001529
John McCallf79e87d2011-03-02 04:00:57 +00001530 // Merge attributes from the parameters. These can mismatch with K&R
1531 // declarations.
1532 if (New->getNumParams() == Old->getNumParams())
1533 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
1534 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
1535 Context);
1536
Douglas Gregore62c0a42009-02-24 01:23:02 +00001537 if (getLangOptions().CPlusPlus)
1538 return MergeCXXFunctionDecl(New, Old);
1539
1540 return false;
1541}
1542
John McCallf79e87d2011-03-02 04:00:57 +00001543void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
1544 const ObjCMethodDecl *oldMethod) {
1545 // Merge the attributes.
1546 mergeDeclAttributes(newMethod, oldMethod, Context);
1547
1548 // Merge attributes from the parameters.
1549 for (ObjCMethodDecl::param_iterator oi = oldMethod->param_begin(),
1550 ni = newMethod->param_begin(), ne = newMethod->param_end();
1551 ni != ne; ++ni, ++oi)
1552 mergeParamDeclAttributes(*ni, *oi, Context);
1553}
1554
Richard Smith30482bc2011-02-20 03:19:35 +00001555/// MergeVarDecl - We parsed a variable 'New' which has the same name and scope
1556/// as a previous declaration 'Old'. Figure out how to merge their types,
1557/// emitting diagnostics as appropriate.
1558///
1559/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
1560/// to here in AddInitializerToDecl and AddCXXDirectInitializerToDecl. We can't
1561/// check them before the initializer is attached.
1562///
1563void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) {
1564 if (New->isInvalidDecl() || Old->isInvalidDecl())
1565 return;
1566
1567 QualType MergedT;
1568 if (getLangOptions().CPlusPlus) {
1569 AutoType *AT = New->getType()->getContainedAutoType();
1570 if (AT && !AT->isDeduced()) {
1571 // We don't know what the new type is until the initializer is attached.
1572 return;
1573 } else if (Context.hasSameType(New->getType(), Old->getType()))
1574 return;
1575 // C++ [basic.link]p10:
1576 // [...] the types specified by all declarations referring to a given
1577 // object or function shall be identical, except that declarations for an
1578 // array object can specify array types that differ by the presence or
1579 // absence of a major array bound (8.3.4).
1580 else if (Old->getType()->isIncompleteArrayType() &&
1581 New->getType()->isArrayType()) {
1582 CanQual<ArrayType> OldArray
1583 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1584 CanQual<ArrayType> NewArray
1585 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1586 if (OldArray->getElementType() == NewArray->getElementType())
1587 MergedT = New->getType();
1588 } else if (Old->getType()->isArrayType() &&
1589 New->getType()->isIncompleteArrayType()) {
1590 CanQual<ArrayType> OldArray
1591 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1592 CanQual<ArrayType> NewArray
1593 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1594 if (OldArray->getElementType() == NewArray->getElementType())
1595 MergedT = Old->getType();
1596 } else if (New->getType()->isObjCObjectPointerType()
1597 && Old->getType()->isObjCObjectPointerType()) {
1598 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
1599 Old->getType());
1600 }
1601 } else {
1602 MergedT = Context.mergeTypes(New->getType(), Old->getType());
1603 }
1604 if (MergedT.isNull()) {
1605 Diag(New->getLocation(), diag::err_redefinition_different_type)
1606 << New->getDeclName();
1607 Diag(Old->getLocation(), diag::note_previous_definition);
1608 return New->setInvalidDecl();
1609 }
1610 New->setType(MergedT);
1611}
1612
Chris Lattner01564d92007-01-27 19:27:06 +00001613/// MergeVarDecl - We just parsed a variable 'New' which has the same name
1614/// and scope as a previous declaration 'Old'. Figure out how to resolve this
1615/// situation, merging decls or emitting diagnostics as appropriate.
1616///
Mike Stump11289f42009-09-09 15:08:12 +00001617/// Tentative definition rules (C99 6.9.2p2) are checked by
1618/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroff5bb8f222008-08-08 17:50:35 +00001619/// definitions here, since the initializer hasn't been attached.
Mike Stump11289f42009-09-09 15:08:12 +00001620///
John McCall1f82f242009-11-18 22:49:29 +00001621void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
1622 // If the new decl is already invalid, don't do any other checking.
1623 if (New->isInvalidDecl())
1624 return;
Mike Stump11289f42009-09-09 15:08:12 +00001625
Chris Lattnerc511efb2007-01-27 19:32:14 +00001626 // Verify the old decl was also a variable.
John McCall1f82f242009-11-18 22:49:29 +00001627 VarDecl *Old = 0;
1628 if (!Previous.isSingleResult() ||
1629 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
Chris Lattner651d42d2008-11-20 06:38:18 +00001630 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001631 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00001632 Diag(Previous.getRepresentativeDecl()->getLocation(),
1633 diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001634 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00001635 }
Chris Lattner84966392008-03-03 03:28:21 +00001636
Douglas Gregor2c7d9292010-08-30 14:32:14 +00001637 // C++ [class.mem]p1:
1638 // A member shall not be declared twice in the member-specification [...]
1639 //
1640 // Here, we need only consider static data members.
1641 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
1642 Diag(New->getLocation(), diag::err_duplicate_member)
1643 << New->getIdentifier();
1644 Diag(Old->getLocation(), diag::note_previous_declaration);
1645 New->setInvalidDecl();
1646 }
1647
John McCallf79e87d2011-03-02 04:00:57 +00001648 mergeDeclAttributes(New, Old, Context);
Chris Lattner84966392008-03-03 03:28:21 +00001649
Richard Smith30482bc2011-02-20 03:19:35 +00001650 // Merge the types.
1651 MergeVarDeclTypes(New, Old);
1652 if (New->isInvalidDecl())
1653 return;
Douglas Gregor04e9a032009-03-11 23:52:16 +00001654
Steve Naroff1e787362008-01-30 00:44:01 +00001655 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
John McCall8e7d6562010-08-26 03:08:43 +00001656 if (New->getStorageClass() == SC_Static &&
1657 (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001658 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001659 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001660 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00001661 }
Mike Stump11289f42009-09-09 15:08:12 +00001662 // C99 6.2.2p4:
Douglas Gregor37311622009-03-19 22:01:50 +00001663 // For an identifier declared with the storage-class specifier
1664 // extern in a scope in which a prior declaration of that
1665 // identifier is visible,23) if the prior declaration specifies
1666 // internal or external linkage, the linkage of the identifier at
1667 // the later declaration is the same as the linkage specified at
1668 // the prior declaration. If no prior declaration is visible, or
1669 // if the prior declaration specifies no linkage, then the
1670 // identifier has external linkage.
Douglas Gregord4eca012009-03-23 16:17:01 +00001671 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor37311622009-03-19 22:01:50 +00001672 /* Okay */;
John McCall8e7d6562010-08-26 03:08:43 +00001673 else if (New->getStorageClass() != SC_Static &&
1674 Old->getStorageClass() == SC_Static) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001675 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001676 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001677 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00001678 }
Daniel Dunbar0ca16602009-04-14 02:25:56 +00001679
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00001680 // Check if extern is followed by non-extern and vice-versa.
1681 if (New->hasExternalStorage() &&
1682 !Old->hasLinkage() && Old->isLocalVarDecl()) {
1683 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
1684 Diag(Old->getLocation(), diag::note_previous_definition);
1685 return New->setInvalidDecl();
1686 }
1687 if (Old->hasExternalStorage() &&
1688 !New->hasLinkage() && New->isLocalVarDecl()) {
1689 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
1690 Diag(Old->getLocation(), diag::note_previous_definition);
1691 return New->setInvalidDecl();
1692 }
1693
Steve Naroffa5629372008-09-17 14:05:40 +00001694 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump11289f42009-09-09 15:08:12 +00001695
Daniel Dunbar0ca16602009-04-14 02:25:56 +00001696 // FIXME: The test for external storage here seems wrong? We still
1697 // need to check for mismatches.
1698 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor04e9a032009-03-11 23:52:16 +00001699 // Don't complain about out-of-line definitions of static members.
1700 !(Old->getLexicalDeclContext()->isRecord() &&
1701 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattnere3d20d92008-11-23 21:45:46 +00001702 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001703 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001704 return New->setInvalidDecl();
Steve Naroff6fbf0dc2007-03-16 00:33:25 +00001705 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00001706
Eli Friedmand5c0eed2009-04-19 20:27:55 +00001707 if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
1708 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
1709 Diag(Old->getLocation(), diag::note_previous_definition);
1710 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
1711 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
1712 Diag(Old->getLocation(), diag::note_previous_definition);
1713 }
1714
Sebastian Redlf1842912010-02-02 18:35:11 +00001715 // C++ doesn't have tentative definitions, so go right ahead and check here.
1716 const VarDecl *Def;
Sebastian Redld85be0c2010-02-03 02:08:48 +00001717 if (getLangOptions().CPlusPlus &&
1718 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redlf1842912010-02-02 18:35:11 +00001719 (Def = Old->getDefinition())) {
1720 Diag(New->getLocation(), diag::err_redefinition)
1721 << New->getDeclName();
1722 Diag(Def->getLocation(), diag::note_previous_definition);
1723 New->setInvalidDecl();
1724 return;
1725 }
Fariborz Jahanianad356a12010-06-25 00:05:45 +00001726 // c99 6.2.2 P4.
1727 // For an identifier declared with the storage-class specifier extern in a
1728 // scope in which a prior declaration of that identifier is visible, if
1729 // the prior declaration specifies internal or external linkage, the linkage
1730 // of the identifier at the later declaration is the same as the linkage
1731 // specified at the prior declaration.
1732 // FIXME. revisit this code.
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00001733 if (New->hasExternalStorage() &&
Fariborz Jahanian4f9c9d62010-06-24 18:50:41 +00001734 Old->getLinkage() == InternalLinkage &&
1735 New->getDeclContext() == Old->getDeclContext())
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00001736 New->setStorageClass(Old->getStorageClass());
1737
Douglas Gregor0760fa12009-03-10 23:43:53 +00001738 // Keep a chain of previous declarations.
1739 New->setPreviousDeclaration(Old);
John McCall401982f2010-01-20 21:53:11 +00001740
1741 // Inherit access appropriately.
1742 New->setAccess(Old->getAccess());
Chris Lattner01564d92007-01-27 19:27:06 +00001743}
1744
Chris Lattnerb6738ec2007-01-28 00:38:24 +00001745/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
1746/// no declarator (e.g. "struct foo;") is parsed.
John McCall48871652010-08-21 09:40:31 +00001747Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
1748 DeclSpec &DS) {
Eli Friedman32e6e8e2009-04-09 21:26:42 +00001749 // FIXME: Error on inline/virtual/explicit
Eli Friedmand5c0eed2009-04-19 20:27:55 +00001750 // FIXME: Warn on useless __thread
Eli Friedman32e6e8e2009-04-09 21:26:42 +00001751 // FIXME: Warn on useless const/volatile
1752 // FIXME: Warn on useless static/extern/typedef/private_extern/mutable
1753 // FIXME: Warn on useless attributes
John McCallc3987482009-10-07 23:34:25 +00001754 Decl *TagD = 0;
Douglas Gregor9817f4a2009-02-09 15:09:02 +00001755 TagDecl *Tag = 0;
1756 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
1757 DS.getTypeSpecType() == DeclSpec::TST_struct ||
1758 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001759 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallba7bf592010-08-24 05:47:05 +00001760 TagD = DS.getRepAsDecl();
John McCallc3987482009-10-07 23:34:25 +00001761
1762 if (!TagD) // We probably had an error
John McCall48871652010-08-21 09:40:31 +00001763 return 0;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001764
John McCall07e91c02009-08-06 02:15:43 +00001765 // Note that the above type specs guarantee that the
1766 // type rep is a Decl, whereas in many of the others
1767 // it's a Type.
John McCallc3987482009-10-07 23:34:25 +00001768 Tag = dyn_cast<TagDecl>(TagD);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001769 }
Douglas Gregor9817f4a2009-02-09 15:09:02 +00001770
Nuno Lopese9823fa2009-12-17 11:35:26 +00001771 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1772 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
1773 // or incomplete types shall not be restrict-qualified."
1774 if (TypeQuals & DeclSpec::TQ_restrict)
1775 Diag(DS.getRestrictSpecLoc(),
1776 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
1777 << DS.getSourceRange();
1778 }
1779
Douglas Gregor3dad8422009-09-26 06:47:28 +00001780 if (DS.isFriendSpecified()) {
John McCallace48cd2010-10-19 01:40:49 +00001781 // If we're dealing with a decl but not a TagDecl, assume that
1782 // whatever routines created it handled the friendship aspect.
1783 if (TagD && !Tag)
John McCall48871652010-08-21 09:40:31 +00001784 return 0;
John McCallc3987482009-10-07 23:34:25 +00001785 return ActOnFriendTypeDecl(S, DS, MultiTemplateParamsArg(*this, 0, 0));
Douglas Gregor3dad8422009-09-26 06:47:28 +00001786 }
1787
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00001788 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCall53fa7142010-12-24 02:08:15 +00001789 ProcessDeclAttributeList(S, Record, DS.getAttributes().getList());
Chris Lattnerecf328e2009-10-25 22:21:57 +00001790
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00001791 if (!Record->getDeclName() && Record->isDefinition() &&
Douglas Gregor2e7cba62009-03-06 23:06:59 +00001792 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
1793 if (getLangOptions().CPlusPlus ||
1794 Record->getDeclContext()->isRecord())
John McCallb54367d2010-05-21 20:45:30 +00001795 return BuildAnonymousStructOrUnion(S, DS, AS, Record);
Douglas Gregor2e7cba62009-03-06 23:06:59 +00001796
Douglas Gregorf19ac0e2010-04-08 21:33:23 +00001797 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
Douglas Gregor2e7cba62009-03-06 23:06:59 +00001798 << DS.getSourceRange();
1799 }
Francois Pichet0c71f6c2010-11-23 06:07:27 +00001800 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00001801
Francois Pichet0c71f6c2010-11-23 06:07:27 +00001802 // Check for Microsoft C extension: anonymous struct.
1803 if (getLangOptions().Microsoft && !getLangOptions().CPlusPlus &&
1804 CurContext->isRecord() &&
1805 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
1806 // Handle 2 kinds of anonymous struct:
1807 // struct STRUCT;
1808 // and
1809 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
1810 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
1811 if ((Record && Record->getDeclName() && !Record->isDefinition()) ||
1812 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
1813 DS.getRepAsType().get()->isStructureType())) {
1814 Diag(DS.getSourceRange().getBegin(), diag::ext_ms_anonymous_struct)
1815 << DS.getSourceRange();
1816 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
1817 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00001818 }
Douglas Gregor3dad8422009-09-26 06:47:28 +00001819
Douglas Gregoraa8c9722010-07-13 06:24:26 +00001820 if (getLangOptions().CPlusPlus &&
1821 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
1822 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
1823 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
1824 !Enum->getIdentifier() && !Enum->isInvalidDecl())
1825 Diag(Enum->getLocation(), diag::ext_no_declarators)
1826 << DS.getSourceRange();
1827
Mike Stump11289f42009-09-09 15:08:12 +00001828 if (!DS.isMissingDeclaratorOk() &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00001829 DS.getTypeSpecType() != DeclSpec::TST_error) {
Douglas Gregor2d9dde0e2009-01-22 16:23:54 +00001830 // Warn about typedefs of enums without names, since this is an
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00001831 // extension in both Microsoft and GNU.
Douglas Gregor051d8fd2009-01-17 02:55:50 +00001832 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
1833 Tag && isa<EnumDecl>(Tag)) {
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00001834 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
1835 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00001836 return Tag;
Douglas Gregor2b136fe2009-01-13 23:10:51 +00001837 }
1838
Douglas Gregorf19ac0e2010-04-08 21:33:23 +00001839 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
Sebastian Redla2b5e312008-12-28 15:28:59 +00001840 << DS.getSourceRange();
Sebastian Redla2b5e312008-12-28 15:28:59 +00001841 }
Mike Stump11289f42009-09-09 15:08:12 +00001842
John McCall48871652010-08-21 09:40:31 +00001843 return TagD;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001844}
1845
Fariborz Jahanian1db5c942010-09-28 20:42:35 +00001846/// ActOnVlaStmt - This rouine if finds a vla expression in a decl spec.
1847/// builds a statement for it and returns it so it is evaluated.
1848StmtResult Sema::ActOnVlaStmt(const DeclSpec &DS) {
1849 StmtResult R;
1850 if (DS.getTypeSpecType() == DeclSpec::TST_typeofExpr) {
1851 Expr *Exp = DS.getRepAsExpr();
1852 QualType Ty = Exp->getType();
1853 if (Ty->isPointerType()) {
1854 do
1855 Ty = Ty->getAs<PointerType>()->getPointeeType();
1856 while (Ty->isPointerType());
1857 }
1858 if (Ty->isVariableArrayType()) {
1859 R = ActOnExprStmt(MakeFullExpr(Exp));
1860 }
1861 }
1862 return R;
1863}
1864
John McCallea305ed2009-12-18 10:40:03 +00001865/// We are trying to inject an anonymous member into the given scope;
John McCall1f82f242009-11-18 22:49:29 +00001866/// check if there's an existing declaration that can't be overloaded.
1867///
1868/// \return true if this is a forbidden redeclaration
John McCallea305ed2009-12-18 10:40:03 +00001869static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
1870 Scope *S,
Fariborz Jahanian53967e22010-01-22 18:30:17 +00001871 DeclContext *Owner,
John McCallea305ed2009-12-18 10:40:03 +00001872 DeclarationName Name,
1873 SourceLocation NameLoc,
1874 unsigned diagnostic) {
1875 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
1876 Sema::ForRedeclaration);
1877 if (!SemaRef.LookupName(R, S)) return false;
John McCall1f82f242009-11-18 22:49:29 +00001878
John McCallea305ed2009-12-18 10:40:03 +00001879 if (R.getAsSingle<TagDecl>())
John McCall1f82f242009-11-18 22:49:29 +00001880 return false;
1881
1882 // Pick a representative declaration.
John McCallea305ed2009-12-18 10:40:03 +00001883 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidise619e992010-09-23 14:26:01 +00001884 assert(PrevDecl && "Expected a non-null Decl");
1885
1886 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
1887 return false;
John McCall1f82f242009-11-18 22:49:29 +00001888
John McCallea305ed2009-12-18 10:40:03 +00001889 SemaRef.Diag(NameLoc, diagnostic) << Name;
1890 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall1f82f242009-11-18 22:49:29 +00001891
1892 return true;
1893}
1894
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001895/// InjectAnonymousStructOrUnionMembers - Inject the members of the
1896/// anonymous struct or union AnonRecord into the owning context Owner
1897/// and scope S. This routine will be invoked just after we realize
1898/// that an unnamed union or struct is actually an anonymous union or
1899/// struct, e.g.,
1900///
1901/// @code
1902/// union {
1903/// int i;
1904/// float f;
1905/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
1906/// // f into the surrounding scope.x
1907/// @endcode
1908///
1909/// This routine is recursive, injecting the names of nested anonymous
1910/// structs/unions into the owning context and scope as well.
John McCallb54367d2010-05-21 20:45:30 +00001911static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
1912 DeclContext *Owner,
1913 RecordDecl *AnonRecord,
Francois Pichet783dd6e2010-11-21 06:08:52 +00001914 AccessSpecifier AS,
Francois Pichet0c71f6c2010-11-23 06:07:27 +00001915 llvm::SmallVector<NamedDecl*, 2> &Chaining,
1916 bool MSAnonStruct) {
John McCall1f82f242009-11-18 22:49:29 +00001917 unsigned diagKind
1918 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
1919 : diag::err_anonymous_struct_member_redecl;
1920
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001921 bool Invalid = false;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00001922
1923 // Look every FieldDecl and IndirectFieldDecl with a name.
1924 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
1925 DEnd = AnonRecord->decls_end();
1926 D != DEnd; ++D) {
1927 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
1928 cast<NamedDecl>(*D)->getDeclName()) {
1929 ValueDecl *VD = cast<ValueDecl>(*D);
1930 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
1931 VD->getLocation(), diagKind)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001932 // C++ [class.union]p2:
1933 // The names of the members of an anonymous union shall be
1934 // distinct from the names of any other entity in the
1935 // scope in which the anonymous union is declared.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001936 Invalid = true;
1937 } else {
1938 // C++ [class.union]p2:
1939 // For the purpose of name lookup, after the anonymous union
1940 // definition, the members of the anonymous union are
1941 // considered to have been defined in the scope in which the
1942 // anonymous union is declared.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00001943 unsigned OldChainingSize = Chaining.size();
1944 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
1945 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
1946 PE = IF->chain_end(); PI != PE; ++PI)
1947 Chaining.push_back(*PI);
1948 else
1949 Chaining.push_back(VD);
1950
Francois Pichet783dd6e2010-11-21 06:08:52 +00001951 assert(Chaining.size() >= 2);
1952 NamedDecl **NamedChain =
1953 new (SemaRef.Context)NamedDecl*[Chaining.size()];
1954 for (unsigned i = 0; i < Chaining.size(); i++)
1955 NamedChain[i] = Chaining[i];
1956
1957 IndirectFieldDecl* IndirectField =
Francois Pichet0c71f6c2010-11-23 06:07:27 +00001958 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
1959 VD->getIdentifier(), VD->getType(),
Francois Pichet783dd6e2010-11-21 06:08:52 +00001960 NamedChain, Chaining.size());
1961
1962 IndirectField->setAccess(AS);
1963 IndirectField->setImplicit();
1964 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallb54367d2010-05-21 20:45:30 +00001965
1966 // That includes picking up the appropriate access specifier.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00001967 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001968
Francois Pichet0c71f6c2010-11-23 06:07:27 +00001969 Chaining.resize(OldChainingSize);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001970 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001971 }
1972 }
1973
1974 return Invalid;
1975}
1976
Douglas Gregorc4df4072010-04-19 22:54:31 +00001977/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
1978/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCall8e7d6562010-08-26 03:08:43 +00001979/// illegal input values are mapped to SC_None.
1980static StorageClass
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00001981StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
Douglas Gregorc4df4072010-04-19 22:54:31 +00001982 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00001983 case DeclSpec::SCS_unspecified: return SC_None;
1984 case DeclSpec::SCS_extern: return SC_Extern;
1985 case DeclSpec::SCS_static: return SC_Static;
1986 case DeclSpec::SCS_auto: return SC_Auto;
1987 case DeclSpec::SCS_register: return SC_Register;
1988 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00001989 // Illegal SCSs map to None: error reporting is up to the caller.
1990 case DeclSpec::SCS_mutable: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00001991 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00001992 }
1993 llvm_unreachable("unknown storage class specifier");
1994}
1995
1996/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
John McCall8e7d6562010-08-26 03:08:43 +00001997/// a StorageClass. Any error reporting is up to the caller:
1998/// illegal input values are mapped to SC_None.
1999static StorageClass
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00002000StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
Douglas Gregorc4df4072010-04-19 22:54:31 +00002001 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00002002 case DeclSpec::SCS_unspecified: return SC_None;
2003 case DeclSpec::SCS_extern: return SC_Extern;
2004 case DeclSpec::SCS_static: return SC_Static;
2005 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002006 // Illegal SCSs map to None: error reporting is up to the caller.
2007 case DeclSpec::SCS_auto: // Fall through.
2008 case DeclSpec::SCS_mutable: // Fall through.
2009 case DeclSpec::SCS_register: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00002010 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002011 }
2012 llvm_unreachable("unknown storage class specifier");
2013}
2014
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002015/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002016/// anonymous structure or union. Anonymous unions are a C++ feature
2017/// (C++ [class.union]) and a GNU C extension; anonymous structures
Mike Stump11289f42009-09-09 15:08:12 +00002018/// are a GNU C and GNU C++ extension.
John McCall48871652010-08-21 09:40:31 +00002019Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2020 AccessSpecifier AS,
2021 RecordDecl *Record) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002022 DeclContext *Owner = Record->getDeclContext();
2023
2024 // Diagnose whether this anonymous struct/union is an extension.
2025 if (Record->isUnion() && !getLangOptions().CPlusPlus)
2026 Diag(Record->getLocation(), diag::ext_anonymous_union);
2027 else if (!Record->isUnion())
2028 Diag(Record->getLocation(), diag::ext_anonymous_struct);
Mike Stump11289f42009-09-09 15:08:12 +00002029
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002030 // C and C++ require different kinds of checks for anonymous
2031 // structs/unions.
2032 bool Invalid = false;
2033 if (getLangOptions().CPlusPlus) {
2034 const char* PrevSpec = 0;
John McCall49bfce42009-08-03 20:12:06 +00002035 unsigned DiagID;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002036 // C++ [class.union]p3:
2037 // Anonymous unions declared in a named namespace or in the
2038 // global namespace shall be declared static.
2039 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
2040 (isa<TranslationUnitDecl>(Owner) ||
Mike Stump11289f42009-09-09 15:08:12 +00002041 (isa<NamespaceDecl>(Owner) &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002042 cast<NamespaceDecl>(Owner)->getDeclName()))) {
2043 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
2044 Invalid = true;
2045
2046 // Recover by adding 'static'.
John McCall49bfce42009-08-03 20:12:06 +00002047 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(),
Peter Collingbournede32b202011-02-11 19:59:54 +00002048 PrevSpec, DiagID, getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +00002049 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002050 // C++ [class.union]p3:
2051 // A storage class is not allowed in a declaration of an
2052 // anonymous union in a class scope.
2053 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
2054 isa<RecordDecl>(Owner)) {
Mike Stump11289f42009-09-09 15:08:12 +00002055 Diag(DS.getStorageClassSpecLoc(),
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002056 diag::err_anonymous_union_with_storage_spec);
2057 Invalid = true;
2058
2059 // Recover by removing the storage specifier.
2060 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
Peter Collingbournede32b202011-02-11 19:59:54 +00002061 PrevSpec, DiagID, getLangOptions());
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002062 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00002063
Mike Stump11289f42009-09-09 15:08:12 +00002064 // C++ [class.union]p2:
Douglas Gregorf4d33272009-01-07 19:46:03 +00002065 // The member-specification of an anonymous union shall only
2066 // define non-static data members. [Note: nested types and
2067 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002068 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
2069 MemEnd = Record->decls_end();
Douglas Gregorf4d33272009-01-07 19:46:03 +00002070 Mem != MemEnd; ++Mem) {
2071 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
2072 // C++ [class.union]p3:
2073 // An anonymous union shall not have private or protected
2074 // members (clause 11).
John McCallb54367d2010-05-21 20:45:30 +00002075 assert(FD->getAccess() != AS_none);
2076 if (FD->getAccess() != AS_public) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00002077 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
2078 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
2079 Invalid = true;
2080 }
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00002081
2082 if (CheckNontrivialField(FD))
2083 Invalid = true;
Douglas Gregorf4d33272009-01-07 19:46:03 +00002084 } else if ((*Mem)->isImplicit()) {
2085 // Any implicit members are fine.
Douglas Gregor8761da52009-02-03 00:34:39 +00002086 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
2087 // This is a type that showed up in an
2088 // elaborated-type-specifier inside the anonymous struct or
2089 // union, but which actually declares a type outside of the
2090 // anonymous struct or union. It's okay.
Douglas Gregorf4d33272009-01-07 19:46:03 +00002091 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
2092 if (!MemRecord->isAnonymousStructOrUnion() &&
2093 MemRecord->getDeclName()) {
Francois Pichet4ad4b582010-09-08 11:32:25 +00002094 // Visual C++ allows type definition in anonymous struct or union.
2095 if (getLangOptions().Microsoft)
2096 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
2097 << (int)Record->isUnion();
2098 else {
2099 // This is a nested type declaration.
2100 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
2101 << (int)Record->isUnion();
2102 Invalid = true;
2103 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00002104 }
Abramo Bagnarad7340582010-06-05 05:09:32 +00002105 } else if (isa<AccessSpecDecl>(*Mem)) {
2106 // Any access specifier is fine.
Douglas Gregorf4d33272009-01-07 19:46:03 +00002107 } else {
2108 // We have something that isn't a non-static data
2109 // member. Complain about it.
2110 unsigned DK = diag::err_anonymous_record_bad_member;
2111 if (isa<TypeDecl>(*Mem))
2112 DK = diag::err_anonymous_record_with_type;
2113 else if (isa<FunctionDecl>(*Mem))
2114 DK = diag::err_anonymous_record_with_function;
2115 else if (isa<VarDecl>(*Mem))
2116 DK = diag::err_anonymous_record_with_static;
Francois Pichet4ad4b582010-09-08 11:32:25 +00002117
2118 // Visual C++ allows type definition in anonymous struct or union.
2119 if (getLangOptions().Microsoft &&
2120 DK == diag::err_anonymous_record_with_type)
2121 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregorf4d33272009-01-07 19:46:03 +00002122 << (int)Record->isUnion();
Francois Pichet4ad4b582010-09-08 11:32:25 +00002123 else {
2124 Diag((*Mem)->getLocation(), DK)
2125 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00002126 Invalid = true;
Francois Pichet4ad4b582010-09-08 11:32:25 +00002127 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00002128 }
2129 }
Mike Stump11289f42009-09-09 15:08:12 +00002130 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002131
2132 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002133 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
2134 << (int)getLangOptions().CPlusPlus;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002135 Invalid = true;
2136 }
2137
John McCallfa2d6922009-10-22 23:31:08 +00002138 // Mock up a declarator.
2139 Declarator Dc(DS, Declarator::TypeNameContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00002140 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCallbcd03502009-12-07 02:54:59 +00002141 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCallfa2d6922009-10-22 23:31:08 +00002142
Mike Stump11289f42009-09-09 15:08:12 +00002143 // Create a declaration for this anonymous struct/union.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002144 NamedDecl *Anon = 0;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002145 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00002146 Anon = FieldDecl::Create(Context, OwningClass,
2147 DS.getSourceRange().getBegin(),
2148 Record->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002149 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00002150 Context.getTypeDeclType(Record),
John McCallbcd03502009-12-07 02:54:59 +00002151 TInfo,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00002152 /*BitWidth=*/0, /*Mutable=*/false);
John McCallb54367d2010-05-21 20:45:30 +00002153 Anon->setAccess(AS);
Douglas Gregor9d5938a2010-09-28 20:38:10 +00002154 if (getLangOptions().CPlusPlus)
Douglas Gregorf4d33272009-01-07 19:46:03 +00002155 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002156 } else {
Douglas Gregorc4df4072010-04-19 22:54:31 +00002157 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
2158 assert(SCSpec != DeclSpec::SCS_typedef &&
2159 "Parser allowed 'typedef' as storage class VarDecl.");
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00002160 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregorc4df4072010-04-19 22:54:31 +00002161 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002162 // mutable can only appear on non-static class members, so it's always
2163 // an error here
2164 Diag(Record->getLocation(), diag::err_mutable_nonmember);
2165 Invalid = true;
John McCall8e7d6562010-08-26 03:08:43 +00002166 SC = SC_None;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002167 }
Douglas Gregorc4df4072010-04-19 22:54:31 +00002168 SCSpec = DS.getStorageClassSpecAsWritten();
2169 VarDecl::StorageClass SCAsWritten
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00002170 = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002171
Abramo Bagnaradff19302011-03-08 08:55:46 +00002172 Anon = VarDecl::Create(Context, Owner,
2173 DS.getSourceRange().getBegin(),
2174 Record->getLocation(), /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00002175 Context.getTypeDeclType(Record),
Douglas Gregorc4df4072010-04-19 22:54:31 +00002176 TInfo, SC, SCAsWritten);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002177 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00002178 Anon->setImplicit();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002179
2180 // Add the anonymous struct/union object to the current
2181 // context. We'll be referencing this object when we refer to one of
2182 // its members.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002183 Owner->addDecl(Anon);
Douglas Gregor456ad1a2010-05-03 15:18:25 +00002184
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002185 // Inject the members of the anonymous struct/union into the owning
2186 // context and into the identifier resolver chain for name lookup
2187 // purposes.
Francois Pichet783dd6e2010-11-21 06:08:52 +00002188 llvm::SmallVector<NamedDecl*, 2> Chain;
2189 Chain.push_back(Anon);
2190
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002191 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
2192 Chain, false))
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002193 Invalid = true;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002194
2195 // Mark this as an anonymous struct/union type. Note that we do not
2196 // do this until after we have already checked and injected the
2197 // members of this anonymous struct/union type, because otherwise
2198 // the members could be injected twice: once by DeclContext when it
2199 // builds its lookup table, and once by
Mike Stump11289f42009-09-09 15:08:12 +00002200 // InjectAnonymousStructOrUnionMembers.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002201 Record->setAnonymousStructOrUnion(true);
2202
2203 if (Invalid)
2204 Anon->setInvalidDecl();
2205
John McCall48871652010-08-21 09:40:31 +00002206 return Anon;
Chris Lattnerb6738ec2007-01-28 00:38:24 +00002207}
2208
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002209/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
2210/// Microsoft C anonymous structure.
2211/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
2212/// Example:
2213///
2214/// struct A { int a; };
2215/// struct B { struct A; int b; };
2216///
2217/// void foo() {
2218/// B var;
2219/// var.a = 3;
2220/// }
2221///
2222Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2223 RecordDecl *Record) {
2224
2225 // If there is no Record, get the record via the typedef.
2226 if (!Record)
2227 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
2228
2229 // Mock up a declarator.
2230 Declarator Dc(DS, Declarator::TypeNameContext);
2231 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
2232 assert(TInfo && "couldn't build declarator info for anonymous struct");
2233
2234 // Create a declaration for this anonymous struct.
2235 NamedDecl* Anon = FieldDecl::Create(Context,
2236 cast<RecordDecl>(CurContext),
2237 DS.getSourceRange().getBegin(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002238 DS.getSourceRange().getBegin(),
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002239 /*IdentifierInfo=*/0,
2240 Context.getTypeDeclType(Record),
2241 TInfo,
2242 /*BitWidth=*/0, /*Mutable=*/false);
2243 Anon->setImplicit();
2244
2245 // Add the anonymous struct object to the current context.
2246 CurContext->addDecl(Anon);
2247
2248 // Inject the members of the anonymous struct into the current
2249 // context and into the identifier resolver chain for name lookup
2250 // purposes.
2251 llvm::SmallVector<NamedDecl*, 2> Chain;
2252 Chain.push_back(Anon);
2253
2254 if (InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
2255 Record->getDefinition(),
2256 AS_none, Chain, true))
2257 Anon->setInvalidDecl();
2258
2259 return Anon;
2260}
Steve Naroff2fea1392007-09-02 02:04:30 +00002261
Douglas Gregor92751d42008-11-17 22:58:34 +00002262/// GetNameForDeclarator - Determine the full declaration name for the
2263/// given Declarator.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002264DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregora121b752009-11-03 16:56:39 +00002265 return GetNameFromUnqualifiedId(D.getName());
2266}
2267
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002268/// \brief Retrieves the declaration name from a parsed unqualified-id.
2269DeclarationNameInfo
2270Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
2271 DeclarationNameInfo NameInfo;
2272 NameInfo.setLoc(Name.StartLocation);
2273
Douglas Gregor7861a802009-11-03 01:35:08 +00002274 switch (Name.getKind()) {
Alexis Hunt34458502009-11-28 04:44:28 +00002275
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002276 case UnqualifiedId::IK_Identifier:
2277 NameInfo.setName(Name.Identifier);
2278 NameInfo.setLoc(Name.StartLocation);
2279 return NameInfo;
Alexis Hunt34458502009-11-28 04:44:28 +00002280
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002281 case UnqualifiedId::IK_OperatorFunctionId:
2282 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
2283 Name.OperatorFunctionId.Operator));
2284 NameInfo.setLoc(Name.StartLocation);
2285 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
2286 = Name.OperatorFunctionId.SymbolLocations[0];
2287 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
2288 = Name.EndLocation.getRawEncoding();
2289 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002290
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002291 case UnqualifiedId::IK_LiteralOperatorId:
2292 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
2293 Name.Identifier));
2294 NameInfo.setLoc(Name.StartLocation);
2295 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
2296 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002297
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002298 case UnqualifiedId::IK_ConversionFunctionId: {
2299 TypeSourceInfo *TInfo;
2300 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
2301 if (Ty.isNull())
2302 return DeclarationNameInfo();
2303 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
2304 Context.getCanonicalType(Ty)));
2305 NameInfo.setLoc(Name.StartLocation);
2306 NameInfo.setNamedTypeInfo(TInfo);
2307 return NameInfo;
Douglas Gregord90fd522009-09-25 21:45:23 +00002308 }
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002309
2310 case UnqualifiedId::IK_ConstructorName: {
2311 TypeSourceInfo *TInfo;
2312 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
2313 if (Ty.isNull())
2314 return DeclarationNameInfo();
2315 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
2316 Context.getCanonicalType(Ty)));
2317 NameInfo.setLoc(Name.StartLocation);
2318 NameInfo.setNamedTypeInfo(TInfo);
2319 return NameInfo;
2320 }
2321
2322 case UnqualifiedId::IK_ConstructorTemplateId: {
2323 // In well-formed code, we can only have a constructor
2324 // template-id that refers to the current context, so go there
2325 // to find the actual type being constructed.
2326 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
2327 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
2328 return DeclarationNameInfo();
2329
2330 // Determine the type of the class being constructed.
2331 QualType CurClassType = Context.getTypeDeclType(CurClass);
2332
2333 // FIXME: Check two things: that the template-id names the same type as
2334 // CurClassType, and that the template-id does not occur when the name
2335 // was qualified.
2336
2337 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
2338 Context.getCanonicalType(CurClassType)));
2339 NameInfo.setLoc(Name.StartLocation);
2340 // FIXME: should we retrieve TypeSourceInfo?
2341 NameInfo.setNamedTypeInfo(0);
2342 return NameInfo;
2343 }
2344
2345 case UnqualifiedId::IK_DestructorName: {
2346 TypeSourceInfo *TInfo;
2347 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
2348 if (Ty.isNull())
2349 return DeclarationNameInfo();
2350 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
2351 Context.getCanonicalType(Ty)));
2352 NameInfo.setLoc(Name.StartLocation);
2353 NameInfo.setNamedTypeInfo(TInfo);
2354 return NameInfo;
2355 }
2356
2357 case UnqualifiedId::IK_TemplateId: {
John McCall3e56fd42010-08-23 07:28:44 +00002358 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002359 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
2360 return Context.getNameForTemplate(TName, TNameLoc);
2361 }
2362
2363 } // switch (Name.getKind())
2364
Douglas Gregor92751d42008-11-17 22:58:34 +00002365 assert(false && "Unknown name kind");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002366 return DeclarationNameInfo();
Douglas Gregor92751d42008-11-17 22:58:34 +00002367}
2368
Douglas Gregor8af63e42009-02-06 17:46:57 +00002369/// isNearlyMatchingFunction - Determine whether the C++ functions
2370/// Declaration and Definition are "nearly" matching. This heuristic
2371/// is used to improve diagnostics in the case where an out-of-line
2372/// function definition doesn't match any declaration within
2373/// the class or namespace.
2374static bool isNearlyMatchingFunction(ASTContext &Context,
2375 FunctionDecl *Declaration,
2376 FunctionDecl *Definition) {
Douglas Gregorad590502008-12-15 23:53:10 +00002377 if (Declaration->param_size() != Definition->param_size())
2378 return false;
2379 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
2380 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
2381 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
2382
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002383 if (!Context.hasSameUnqualifiedType(DeclParamTy.getNonReferenceType(),
2384 DefParamTy.getNonReferenceType()))
Douglas Gregorad590502008-12-15 23:53:10 +00002385 return false;
2386 }
2387
2388 return true;
2389}
2390
John McCall99b2fe52010-04-29 23:50:39 +00002391/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
2392/// declarator needs to be rebuilt in the current instantiation.
2393/// Any bits of declarator which appear before the name are valid for
2394/// consideration here. That's specifically the type in the decl spec
2395/// and the base type in any member-pointer chunks.
2396static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
2397 DeclarationName Name) {
2398 // The types we specifically need to rebuild are:
2399 // - typenames, typeofs, and decltypes
2400 // - types which will become injected class names
2401 // Of course, we also need to rebuild any type referencing such a
2402 // type. It's safest to just say "dependent", but we call out a
2403 // few cases here.
2404
2405 DeclSpec &DS = D.getMutableDeclSpec();
2406 switch (DS.getTypeSpecType()) {
2407 case DeclSpec::TST_typename:
2408 case DeclSpec::TST_typeofType:
John McCall99b2fe52010-04-29 23:50:39 +00002409 case DeclSpec::TST_decltype: {
2410 // Grab the type from the parser.
2411 TypeSourceInfo *TSI = 0;
John McCallba7bf592010-08-24 05:47:05 +00002412 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall99b2fe52010-04-29 23:50:39 +00002413 if (T.isNull() || !T->isDependentType()) break;
2414
2415 // Make sure there's a type source info. This isn't really much
2416 // of a waste; most dependent types should have type source info
2417 // attached already.
2418 if (!TSI)
2419 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
2420
2421 // Rebuild the type in the current instantiation.
2422 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
2423 if (!TSI) return true;
2424
2425 // Store the new type back in the decl spec.
John McCallba7bf592010-08-24 05:47:05 +00002426 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
2427 DS.UpdateTypeRep(LocType);
2428 break;
2429 }
2430
2431 case DeclSpec::TST_typeofExpr: {
2432 Expr *E = DS.getRepAsExpr();
John McCalldadc5752010-08-24 06:29:42 +00002433 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallba7bf592010-08-24 05:47:05 +00002434 if (Result.isInvalid()) return true;
2435 DS.UpdateExprRep(Result.get());
John McCall99b2fe52010-04-29 23:50:39 +00002436 break;
2437 }
2438
2439 default:
2440 // Nothing to do for these decl specs.
2441 break;
2442 }
2443
2444 // It doesn't matter what order we do this in.
2445 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
2446 DeclaratorChunk &Chunk = D.getTypeObject(I);
2447
2448 // The only type information in the declarator which can come
2449 // before the declaration name is the base type of a member
2450 // pointer.
2451 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
2452 continue;
2453
2454 // Rebuild the scope specifier in-place.
2455 CXXScopeSpec &SS = Chunk.Mem.Scope();
2456 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
2457 return true;
2458 }
2459
2460 return false;
2461}
2462
John McCallde6836a2010-08-24 07:21:54 +00002463Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
2464 return HandleDeclarator(S, D, MultiTemplateParamsArg(*this), false);
2465}
2466
John McCall48871652010-08-21 09:40:31 +00002467Decl *Sema::HandleDeclarator(Scope *S, Declarator &D,
2468 MultiTemplateParamsArg TemplateParamLists,
2469 bool IsFunctionDefinition) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002470 // TODO: consider using NameInfo for diagnostic.
2471 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2472 DeclarationName Name = NameInfo.getName();
Douglas Gregor92751d42008-11-17 22:58:34 +00002473
Chris Lattner02c04392007-07-25 00:24:17 +00002474 // All of these full declarators require an identifier. If it doesn't have
2475 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor92751d42008-11-17 22:58:34 +00002476 if (!Name) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002477 if (!D.isInvalidType()) // Reject this if we think it is valid.
Chris Lattner8c5dd732008-11-11 06:13:16 +00002478 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002479 diag::err_declarator_need_ident)
2480 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00002481 return 0;
Douglas Gregorc4356532010-12-16 00:46:58 +00002482 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
2483 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002484
Chris Lattner1a76a3c2007-08-26 06:24:45 +00002485 // The scope passed in may not be a decl scope. Zip up the scope tree until
2486 // we find one that is.
Douglas Gregor91f84212008-12-11 16:49:14 +00002487 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregorded2d7b2009-02-04 19:02:06 +00002488 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner1a76a3c2007-08-26 06:24:45 +00002489 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00002490
John McCall99b2fe52010-04-29 23:50:39 +00002491 DeclContext *DC = CurContext;
2492 if (D.getCXXScopeSpec().isInvalid())
2493 D.setInvalidType();
2494 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6c110f32010-12-16 01:14:37 +00002495 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
2496 UPPC_DeclarationQualifier))
2497 return 0;
2498
John McCall99b2fe52010-04-29 23:50:39 +00002499 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
2500 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
2501 if (!DC) {
2502 // If we could not compute the declaration context, it's because the
2503 // declaration context is dependent but does not refer to a class,
2504 // class template, or class template partial specialization. Complain
2505 // and return early, to avoid the coming semantic disaster.
2506 Diag(D.getIdentifierLoc(),
2507 diag::err_template_qualified_declarator_no_match)
2508 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
2509 << D.getCXXScopeSpec().getRange();
John McCall48871652010-08-21 09:40:31 +00002510 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00002511 }
John McCall4d6d6132009-12-19 09:35:56 +00002512
John McCall99b2fe52010-04-29 23:50:39 +00002513 bool IsDependentContext = DC->isDependentContext();
John McCall4d6d6132009-12-19 09:35:56 +00002514
John McCall99b2fe52010-04-29 23:50:39 +00002515 if (!IsDependentContext &&
John McCall0b66eb32010-05-01 00:40:08 +00002516 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCall48871652010-08-21 09:40:31 +00002517 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00002518
Douglas Gregora007d362010-10-13 22:19:53 +00002519 if (isa<CXXRecordDecl>(DC)) {
2520 if (!cast<CXXRecordDecl>(DC)->hasDefinition()) {
2521 Diag(D.getIdentifierLoc(),
2522 diag::err_member_def_undefined_record)
2523 << Name << DC << D.getCXXScopeSpec().getRange();
2524 D.setInvalidType();
2525 } else if (isa<CXXRecordDecl>(CurContext) &&
2526 !D.getDeclSpec().isFriendSpecified()) {
2527 // The user provided a superfluous scope specifier inside a class
2528 // definition:
2529 //
2530 // class X {
2531 // void X::f();
2532 // };
2533 if (CurContext->Equals(DC))
2534 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
2535 << Name << FixItHint::CreateRemoval(D.getCXXScopeSpec().getRange());
2536 else
2537 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2538 << Name << D.getCXXScopeSpec().getRange();
2539
2540 // Pretend that this qualifier was not here.
2541 D.getCXXScopeSpec().clear();
2542 }
John McCall99b2fe52010-04-29 23:50:39 +00002543 }
2544
2545 // Check whether we need to rebuild the type of the given
2546 // declaration in the current instantiation.
2547 if (EnteringContext && IsDependentContext &&
2548 TemplateParamLists.size() != 0) {
2549 ContextRAII SavedContext(*this, DC);
2550 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
2551 D.setInvalidType();
Douglas Gregor15acfb92009-08-06 16:20:37 +00002552 }
2553 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00002554
2555 // C++ [class.mem]p13:
2556 // If T is the name of a class, then each of the following shall have a
2557 // name different from T:
2558 // - every static data member of class T;
2559 // - every member function of class T
2560 // - every member of class T that is itself a type;
2561 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
2562 if (Record->getIdentifier() && Record->getDeclName() == Name) {
2563 Diag(D.getIdentifierLoc(), diag::err_member_name_of_class)
2564 << Name;
2565
2566 // If this is a typedef, we'll end up spewing multiple diagnostics.
2567 // Just return early; it's safer.
2568 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2569 return 0;
2570 }
2571
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002572 NamedDecl *New;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002573
John McCall8cb7bdf2010-06-04 23:28:52 +00002574 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
2575 QualType R = TInfo->getType();
Douglas Gregoreddf4332009-02-24 20:03:32 +00002576
Douglas Gregor506bd562010-12-13 22:49:22 +00002577 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
2578 UPPC_DeclarationType))
2579 D.setInvalidType();
2580
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002581 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00002582 ForRedeclaration);
2583
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00002584 // See if this is a redefinition of a variable in the same scope.
John McCall99b2fe52010-04-29 23:50:39 +00002585 if (!D.getCXXScopeSpec().isSet()) {
John McCall1f82f242009-11-18 22:49:29 +00002586 bool IsLinkageLookup = false;
Douglas Gregoreddf4332009-02-24 20:03:32 +00002587
2588 // If the declaration we're planning to build will be a function
2589 // or object with linkage, then look for another declaration with
2590 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
2591 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2592 /* Do nothing*/;
2593 else if (R->isFunctionType()) {
Douglas Gregor20749772009-07-07 17:00:05 +00002594 if (CurContext->isFunctionOrMethod() ||
2595 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall1f82f242009-11-18 22:49:29 +00002596 IsLinkageLookup = true;
Douglas Gregoreddf4332009-02-24 20:03:32 +00002597 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
John McCall1f82f242009-11-18 22:49:29 +00002598 IsLinkageLookup = true;
Sebastian Redl50c68252010-08-31 00:36:30 +00002599 else if (CurContext->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor20749772009-07-07 17:00:05 +00002600 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall1f82f242009-11-18 22:49:29 +00002601 IsLinkageLookup = true;
2602
2603 if (IsLinkageLookup)
2604 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregoreddf4332009-02-24 20:03:32 +00002605
John McCall1f82f242009-11-18 22:49:29 +00002606 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00002607 } else { // Something like "int foo::x;"
John McCall1f82f242009-11-18 22:49:29 +00002608 LookupQualifiedName(Previous, DC);
2609
2610 // Don't consider using declarations as previous declarations for
2611 // out-of-line members.
2612 RemoveUsingDecls(Previous);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00002613
2614 // C++ 7.3.1.2p2:
2615 // Members (including explicit specializations of templates) of a named
2616 // namespace can also be defined outside that namespace by explicit
2617 // qualification of the name being defined, provided that the entity being
2618 // defined was already declared in the namespace and the definition appears
2619 // after the point of declaration in a namespace that encloses the
2620 // declarations namespace.
2621 //
Douglas Gregorad590502008-12-15 23:53:10 +00002622 // Note that we only check the context at this point. We don't yet
2623 // have enough information to make sure that PrevDecl is actually
2624 // the declaration we want to match. For example, given:
2625 //
Douglas Gregor4287b372008-12-12 08:25:50 +00002626 // class X {
2627 // void f();
Douglas Gregorad590502008-12-15 23:53:10 +00002628 // void f(float);
Douglas Gregor4287b372008-12-12 08:25:50 +00002629 // };
2630 //
Douglas Gregorad590502008-12-15 23:53:10 +00002631 // void X::f(int) { } // ill-formed
2632 //
2633 // In this case, PrevDecl will point to the overload set
2634 // containing the two f's declared in X, but neither of them
Mike Stump11289f42009-09-09 15:08:12 +00002635 // matches.
Douglas Gregor8af63e42009-02-06 17:46:57 +00002636
2637 // First check whether we named the global scope.
2638 if (isa<TranslationUnitDecl>(DC)) {
Mike Stump11289f42009-09-09 15:08:12 +00002639 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
Douglas Gregor8af63e42009-02-06 17:46:57 +00002640 << Name << D.getCXXScopeSpec().getRange();
Sebastian Redlafb8be72009-11-08 11:36:54 +00002641 } else {
2642 DeclContext *Cur = CurContext;
2643 while (isa<LinkageSpecDecl>(Cur))
2644 Cur = Cur->getParent();
2645 if (!Cur->Encloses(DC)) {
2646 // The qualifying scope doesn't enclose the original declaration.
2647 // Emit diagnostic based on current scope.
2648 SourceLocation L = D.getIdentifierLoc();
2649 SourceRange R = D.getCXXScopeSpec().getRange();
2650 if (isa<FunctionDecl>(Cur))
2651 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
2652 else
2653 Diag(L, diag::err_invalid_declarator_scope)
2654 << Name << cast<NamedDecl>(DC) << R;
2655 D.setInvalidType();
2656 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00002657 }
2658 }
2659
John McCall1f82f242009-11-18 22:49:29 +00002660 if (Previous.isSingleResult() &&
2661 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00002662 // Maybe we will complain about the shadowed template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002663 if (!D.isInvalidType())
John McCall1f82f242009-11-18 22:49:29 +00002664 if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
2665 Previous.getFoundDecl()))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002666 D.setInvalidType();
Mike Stump11289f42009-09-09 15:08:12 +00002667
Douglas Gregor5101c242008-12-05 18:15:24 +00002668 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00002669 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00002670 }
2671
Douglas Gregor83a586e2008-04-13 21:07:44 +00002672 // In C++, the previous declaration we find might be a tag type
2673 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorfb034662009-01-28 17:15:10 +00002674 // tag type. Note that this does does not apply if we're declaring a
2675 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00002676 if (Previous.isSingleTagDecl() &&
Douglas Gregorfb034662009-01-28 17:15:10 +00002677 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall1f82f242009-11-18 22:49:29 +00002678 Previous.clear();
Douglas Gregor83a586e2008-04-13 21:07:44 +00002679
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002680 bool Redeclaration = false;
Chris Lattner01a7c532007-01-25 23:09:03 +00002681 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00002682 if (TemplateParamLists.size()) {
2683 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
John McCall48871652010-08-21 09:40:31 +00002684 return 0;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00002685 }
Mike Stump11289f42009-09-09 15:08:12 +00002686
John McCallbcd03502009-12-07 02:54:59 +00002687 New = ActOnTypedefDeclarator(S, D, DC, R, TInfo, Previous, Redeclaration);
Douglas Gregoreddf4332009-02-24 20:03:32 +00002688 } else if (R->isFunctionType()) {
John McCallbcd03502009-12-07 02:54:59 +00002689 New = ActOnFunctionDeclarator(S, D, DC, R, TInfo, Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00002690 move(TemplateParamLists),
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002691 IsFunctionDefinition, Redeclaration);
Chris Lattner01a7c532007-01-25 23:09:03 +00002692 } else {
John McCallbcd03502009-12-07 02:54:59 +00002693 New = ActOnVariableDeclarator(S, D, DC, R, TInfo, Previous,
Douglas Gregorb09f3d82009-07-22 17:18:37 +00002694 move(TemplateParamLists),
2695 Redeclaration);
Chris Lattner01a7c532007-01-25 23:09:03 +00002696 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00002697
2698 if (New == 0)
John McCall48871652010-08-21 09:40:31 +00002699 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002700
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002701 // If this has an identifier and is not an invalid redeclaration or
2702 // function template specialization, add it to the scope stack.
Douglas Gregor536f0912010-07-24 00:10:38 +00002703 if (New->getDeclName() && !(Redeclaration && New->isInvalidDecl()))
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00002704 PushOnScopeChains(New, S);
Mike Stump11289f42009-09-09 15:08:12 +00002705
John McCall48871652010-08-21 09:40:31 +00002706 return New;
Chris Lattnere168f762006-11-10 05:29:30 +00002707}
2708
Eli Friedmana3b1d032009-02-21 00:44:51 +00002709/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2710/// types into constant array types in certain situations which would otherwise
2711/// be errors (for GCC compatibility).
2712static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2713 ASTContext &Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00002714 bool &SizeIsNegative,
2715 llvm::APSInt &Oversized) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00002716 // This method tries to turn a variable array into a constant
2717 // array even when the size isn't an ICE. This is necessary
2718 // for compatibility with code that depends on gcc's buggy
2719 // constant expression folding, like struct {char x[(int)(char*)2];}
2720 SizeIsNegative = false;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00002721 Oversized = 0;
2722
2723 if (T->isDependentType())
2724 return QualType();
2725
John McCall8ccfcb52009-09-24 19:53:00 +00002726 QualifierCollector Qs;
2727 const Type *Ty = Qs.strip(T);
2728
2729 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00002730 QualType Pointee = PTy->getPointeeType();
2731 QualType FixedType =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00002732 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
2733 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00002734 if (FixedType.isNull()) return FixedType;
Eli Friedman44c0f2a2009-02-21 00:58:02 +00002735 FixedType = Context.getPointerType(FixedType);
John McCall717d9b02010-12-10 11:01:00 +00002736 return Qs.apply(Context, FixedType);
Eli Friedmana3b1d032009-02-21 00:44:51 +00002737 }
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002738 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
2739 QualType Inner = PTy->getInnerType();
2740 QualType FixedType =
2741 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
2742 Oversized);
2743 if (FixedType.isNull()) return FixedType;
2744 FixedType = Context.getParenType(FixedType);
2745 return Qs.apply(Context, FixedType);
2746 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00002747
2748 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanadf40d42009-02-26 03:58:54 +00002749 if (!VLATy)
2750 return QualType();
2751 // FIXME: We should probably handle this case
2752 if (VLATy->getElementType()->isVariablyModifiedType())
2753 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00002754
Eli Friedmana3b1d032009-02-21 00:44:51 +00002755 Expr::EvalResult EvalResult;
2756 if (!VLATy->getSizeExpr() ||
Eli Friedmanadf40d42009-02-26 03:58:54 +00002757 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
2758 !EvalResult.Val.isInt())
Eli Friedmana3b1d032009-02-21 00:44:51 +00002759 return QualType();
Eli Friedmanadf40d42009-02-26 03:58:54 +00002760
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00002761 // Check whether the array size is negative.
Eli Friedmana3b1d032009-02-21 00:44:51 +00002762 llvm::APSInt &Res = EvalResult.Val.getInt();
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00002763 if (Res.isSigned() && Res.isNegative()) {
2764 SizeIsNegative = true;
2765 return QualType();
Douglas Gregor04318252009-07-06 15:59:29 +00002766 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00002767
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00002768 // Check whether the array is too large to be addressed.
2769 unsigned ActiveSizeBits
2770 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
2771 Res);
2772 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2773 Oversized = Res;
2774 return QualType();
2775 }
2776
2777 return Context.getConstantArrayType(VLATy->getElementType(),
2778 Res, ArrayType::Normal, 0);
Eli Friedmana3b1d032009-02-21 00:44:51 +00002779}
2780
Douglas Gregor5a80bd12009-03-02 00:19:53 +00002781/// \brief Register the given locally-scoped external C declaration so
2782/// that it can be found later for redeclarations
Mike Stump11289f42009-09-09 15:08:12 +00002783void
John McCall1f82f242009-11-18 22:49:29 +00002784Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
2785 const LookupResult &Previous,
Douglas Gregor5a80bd12009-03-02 00:19:53 +00002786 Scope *S) {
2787 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
2788 "Decl is not a locally-scoped decl!");
2789 // Note that we have a locally-scoped external with this name.
2790 LocallyScopedExternalDecls[ND->getDeclName()] = ND;
2791
John McCall1f82f242009-11-18 22:49:29 +00002792 if (!Previous.isSingleResult())
Douglas Gregor5a80bd12009-03-02 00:19:53 +00002793 return;
2794
John McCall1f82f242009-11-18 22:49:29 +00002795 NamedDecl *PrevDecl = Previous.getFoundDecl();
2796
Douglas Gregor5a80bd12009-03-02 00:19:53 +00002797 // If there was a previous declaration of this variable, it may be
2798 // in our identifier chain. Update the identifier chain with the new
2799 // declaration.
Douglas Gregorf4f296d2009-03-23 23:06:20 +00002800 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00002801 // The previous declaration was found on the identifer resolver
2802 // chain, so remove it from its scope.
John McCall48871652010-08-21 09:40:31 +00002803 while (S && !S->isDeclScope(PrevDecl))
Douglas Gregor5a80bd12009-03-02 00:19:53 +00002804 S = S->getParent();
2805
2806 if (S)
John McCall48871652010-08-21 09:40:31 +00002807 S->RemoveDecl(PrevDecl);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00002808 }
2809}
2810
Eli Friedman574c7452009-04-07 19:37:57 +00002811/// \brief Diagnose function specifiers on a declaration of an identifier that
2812/// does not identify a function.
2813void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
2814 // FIXME: We should probably indicate the identifier in question to avoid
2815 // confusion for constructs like "inline int a(), b;"
2816 if (D.getDeclSpec().isInlineSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00002817 Diag(D.getDeclSpec().getInlineSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00002818 diag::err_inline_non_function);
2819
2820 if (D.getDeclSpec().isVirtualSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00002821 Diag(D.getDeclSpec().getVirtualSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00002822 diag::err_virtual_non_function);
2823
2824 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00002825 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00002826 diag::err_explicit_non_function);
2827}
2828
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002829NamedDecl*
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002830Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
John McCallbcd03502009-12-07 02:54:59 +00002831 QualType R, TypeSourceInfo *TInfo,
John McCall1f82f242009-11-18 22:49:29 +00002832 LookupResult &Previous, bool &Redeclaration) {
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002833 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
2834 if (D.getCXXScopeSpec().isSet()) {
2835 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
2836 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002837 D.setInvalidType();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002838 // Pretend we didn't see the scope specifier.
Douglas Gregorb525ef82010-03-23 15:26:55 +00002839 DC = CurContext;
2840 Previous.clear();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002841 }
2842
Douglas Gregor0c880302009-03-11 23:00:04 +00002843 if (getLangOptions().CPlusPlus) {
2844 // Check that there are no default arguments (C++ only).
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002845 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00002846 }
2847
Eli Friedman574c7452009-04-07 19:37:57 +00002848 DiagnoseFunctionSpecifiers(D);
2849
Eli Friedmand5c0eed2009-04-19 20:27:55 +00002850 if (D.getDeclSpec().isThreadSpecified())
2851 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2852
Douglas Gregord8f446f2010-07-13 06:37:01 +00002853 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
2854 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
2855 << D.getName().getSourceRange();
2856 return 0;
2857 }
2858
John McCallbcd03502009-12-07 02:54:59 +00002859 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, TInfo);
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002860 if (!NewTD) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002861
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002862 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00002863 ProcessDeclAttributes(S, NewTD, D);
John McCall1f82f242009-11-18 22:49:29 +00002864
Chris Lattner9fecd742009-04-19 05:21:20 +00002865 // C99 6.7.7p2: If a typedef name specifies a variably modified type
2866 // then it shall have block scope.
Eli Friedman88f4ed92010-08-10 03:13:15 +00002867 // Note that variably modified types must be fixed before merging the decl so
2868 // that redeclarations will match.
Chris Lattner9fecd742009-04-19 05:21:20 +00002869 QualType T = NewTD->getUnderlyingType();
2870 if (T->isVariablyModifiedType()) {
John McCallaab3e412010-08-25 08:40:02 +00002871 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00002872
Chris Lattner9fecd742009-04-19 05:21:20 +00002873 if (S->getFnParent() == 0) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00002874 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00002875 llvm::APSInt Oversized;
Eli Friedmana3b1d032009-02-21 00:44:51 +00002876 QualType FixedTy =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00002877 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
2878 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00002879 if (!FixedTy.isNull()) {
2880 Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size);
John McCallbcd03502009-12-07 02:54:59 +00002881 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
Eli Friedmana3b1d032009-02-21 00:44:51 +00002882 } else {
2883 if (SizeIsNegative)
2884 Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size);
2885 else if (T->isVariableArrayType())
2886 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00002887 else if (Oversized.getBoolValue())
2888 Diag(D.getIdentifierLoc(), diag::err_array_too_large)
2889 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00002890 else
2891 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002892 NewTD->setInvalidDecl();
Eli Friedmana3b1d032009-02-21 00:44:51 +00002893 }
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002894 }
2895 }
Douglas Gregor27821ce2009-07-07 16:35:42 +00002896
Eli Friedman88f4ed92010-08-10 03:13:15 +00002897 // Merge the decl with the existing one if appropriate. If the decl is
2898 // in an outer scope, it isn't the same thing.
Douglas Gregordb446112011-03-07 16:54:27 +00002899 FilterLookupForScope(*this, Previous, DC, S, /*ConsiderLinkage*/ false,
2900 /*ExplicitInstantiationOrSpecialization=*/false);
Eli Friedman88f4ed92010-08-10 03:13:15 +00002901 if (!Previous.empty()) {
2902 Redeclaration = true;
2903 MergeTypeDefDecl(NewTD, Previous);
2904 }
2905
Douglas Gregor27821ce2009-07-07 16:35:42 +00002906 // If this is the C FILE type, notify the AST context.
2907 if (IdentifierInfo *II = NewTD->getIdentifier())
2908 if (!NewTD->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00002909 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stumpa4de80b2009-07-28 02:25:19 +00002910 if (II->isStr("FILE"))
2911 Context.setFILEDecl(NewTD);
2912 else if (II->isStr("jmp_buf"))
2913 Context.setjmp_bufDecl(NewTD);
2914 else if (II->isStr("sigjmp_buf"))
2915 Context.setsigjmp_bufDecl(NewTD);
Douglas Gregor2c2c4cd2010-10-05 15:41:24 +00002916 else if (II->isStr("__builtin_va_list"))
2917 Context.setBuiltinVaListType(Context.getTypedefType(NewTD));
Mike Stumpa4de80b2009-07-28 02:25:19 +00002918 }
2919
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00002920 return NewTD;
2921}
2922
Douglas Gregor5d68a202009-02-24 19:23:27 +00002923/// \brief Determines whether the given declaration is an out-of-scope
2924/// previous declaration.
2925///
2926/// This routine should be invoked when name lookup has found a
2927/// previous declaration (PrevDecl) that is not in the scope where a
2928/// new declaration by the same name is being introduced. If the new
2929/// declaration occurs in a local scope, previous declarations with
2930/// linkage may still be considered previous declarations (C99
2931/// 6.2.2p4-5, C++ [basic.link]p6).
2932///
2933/// \param PrevDecl the previous declaration found by name
2934/// lookup
Mike Stump11289f42009-09-09 15:08:12 +00002935///
Douglas Gregor5d68a202009-02-24 19:23:27 +00002936/// \param DC the context in which the new declaration is being
2937/// declared.
2938///
2939/// \returns true if PrevDecl is an out-of-scope previous declaration
2940/// for a new delcaration with the same name.
Mike Stump11289f42009-09-09 15:08:12 +00002941static bool
Douglas Gregor5d68a202009-02-24 19:23:27 +00002942isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
2943 ASTContext &Context) {
2944 if (!PrevDecl)
Sebastian Redl50c68252010-08-31 00:36:30 +00002945 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00002946
Douglas Gregoreddf4332009-02-24 20:03:32 +00002947 if (!PrevDecl->hasLinkage())
2948 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00002949
2950 if (Context.getLangOptions().CPlusPlus) {
2951 // C++ [basic.link]p6:
2952 // If there is a visible declaration of an entity with linkage
2953 // having the same name and type, ignoring entities declared
2954 // outside the innermost enclosing namespace scope, the block
2955 // scope declaration declares that same entity and receives the
2956 // linkage of the previous declaration.
Sebastian Redl50c68252010-08-31 00:36:30 +00002957 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor5d68a202009-02-24 19:23:27 +00002958 if (!OuterContext->isFunctionOrMethod())
2959 // This rule only applies to block-scope declarations.
2960 return false;
Douglas Gregorfcee9462010-08-27 22:55:10 +00002961
2962 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
2963 if (PrevOuterContext->isRecord())
2964 // We found a member function: ignore it.
2965 return false;
2966
2967 // Find the innermost enclosing namespace for the new and
2968 // previous declarations.
Sebastian Redl50c68252010-08-31 00:36:30 +00002969 OuterContext = OuterContext->getEnclosingNamespaceContext();
2970 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump11289f42009-09-09 15:08:12 +00002971
Douglas Gregorfcee9462010-08-27 22:55:10 +00002972 // The previous declaration is in a different namespace, so it
2973 // isn't the same function.
2974 if (!OuterContext->Equals(PrevOuterContext))
2975 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00002976 }
2977
Douglas Gregor5d68a202009-02-24 19:23:27 +00002978 return true;
2979}
2980
John McCall3e11ebe2010-03-15 10:12:16 +00002981static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
2982 CXXScopeSpec &SS = D.getCXXScopeSpec();
2983 if (!SS.isSet()) return;
Douglas Gregor14454802011-02-25 02:25:35 +00002984 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00002985}
2986
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002987NamedDecl*
Chris Lattner88fdea82010-10-10 18:16:20 +00002988Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
John McCallbcd03502009-12-07 02:54:59 +00002989 QualType R, TypeSourceInfo *TInfo,
John McCall1f82f242009-11-18 22:49:29 +00002990 LookupResult &Previous,
Douglas Gregorb09f3d82009-07-22 17:18:37 +00002991 MultiTemplateParamsArg TemplateParamLists,
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002992 bool &Redeclaration) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002993 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00002994
2995 // Check that there are no default arguments (C++ only).
2996 if (getLangOptions().CPlusPlus)
2997 CheckExtraCXXDefaultArguments(D);
2998
Douglas Gregorc4df4072010-04-19 22:54:31 +00002999 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
3000 assert(SCSpec != DeclSpec::SCS_typedef &&
3001 "Parser allowed 'typedef' as storage class VarDecl.");
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00003002 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregorc4df4072010-04-19 22:54:31 +00003003 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003004 // mutable can only appear on non-static class members, so it's always
3005 // an error here
3006 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003007 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003008 SC = SC_None;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003009 }
Douglas Gregorc4df4072010-04-19 22:54:31 +00003010 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
3011 VarDecl::StorageClass SCAsWritten
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00003012 = StorageClassSpecToVarDeclStorageClass(SCSpec);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003013
3014 IdentifierInfo *II = Name.getAsIdentifierInfo();
3015 if (!II) {
3016 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
3017 << Name.getAsString();
3018 return 0;
3019 }
3020
Eli Friedman574c7452009-04-07 19:37:57 +00003021 DiagnoseFunctionSpecifiers(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00003022
Douglas Gregor212cab32009-03-11 20:22:50 +00003023 if (!DC->isRecord() && S->getFnParent() == 0) {
3024 // C99 6.9p2: The storage-class specifiers auto and register shall not
3025 // appear in the declaration specifiers in an external declaration.
John McCall8e7d6562010-08-26 03:08:43 +00003026 if (SC == SC_Auto || SC == SC_Register) {
Mike Stump11289f42009-09-09 15:08:12 +00003027
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00003028 // If this is a register variable with an asm label specified, then this
3029 // is a GNU extension.
John McCall8e7d6562010-08-26 03:08:43 +00003030 if (SC == SC_Register && D.getAsmLabel())
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00003031 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
3032 else
3033 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003034 D.setInvalidType();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003035 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003036 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003037
Ted Kremenek582a0992011-01-23 17:04:59 +00003038 bool isExplicitSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003039 VarDecl *NewVD;
3040 if (!getLangOptions().CPlusPlus) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003041 NewVD = VarDecl::Create(Context, DC, D.getSourceRange().getBegin(),
3042 D.getIdentifierLoc(), II,
3043 R, TInfo, SC, SCAsWritten);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003044
3045 if (D.isInvalidType())
3046 NewVD->setInvalidDecl();
3047 } else {
3048 if (DC->isRecord() && !CurContext->isRecord()) {
3049 // This is an out-of-line definition of a static data member.
3050 if (SC == SC_Static) {
3051 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
3052 diag::err_static_out_of_line)
3053 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3054 } else if (SC == SC_None)
3055 SC = SC_Static;
Anders Carlssond2e8adf2009-06-24 00:28:53 +00003056 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003057 if (SC == SC_Static) {
3058 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
3059 if (RD->isLocalClass())
3060 Diag(D.getIdentifierLoc(),
3061 diag::err_static_data_member_not_allowed_in_local_class)
3062 << Name << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003063
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003064 // C++ [class.union]p1: If a union contains a static data member,
3065 // the program is ill-formed.
3066 //
3067 // We also disallow static data members in anonymous structs.
3068 if (CurContext->isRecord() && (RD->isUnion() || !RD->getDeclName()))
3069 Diag(D.getIdentifierLoc(),
3070 diag::err_static_data_member_not_allowed_in_union_or_anon_struct)
3071 << Name << RD->isUnion();
3072 }
3073 }
3074
3075 // Match up the template parameter lists with the scope specifier, then
3076 // determine whether we have a template or a template specialization.
3077 isExplicitSpecialization = false;
3078 unsigned NumMatchedTemplateParamLists = TemplateParamLists.size();
3079 bool Invalid = false;
3080 if (TemplateParameterList *TemplateParams
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003081 = MatchTemplateParametersToScopeSpecifier(
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003082 D.getDeclSpec().getSourceRange().getBegin(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003083 D.getCXXScopeSpec(),
John McCallace48cd2010-10-19 01:40:49 +00003084 TemplateParamLists.get(),
3085 TemplateParamLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00003086 /*never a friend*/ false,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003087 isExplicitSpecialization,
3088 Invalid)) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003089 // All but one template parameter lists have been matching.
3090 --NumMatchedTemplateParamLists;
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003091
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003092 if (TemplateParams->size() > 0) {
3093 // There is no such thing as a variable template.
3094 Diag(D.getIdentifierLoc(), diag::err_template_variable)
3095 << II
3096 << SourceRange(TemplateParams->getTemplateLoc(),
3097 TemplateParams->getRAngleLoc());
3098 return 0;
3099 } else {
3100 // There is an extraneous 'template<>' for this variable. Complain
3101 // about it, but allow the declaration of the variable.
3102 Diag(TemplateParams->getTemplateLoc(),
3103 diag::err_template_variable_noparams)
3104 << II
3105 << SourceRange(TemplateParams->getTemplateLoc(),
3106 TemplateParams->getRAngleLoc());
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003107
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003108 isExplicitSpecialization = true;
3109 }
Douglas Gregorb09f3d82009-07-22 17:18:37 +00003110 }
Mike Stump11289f42009-09-09 15:08:12 +00003111
Abramo Bagnaradff19302011-03-08 08:55:46 +00003112 NewVD = VarDecl::Create(Context, DC, D.getSourceRange().getBegin(),
3113 D.getIdentifierLoc(), II,
3114 R, TInfo, SC, SCAsWritten);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003115
Richard Smithb2bc2e62011-02-21 20:05:19 +00003116 // If this decl has an auto type in need of deduction, make a note of the
3117 // Decl so we can diagnose uses of it in its own initializer.
3118 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
3119 R->getContainedAutoType())
3120 ParsingInitForAutoVars.insert(NewVD);
Richard Smith30482bc2011-02-20 03:19:35 +00003121
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003122 if (D.isInvalidType() || Invalid)
3123 NewVD->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003124
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003125 SetNestedNameSpecifier(NewVD, D);
John McCall3e11ebe2010-03-15 10:12:16 +00003126
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003127 if (NumMatchedTemplateParamLists > 0 && D.getCXXScopeSpec().isSet()) {
3128 NewVD->setTemplateParameterListsInfo(Context,
3129 NumMatchedTemplateParamLists,
3130 TemplateParamLists.release());
3131 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003132 }
3133
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003134 if (D.getDeclSpec().isThreadSpecified()) {
3135 if (NewVD->hasLocalStorage())
3136 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
Eli Friedmandaea3f62009-04-19 21:48:33 +00003137 else if (!Context.Target.isTLSSupported())
3138 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003139 else
3140 NewVD->setThreadSpecified(true);
3141 }
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003142
Douglas Gregor04e9a032009-03-11 23:52:16 +00003143 // Set the lexical context. If the declarator has a C++ scope specifier, the
3144 // lexical context will be different from the semantic context.
3145 NewVD->setLexicalDeclContext(CurContext);
3146
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003147 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00003148 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003149
3150 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner88fdea82010-10-10 18:16:20 +00003151 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003152 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00003153 StringLiteral *SE = cast<StringLiteral>(E);
Rafael Espindola478abca2011-01-01 21:47:03 +00003154 llvm::StringRef Label = SE->getString();
Abramo Bagnara13392232011-01-11 15:16:52 +00003155 if (S->getFnParent() != 0) {
3156 switch (SC) {
3157 case SC_None:
3158 case SC_Auto:
3159 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
3160 break;
3161 case SC_Register:
3162 if (!Context.Target.isValidGCCRegisterName(Label))
3163 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
3164 break;
3165 case SC_Static:
3166 case SC_Extern:
3167 case SC_PrivateExtern:
3168 break;
3169 }
3170 }
3171
3172 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Rafael Espindola478abca2011-01-01 21:47:03 +00003173 Context, Label));
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003174 }
3175
John McCalla2a3f7d2010-03-16 21:48:18 +00003176 // Diagnose shadowed variables before filtering for scope.
John McCall2d8c7602010-03-20 04:12:52 +00003177 if (!D.getCXXScopeSpec().isSet())
John McCalldf8b37c2010-03-22 09:20:08 +00003178 CheckShadow(S, NewVD, Previous);
John McCalla2a3f7d2010-03-16 21:48:18 +00003179
John McCall1f82f242009-11-18 22:49:29 +00003180 // Don't consider existing declarations that are in a different
3181 // scope and are out-of-semantic-context declarations (if the new
3182 // declaration has linkage).
Douglas Gregordb446112011-03-07 16:54:27 +00003183 FilterLookupForScope(*this, Previous, DC, S, NewVD->hasLinkage(),
3184 isExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00003185
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003186 if (!getLangOptions().CPlusPlus)
3187 CheckVariableDeclaration(NewVD, Previous, Redeclaration);
3188 else {
3189 // Merge the decl with the existing one if appropriate.
3190 if (!Previous.empty()) {
3191 if (Previous.isSingleResult() &&
3192 isa<FieldDecl>(Previous.getFoundDecl()) &&
3193 D.getCXXScopeSpec().isSet()) {
3194 // The user tried to define a non-static data member
3195 // out-of-line (C++ [dcl.meaning]p1).
3196 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
3197 << D.getCXXScopeSpec().getRange();
3198 Previous.clear();
3199 NewVD->setInvalidDecl();
3200 }
3201 } else if (D.getCXXScopeSpec().isSet()) {
3202 // No previous declaration in the qualifying scope.
3203 Diag(D.getIdentifierLoc(), diag::err_no_member)
3204 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003205 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003206 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003207 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003208
3209 CheckVariableDeclaration(NewVD, Previous, Redeclaration);
3210
3211 // This is an explicit specialization of a static data member. Check it.
3212 if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
3213 CheckMemberSpecialization(NewVD, Previous))
3214 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003215 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003216
Ryan Flynne5dc8592009-07-25 22:29:44 +00003217 // attributes declared post-definition are currently ignored
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003218 // FIXME: This should be handled in attribute merging, not
3219 // here.
John McCall1f82f242009-11-18 22:49:29 +00003220 if (Previous.isSingleResult()) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00003221 VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl());
3222 if (Def && (Def = Def->getDefinition()) &&
3223 Def != NewVD && D.hasAttributes()) {
Ryan Flynne5dc8592009-07-25 22:29:44 +00003224 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
3225 Diag(Def->getLocation(), diag::note_previous_definition);
3226 }
3227 }
3228
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003229 // If this is a locally-scoped extern C variable, update the map of
3230 // such variables.
Douglas Gregor16618f22009-09-12 00:17:51 +00003231 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003232 !NewVD->isInvalidDecl())
John McCall1f82f242009-11-18 22:49:29 +00003233 RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003234
Eli Friedman570024a2010-08-05 06:57:20 +00003235 // If there's a #pragma GCC visibility in scope, and this isn't a class
3236 // member, set the visibility of this variable.
3237 if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord())
3238 AddPushedVisibilityAttribute(NewVD);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003239
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00003240 MarkUnusedFileScopedDecl(NewVD);
3241
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003242 return NewVD;
3243}
3244
John McCalldf8b37c2010-03-22 09:20:08 +00003245/// \brief Diagnose variable or built-in function shadowing. Implements
3246/// -Wshadow.
John McCalla2a3f7d2010-03-16 21:48:18 +00003247///
John McCalldf8b37c2010-03-22 09:20:08 +00003248/// This method is called whenever a VarDecl is added to a "useful"
3249/// scope.
John McCalla2a3f7d2010-03-16 21:48:18 +00003250///
John McCall2d8c7602010-03-20 04:12:52 +00003251/// \param S the scope in which the shadowing name is being declared
3252/// \param R the lookup of the name
John McCalla2a3f7d2010-03-16 21:48:18 +00003253///
John McCalldf8b37c2010-03-22 09:20:08 +00003254void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCalla2a3f7d2010-03-16 21:48:18 +00003255 // Return if warning is ignored.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003256 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
3257 Diagnostic::Ignored)
John McCalla2a3f7d2010-03-16 21:48:18 +00003258 return;
3259
Argyrios Kyrtzidis898fdbf2011-02-08 18:21:25 +00003260 // Don't diagnose declarations at file scope.
3261 DeclContext *NewDC = D->getDeclContext();
3262 if (NewDC->isFileContext())
John McCalla2a3f7d2010-03-16 21:48:18 +00003263 return;
John McCall2d8c7602010-03-20 04:12:52 +00003264
3265 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregor319aa6c2010-03-17 16:03:44 +00003266 if (R.getResultKind() != LookupResult::Found)
John McCalla2a3f7d2010-03-16 21:48:18 +00003267 return;
John McCalla2a3f7d2010-03-16 21:48:18 +00003268
John McCalla2a3f7d2010-03-16 21:48:18 +00003269 NamedDecl* ShadowedDecl = R.getFoundDecl();
3270 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
3271 return;
3272
Argyrios Kyrtzidisf46cc652011-01-31 07:04:54 +00003273 // Fields are not shadowed by variables in C++ static methods.
3274 if (isa<FieldDecl>(ShadowedDecl))
3275 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
3276 if (MD->isStatic())
3277 return;
3278
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00003279 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
3280 if (shadowedVar->isExternC()) {
3281 // Don't warn for this case:
3282 //
3283 // @code
3284 // extern int bob;
3285 // void f() {
3286 // extern int bob;
3287 // }
3288 // @endcode
3289 if (D->isExternC())
Argyrios Kyrtzidisf41860c2011-01-31 07:04:41 +00003290 return;
3291
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00003292 // For shadowing external vars, make sure that we point to the global
3293 // declaration, not a locally scoped extern declaration.
3294 for (VarDecl::redecl_iterator
3295 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
3296 I != E; ++I)
3297 if (I->isFileVarDecl()) {
3298 ShadowedDecl = *I;
3299 break;
3300 }
3301 }
3302
3303 DeclContext *OldDC = ShadowedDecl->getDeclContext();
3304
John McCall2d8c7602010-03-20 04:12:52 +00003305 // Only warn about certain kinds of shadowing for class members.
3306 if (NewDC && NewDC->isRecord()) {
3307 // In particular, don't warn about shadowing non-class members.
3308 if (!OldDC->isRecord())
3309 return;
3310
3311 // TODO: should we warn about static data members shadowing
3312 // static data members from base classes?
3313
3314 // TODO: don't diagnose for inaccessible shadowed members.
3315 // This is hard to do perfectly because we might friend the
3316 // shadowing context, but that's just a false negative.
3317 }
3318
3319 // Determine what kind of declaration we're shadowing.
John McCalla2a3f7d2010-03-16 21:48:18 +00003320 unsigned Kind;
John McCall2d8c7602010-03-20 04:12:52 +00003321 if (isa<RecordDecl>(OldDC)) {
John McCalla2a3f7d2010-03-16 21:48:18 +00003322 if (isa<FieldDecl>(ShadowedDecl))
3323 Kind = 3; // field
3324 else
3325 Kind = 2; // static data member
John McCall2d8c7602010-03-20 04:12:52 +00003326 } else if (OldDC->isFileContext())
John McCalla2a3f7d2010-03-16 21:48:18 +00003327 Kind = 1; // global
3328 else
3329 Kind = 0; // local
3330
John McCall2d8c7602010-03-20 04:12:52 +00003331 DeclarationName Name = R.getLookupName();
3332
John McCalla2a3f7d2010-03-16 21:48:18 +00003333 // Emit warning and note.
John McCall2d8c7602010-03-20 04:12:52 +00003334 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCalla2a3f7d2010-03-16 21:48:18 +00003335 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
3336}
3337
John McCalldf8b37c2010-03-22 09:20:08 +00003338/// \brief Check -Wshadow without the advantage of a previous lookup.
3339void Sema::CheckShadow(Scope *S, VarDecl *D) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003340 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
3341 Diagnostic::Ignored)
3342 return;
3343
John McCalldf8b37c2010-03-22 09:20:08 +00003344 LookupResult R(*this, D->getDeclName(), D->getLocation(),
3345 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
3346 LookupName(R, S);
3347 CheckShadow(S, D, R);
3348}
3349
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003350/// \brief Perform semantic checking on a newly-created variable
3351/// declaration.
3352///
3353/// This routine performs all of the type-checking required for a
Douglas Gregorf16a8a72009-05-01 15:47:09 +00003354/// variable declaration once it has been built. It is used both to
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003355/// check variables after they have been parsed and their declarators
Douglas Gregorf16a8a72009-05-01 15:47:09 +00003356/// have been translated into a declaration, and to check variables
3357/// that have been instantiated from a template.
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003358///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003359/// Sets NewVD->isInvalidDecl() if an error was encountered.
John McCall1f82f242009-11-18 22:49:29 +00003360void Sema::CheckVariableDeclaration(VarDecl *NewVD,
3361 LookupResult &Previous,
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003362 bool &Redeclaration) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003363 // If the decl is already known invalid, don't check it.
3364 if (NewVD->isInvalidDecl())
3365 return;
Mike Stump11289f42009-09-09 15:08:12 +00003366
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003367 QualType T = NewVD->getType();
3368
John McCall8b07ec22010-05-15 11:32:37 +00003369 if (T->isObjCObjectType()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003370 Diag(NewVD->getLocation(), diag::err_statically_allocated_object);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003371 return NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003372 }
Mike Stump11289f42009-09-09 15:08:12 +00003373
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003374 // Emit an error if an address space was applied to decl with local storage.
3375 // This includes arrays of objects with address space qualifiers, but not
3376 // automatic variables that point to other address spaces.
3377 // ISO/IEC TR 18037 S5.1.2
Chris Lattner88fdea82010-10-10 18:16:20 +00003378 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003379 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003380 return NewVD->setInvalidDecl();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003381 }
Fariborz Jahanian0c9404e2009-02-21 19:44:02 +00003382
Mike Stumpca5ae662009-04-14 00:57:29 +00003383 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003384 && !NewVD->hasAttr<BlocksAttr>())
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003385 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
Chris Lattner88fdea82010-10-10 18:16:20 +00003386
Chris Lattner9fecd742009-04-19 05:21:20 +00003387 bool isVM = T->isVariablyModifiedType();
Chris Lattner9662cd32009-07-19 20:17:11 +00003388 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalld4e1b762010-08-01 01:24:59 +00003389 NewVD->hasAttr<BlocksAttr>())
John McCallaab3e412010-08-25 08:40:02 +00003390 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00003391
Chris Lattner9fecd742009-04-19 05:21:20 +00003392 if ((isVM && NewVD->hasLinkage()) ||
3393 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson6c885802009-02-28 21:56:50 +00003394 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003395 llvm::APSInt Oversized;
Anders Carlsson6c885802009-02-28 21:56:50 +00003396 QualType FixedTy =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003397 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
3398 Oversized);
Mike Stump11289f42009-09-09 15:08:12 +00003399
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003400 if (FixedTy.isNull() && T->isVariableArrayType()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003401 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00003402 // FIXME: This won't give the correct result for
3403 // int a[10][n];
Anders Carlsson6c885802009-02-28 21:56:50 +00003404 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003405
Anders Carlsson6c885802009-02-28 21:56:50 +00003406 if (NewVD->isFileVarDecl())
3407 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003408 << SizeRange;
John McCall8e7d6562010-08-26 03:08:43 +00003409 else if (NewVD->getStorageClass() == SC_Static)
Anders Carlsson6c885802009-02-28 21:56:50 +00003410 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003411 << SizeRange;
Anders Carlsson6c885802009-02-28 21:56:50 +00003412 else
3413 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003414 << SizeRange;
3415 return NewVD->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003416 }
3417
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003418 if (FixedTy.isNull()) {
Anders Carlsson6c885802009-02-28 21:56:50 +00003419 if (NewVD->isFileVarDecl())
3420 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
3421 else
3422 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003423 return NewVD->setInvalidDecl();
Anders Carlsson6c885802009-02-28 21:56:50 +00003424 }
Mike Stump11289f42009-09-09 15:08:12 +00003425
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003426 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
3427 NewVD->setType(FixedTy);
Anders Carlsson6c885802009-02-28 21:56:50 +00003428 }
3429
John McCall1f82f242009-11-18 22:49:29 +00003430 if (Previous.empty() && NewVD->isExternC()) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003431 // Since we did not find anything by this name and we're declaring
3432 // an extern "C" variable, look for a non-visible extern "C"
3433 // declaration with the same name.
3434 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003435 = LocallyScopedExternalDecls.find(NewVD->getDeclName());
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003436 if (Pos != LocallyScopedExternalDecls.end())
John McCall1f82f242009-11-18 22:49:29 +00003437 Previous.addDecl(Pos->second);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003438 }
3439
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003440 if (T->isVoidType() && !NewVD->hasExternalStorage()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003441 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
3442 << T;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003443 return NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003444 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003445
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003446 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00003447 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
3448 return NewVD->setInvalidDecl();
3449 }
Mike Stump11289f42009-09-09 15:08:12 +00003450
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003451 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpa7128632009-05-01 23:41:47 +00003452 Diag(NewVD->getLocation(), diag::err_block_on_vm);
3453 return NewVD->setInvalidDecl();
3454 }
3455
Sebastian Redl5467c9f2010-07-12 23:11:43 +00003456 // Function pointers and references cannot have qualified function type, only
3457 // function pointer-to-members can do that.
3458 QualType Pointee;
3459 unsigned PtrOrRef = 0;
3460 if (const PointerType *Ptr = T->getAs<PointerType>())
3461 Pointee = Ptr->getPointeeType();
3462 else if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
3463 Pointee = Ref->getPointeeType();
3464 PtrOrRef = 1;
3465 }
3466 if (!Pointee.isNull() && Pointee->isFunctionProtoType() &&
3467 Pointee->getAs<FunctionProtoType>()->getTypeQuals() != 0) {
3468 Diag(NewVD->getLocation(), diag::err_invalid_qualified_function_pointer)
3469 << PtrOrRef;
3470 return NewVD->setInvalidDecl();
3471 }
3472
John McCall1f82f242009-11-18 22:49:29 +00003473 if (!Previous.empty()) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00003474 Redeclaration = true;
John McCall1f82f242009-11-18 22:49:29 +00003475 MergeVarDecl(NewVD, Previous);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003476 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003477}
3478
Douglas Gregor36d1b142009-10-06 17:59:45 +00003479/// \brief Data used with FindOverriddenMethod
3480struct FindOverriddenMethodData {
3481 Sema *S;
3482 CXXMethodDecl *Method;
3483};
3484
3485/// \brief Member lookup function that determines whether a given C++
3486/// method overrides a method in a base class, to be used with
3487/// CXXRecordDecl::lookupInBases().
John McCall84c16cf2009-11-12 03:15:40 +00003488static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregor36d1b142009-10-06 17:59:45 +00003489 CXXBasePath &Path,
3490 void *UserData) {
3491 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlssone985fae2009-11-26 20:50:40 +00003492
Douglas Gregor36d1b142009-10-06 17:59:45 +00003493 FindOverriddenMethodData *Data
3494 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlssone985fae2009-11-26 20:50:40 +00003495
3496 DeclarationName Name = Data->Method->getDeclName();
3497
3498 // FIXME: Do we care about other names here too?
3499 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCalle9cccd82010-06-16 08:42:20 +00003500 // We really want to find the base class destructor here.
Anders Carlssone985fae2009-11-26 20:50:40 +00003501 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
3502 CanQualType CT = Data->S->Context.getCanonicalType(T);
3503
Anders Carlsson5a4f7722009-11-27 01:26:58 +00003504 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlssone985fae2009-11-26 20:50:40 +00003505 }
3506
3507 for (Path.Decls = BaseRecord->lookup(Name);
Douglas Gregor36d1b142009-10-06 17:59:45 +00003508 Path.Decls.first != Path.Decls.second;
3509 ++Path.Decls.first) {
John McCall38e5f432010-06-16 09:33:39 +00003510 NamedDecl *D = *Path.Decls.first;
John McCalle9cccd82010-06-16 08:42:20 +00003511 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
3512 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregor36d1b142009-10-06 17:59:45 +00003513 return true;
3514 }
3515 }
3516
3517 return false;
3518}
3519
Sebastian Redld5b24532009-11-18 21:51:29 +00003520/// AddOverriddenMethods - See if a method overrides any in the base classes,
3521/// and if so, check that it's a valid override and remember it.
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00003522bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redld5b24532009-11-18 21:51:29 +00003523 // Look for virtual methods in base classes that this method might override.
3524 CXXBasePaths Paths;
3525 FindOverriddenMethodData Data;
3526 Data.Method = MD;
3527 Data.S = this;
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00003528 bool AddedAny = false;
Sebastian Redld5b24532009-11-18 21:51:29 +00003529 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
3530 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
3531 E = Paths.found_decls_end(); I != E; ++I) {
3532 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
3533 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Alexis Hunt96d5c762009-11-21 08:43:09 +00003534 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
Anders Carlsson3f610c72011-01-20 16:25:36 +00003535 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
Anders Carlssonf3935b42009-12-04 05:51:56 +00003536 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00003537 AddedAny = true;
3538 }
Sebastian Redld5b24532009-11-18 21:51:29 +00003539 }
3540 }
3541 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00003542
3543 return AddedAny;
Sebastian Redld5b24532009-11-18 21:51:29 +00003544}
3545
John McCallf7cfb222010-10-13 05:45:15 +00003546static void DiagnoseInvalidRedeclaration(Sema &S, FunctionDecl *NewFD) {
3547 LookupResult Prev(S, NewFD->getDeclName(), NewFD->getLocation(),
3548 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
3549 S.LookupQualifiedName(Prev, NewFD->getDeclContext());
3550 assert(!Prev.isAmbiguous() &&
3551 "Cannot have an ambiguity in previous-declaration lookup");
3552 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
3553 Func != FuncEnd; ++Func) {
3554 if (isa<FunctionDecl>(*Func) &&
3555 isNearlyMatchingFunction(S.Context, cast<FunctionDecl>(*Func), NewFD))
3556 S.Diag((*Func)->getLocation(), diag::note_member_def_close_match);
3557 }
3558}
3559
Mike Stump11289f42009-09-09 15:08:12 +00003560NamedDecl*
Zhongxing Xubece5d62009-01-16 01:13:29 +00003561Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
John McCallbcd03502009-12-07 02:54:59 +00003562 QualType R, TypeSourceInfo *TInfo,
John McCall1f82f242009-11-18 22:49:29 +00003563 LookupResult &Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003564 MultiTemplateParamsArg TemplateParamLists,
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003565 bool IsFunctionDefinition, bool &Redeclaration) {
Zhongxing Xubece5d62009-01-16 01:13:29 +00003566 assert(R.getTypePtr()->isFunctionType());
3567
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003568 // TODO: consider using NameInfo for diagnostic.
3569 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3570 DeclarationName Name = NameInfo.getName();
John McCall8e7d6562010-08-26 03:08:43 +00003571 FunctionDecl::StorageClass SC = SC_None;
Zhongxing Xubece5d62009-01-16 01:13:29 +00003572 switch (D.getDeclSpec().getStorageClassSpec()) {
3573 default: assert(0 && "Unknown storage class!");
3574 case DeclSpec::SCS_auto:
3575 case DeclSpec::SCS_register:
3576 case DeclSpec::SCS_mutable:
Mike Stump11289f42009-09-09 15:08:12 +00003577 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregore62c0a42009-02-24 01:23:02 +00003578 diag::err_typecheck_sclass_func);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003579 D.setInvalidType();
Zhongxing Xubece5d62009-01-16 01:13:29 +00003580 break;
John McCall8e7d6562010-08-26 03:08:43 +00003581 case DeclSpec::SCS_unspecified: SC = SC_None; break;
3582 case DeclSpec::SCS_extern: SC = SC_Extern; break;
Douglas Gregore62c0a42009-02-24 01:23:02 +00003583 case DeclSpec::SCS_static: {
Sebastian Redl50c68252010-08-31 00:36:30 +00003584 if (CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregore62c0a42009-02-24 01:23:02 +00003585 // C99 6.7.1p5:
3586 // The declaration of an identifier for a function that has
3587 // block scope shall have no explicit storage-class specifier
3588 // other than extern
3589 // See also (C++ [dcl.stc]p4).
Mike Stump11289f42009-09-09 15:08:12 +00003590 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregore62c0a42009-02-24 01:23:02 +00003591 diag::err_static_block_func);
John McCall8e7d6562010-08-26 03:08:43 +00003592 SC = SC_None;
Douglas Gregore62c0a42009-02-24 01:23:02 +00003593 } else
John McCall8e7d6562010-08-26 03:08:43 +00003594 SC = SC_Static;
Douglas Gregore62c0a42009-02-24 01:23:02 +00003595 break;
3596 }
Gabor Greif80c21832010-09-08 00:31:13 +00003597 case DeclSpec::SCS_private_extern: SC = SC_PrivateExtern; break;
Zhongxing Xubece5d62009-01-16 01:13:29 +00003598 }
3599
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003600 if (D.getDeclSpec().isThreadSpecified())
3601 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
3602
Chris Lattner347eec92009-04-11 19:17:25 +00003603 // Do not allow returning a objc interface by-value.
John McCall8b07ec22010-05-15 11:32:37 +00003604 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
Chris Lattner347eec92009-04-11 19:17:25 +00003605 Diag(D.getIdentifierLoc(),
3606 diag::err_object_cannot_be_passed_returned_by_value) << 0
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003607 << R->getAs<FunctionType>()->getResultType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003608 D.setInvalidType();
Chris Lattner347eec92009-04-11 19:17:25 +00003609 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003610
Zhongxing Xubece5d62009-01-16 01:13:29 +00003611 FunctionDecl *NewFD;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003612 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor513e63c2010-12-10 19:28:19 +00003613 bool isFriend = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003614 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
3615 FunctionDecl::StorageClass SCAsWritten
3616 = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
Douglas Gregor513e63c2010-12-10 19:28:19 +00003617 FunctionTemplateDecl *FunctionTemplate = 0;
3618 bool isExplicitSpecialization = false;
3619 bool isFunctionTemplateSpecialization = false;
3620 unsigned NumMatchedTemplateParamLists = 0;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003621
3622 if (!getLangOptions().CPlusPlus) {
Douglas Gregor2797d322009-03-19 18:33:54 +00003623 // Determine whether the function was written with a
3624 // prototype. This true when:
Douglas Gregor2797d322009-03-19 18:33:54 +00003625 // - there is a prototype in the declarator, or
3626 // - the type R of the function is some kind of typedef or other reference
3627 // to a type name (which eventually refers to a function type).
Mike Stump11289f42009-09-09 15:08:12 +00003628 bool HasPrototype =
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003629 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003630 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
3631
Abramo Bagnaradff19302011-03-08 08:55:46 +00003632 NewFD = FunctionDecl::Create(Context, DC, D.getSourceRange().getBegin(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003633 NameInfo, R, TInfo, SC, SCAsWritten, isInline,
Douglas Gregorc4df4072010-04-19 22:54:31 +00003634 HasPrototype);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003635 if (D.isInvalidType())
3636 NewFD->setInvalidDecl();
3637
3638 // Set the lexical context.
3639 NewFD->setLexicalDeclContext(CurContext);
3640 // Filter out previous declarations that don't match the scope.
Douglas Gregordb446112011-03-07 16:54:27 +00003641 FilterLookupForScope(*this, Previous, DC, S, NewFD->hasLinkage(),
3642 /*ExplicitInstantiationOrSpecialization=*/false);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003643 } else {
3644 isFriend = D.getDeclSpec().isFriendSpecified();
Douglas Gregor513e63c2010-12-10 19:28:19 +00003645 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
3646 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
3647 bool isVirtualOkay = false;
Zhongxing Xubece5d62009-01-16 01:13:29 +00003648
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003649 // Check that the return type is not an abstract class type.
3650 // For record types, this is done by the AbstractClassUsageDiagnoser once
3651 // the class has been completely parsed.
3652 if (!DC->isRecord() &&
3653 RequireNonAbstractType(D.getIdentifierLoc(),
3654 R->getAs<FunctionType>()->getResultType(),
3655 diag::err_abstract_type_in_decl,
3656 AbstractReturnType))
3657 D.setInvalidType();
Mike Stump11289f42009-09-09 15:08:12 +00003658
John McCall3e11ebe2010-03-15 10:12:16 +00003659
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003660 if (isFriend) {
3661 // C++ [class.friend]p5
3662 // A function can be defined in a friend declaration of a
3663 // class . . . . Such a function is implicitly inline.
3664 isInline |= IsFunctionDefinition;
3665 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00003666
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003667 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
3668 // This is a C++ constructor declaration.
3669 assert(DC->isRecord() &&
3670 "Constructors can only be declared in a member context");
3671
3672 R = CheckConstructorDeclarator(D, R, SC);
3673
3674 // Create the new declaration
3675 NewFD = CXXConstructorDecl::Create(Context,
3676 cast<CXXRecordDecl>(DC),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003677 D.getSourceRange().getBegin(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003678 NameInfo, R, TInfo,
3679 isExplicit, isInline,
3680 /*isImplicitlyDeclared=*/false);
3681 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
3682 // This is a C++ destructor declaration.
3683 if (DC->isRecord()) {
3684 R = CheckDestructorDeclarator(D, R, SC);
3685
3686 NewFD = CXXDestructorDecl::Create(Context,
3687 cast<CXXRecordDecl>(DC),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003688 D.getSourceRange().getBegin(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003689 NameInfo, R, TInfo,
3690 isInline,
3691 /*isImplicitlyDeclared=*/false);
3692 isVirtualOkay = true;
3693 } else {
3694 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
3695
3696 // Create a FunctionDecl to satisfy the function definition parsing
3697 // code path.
Abramo Bagnaradff19302011-03-08 08:55:46 +00003698 NewFD = FunctionDecl::Create(Context, DC, D.getSourceRange().getBegin(),
3699 D.getIdentifierLoc(), Name, R, TInfo,
3700 SC, SCAsWritten, isInline,
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003701 /*hasPrototype=*/true);
3702 D.setInvalidType();
3703 }
3704 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
3705 if (!DC->isRecord()) {
3706 Diag(D.getIdentifierLoc(),
3707 diag::err_conv_function_not_member);
3708 return 0;
3709 }
3710
3711 CheckConversionDeclarator(D, R, SC);
3712 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003713 D.getSourceRange().getBegin(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003714 NameInfo, R, TInfo,
Douglas Gregorf2f08062011-03-08 17:10:18 +00003715 isInline, isExplicit,
3716 SourceLocation());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003717
3718 isVirtualOkay = true;
3719 } else if (DC->isRecord()) {
3720 // If the of the function is the same as the name of the record, then this
3721 // must be an invalid constructor that has a return type.
3722 // (The parser checks for a return type and makes the declarator a
3723 // constructor if it has no return type).
3724 // must have an invalid constructor that has a return type
3725 if (Name.getAsIdentifierInfo() &&
3726 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
3727 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
3728 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3729 << SourceRange(D.getIdentifierLoc());
3730 return 0;
3731 }
3732
3733 bool isStatic = SC == SC_Static;
3734
3735 // [class.free]p1:
3736 // Any allocation function for a class T is a static member
3737 // (even if not explicitly declared static).
3738 if (Name.getCXXOverloadedOperator() == OO_New ||
3739 Name.getCXXOverloadedOperator() == OO_Array_New)
3740 isStatic = true;
3741
3742 // [class.free]p6 Any deallocation function for a class X is a static member
3743 // (even if not explicitly declared static).
3744 if (Name.getCXXOverloadedOperator() == OO_Delete ||
3745 Name.getCXXOverloadedOperator() == OO_Array_Delete)
3746 isStatic = true;
3747
3748 // This is a C++ method declaration.
3749 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003750 D.getSourceRange().getBegin(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003751 NameInfo, R, TInfo,
Douglas Gregorf2f08062011-03-08 17:10:18 +00003752 isStatic, SCAsWritten, isInline,
3753 SourceLocation());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003754
3755 isVirtualOkay = !isStatic;
3756 } else {
3757 // Determine whether the function was written with a
3758 // prototype. This true when:
3759 // - we're in C++ (where every function has a prototype),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003760 NewFD = FunctionDecl::Create(Context, DC, D.getSourceRange().getBegin(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003761 NameInfo, R, TInfo, SC, SCAsWritten, isInline,
3762 true/*HasPrototype*/);
3763 }
3764 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003765 isExplicitSpecialization = false;
3766 isFunctionTemplateSpecialization = false;
3767 NumMatchedTemplateParamLists = TemplateParamLists.size();
3768 if (D.isInvalidType())
3769 NewFD->setInvalidDecl();
3770
3771 // Set the lexical context. If the declarator has a C++
3772 // scope specifier, or is the object of a friend declaration, the
3773 // lexical context will be different from the semantic context.
3774 NewFD->setLexicalDeclContext(CurContext);
3775
3776 // Match up the template parameter lists with the scope specifier, then
3777 // determine whether we have a template or a template specialization.
3778 bool Invalid = false;
3779 if (TemplateParameterList *TemplateParams
Douglas Gregor93ded322011-03-04 22:45:55 +00003780 = MatchTemplateParametersToScopeSpecifier(
Douglas Gregord8d297c2009-07-21 23:53:31 +00003781 D.getDeclSpec().getSourceRange().getBegin(),
3782 D.getCXXScopeSpec(),
John McCall2c2eb122010-10-16 06:59:13 +00003783 TemplateParamLists.get(),
3784 TemplateParamLists.size(),
3785 isFriend,
3786 isExplicitSpecialization,
3787 Invalid)) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003788 // All but one template parameter lists have been matching.
3789 --NumMatchedTemplateParamLists;
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003790
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003791 if (TemplateParams->size() > 0) {
3792 // This is a function template
Mike Stump11289f42009-09-09 15:08:12 +00003793
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003794 // Check that we can declare a template here.
3795 if (CheckTemplateDeclScope(S, TemplateParams))
3796 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003797
Douglas Gregor93ded322011-03-04 22:45:55 +00003798 // A destructor cannot be a template.
3799 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
3800 Diag(NewFD->getLocation(), diag::err_destructor_template);
3801 return 0;
3802 }
3803
3804
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003805 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
Douglas Gregorc1da0f02009-06-24 00:23:40 +00003806 NewFD->getLocation(),
3807 Name, TemplateParams,
3808 NewFD);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003809 FunctionTemplate->setLexicalDeclContext(CurContext);
3810 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
3811 } else {
3812 // This is a function template specialization.
3813 isFunctionTemplateSpecialization = true;
John McCall816d75b2010-03-24 07:46:06 +00003814
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003815 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
3816 if (isFriend && isFunctionTemplateSpecialization) {
3817 // We want to remove the "template<>", found here.
3818 SourceRange RemoveRange = TemplateParams->getSourceRange();
John McCall1f0479e2010-03-24 08:27:58 +00003819
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003820 // If we remove the template<> and the name is not a
3821 // template-id, we're actually silently creating a problem:
3822 // the friend declaration will refer to an untemplated decl,
3823 // and clearly the user wants a template specialization. So
3824 // we need to insert '<>' after the name.
3825 SourceLocation InsertLoc;
3826 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
3827 InsertLoc = D.getName().getSourceRange().getEnd();
3828 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
3829 }
3830
3831 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
3832 << Name << RemoveRange
3833 << FixItHint::CreateRemoval(RemoveRange)
3834 << FixItHint::CreateInsertion(InsertLoc, "<>");
3835 }
3836 }
John McCall1f0479e2010-03-24 08:27:58 +00003837 }
3838
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003839 if (NumMatchedTemplateParamLists > 0 && D.getCXXScopeSpec().isSet()) {
3840 NewFD->setTemplateParameterListsInfo(Context,
3841 NumMatchedTemplateParamLists,
3842 TemplateParamLists.release());
3843 }
3844
3845 if (Invalid) {
3846 NewFD->setInvalidDecl();
3847 if (FunctionTemplate)
3848 FunctionTemplate->setInvalidDecl();
3849 }
3850
3851 // C++ [dcl.fct.spec]p5:
3852 // The virtual specifier shall only be used in declarations of
3853 // nonstatic class member functions that appear within a
3854 // member-specification of a class declaration; see 10.3.
3855 //
3856 if (isVirtual && !NewFD->isInvalidDecl()) {
3857 if (!isVirtualOkay) {
3858 Diag(D.getDeclSpec().getVirtualSpecLoc(),
3859 diag::err_virtual_non_function);
3860 } else if (!CurContext->isRecord()) {
3861 // 'virtual' was specified outside of the class.
Anders Carlssone9738992011-01-22 14:43:56 +00003862 Diag(D.getDeclSpec().getVirtualSpecLoc(),
3863 diag::err_virtual_out_of_class)
3864 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
3865 } else if (NewFD->getDescribedFunctionTemplate()) {
3866 // C++ [temp.mem]p3:
3867 // A member function template shall not be virtual.
3868 Diag(D.getDeclSpec().getVirtualSpecLoc(),
3869 diag::err_virtual_member_function_template)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003870 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
3871 } else {
3872 // Okay: Add virtual to the method.
3873 NewFD->setVirtualAsWritten(true);
John McCall816d75b2010-03-24 07:46:06 +00003874 }
Douglas Gregorc1da0f02009-06-24 00:23:40 +00003875 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003876
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003877 // C++ [dcl.fct.spec]p3:
3878 // The inline specifier shall not appear on a block scope function declaration.
3879 if (isInline && !NewFD->isInvalidDecl()) {
3880 if (CurContext->isFunctionOrMethod()) {
3881 // 'inline' is not allowed on block scope function declaration.
3882 Diag(D.getDeclSpec().getInlineSpecLoc(),
3883 diag::err_inline_declaration_block_scope) << Name
3884 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
3885 }
3886 }
3887
3888 // C++ [dcl.fct.spec]p6:
3889 // The explicit specifier shall be used only in the declaration of a
3890 // constructor or conversion function within its class definition; see 12.3.1
3891 // and 12.3.2.
3892 if (isExplicit && !NewFD->isInvalidDecl()) {
3893 if (!CurContext->isRecord()) {
3894 // 'explicit' was specified outside of the class.
3895 Diag(D.getDeclSpec().getExplicitSpecLoc(),
3896 diag::err_explicit_out_of_class)
3897 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
3898 } else if (!isa<CXXConstructorDecl>(NewFD) &&
3899 !isa<CXXConversionDecl>(NewFD)) {
3900 // 'explicit' was specified on a function that wasn't a constructor
3901 // or conversion function.
3902 Diag(D.getDeclSpec().getExplicitSpecLoc(),
3903 diag::err_explicit_non_ctor_or_conv_function)
3904 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
3905 }
3906 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003907
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003908 // Filter out previous declarations that don't match the scope.
Douglas Gregordb446112011-03-07 16:54:27 +00003909 FilterLookupForScope(*this, Previous, DC, S, NewFD->hasLinkage(),
3910 isExplicitSpecialization ||
3911 isFunctionTemplateSpecialization);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003912
3913 if (isFriend) {
3914 // For now, claim that the objects have no previous declaration.
3915 if (FunctionTemplate) {
3916 FunctionTemplate->setObjectOfFriendDecl(false);
3917 FunctionTemplate->setAccess(AS_public);
3918 }
3919 NewFD->setObjectOfFriendDecl(false);
3920 NewFD->setAccess(AS_public);
3921 }
3922
John McCall357d0f32010-12-15 04:00:32 +00003923 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && IsFunctionDefinition) {
3924 // A method is implicitly inline if it's defined in its class
3925 // definition.
3926 NewFD->setImplicitlyInline();
3927 }
3928
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003929 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
3930 !CurContext->isRecord()) {
3931 // C++ [class.static]p1:
3932 // A data or function member of a class may be declared static
3933 // in a class definition, in which case it is a static member of
3934 // the class.
3935
3936 // Complain about the 'static' specifier if it's on an out-of-line
3937 // member function definition.
3938 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
3939 diag::err_static_out_of_line)
3940 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3941 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003942 }
3943
Zhongxing Xubece5d62009-01-16 01:13:29 +00003944 // Handle GNU asm-label extension (encoded as an attribute).
3945 if (Expr *E = (Expr*) D.getAsmLabel()) {
3946 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00003947 StringLiteral *SE = cast<StringLiteral>(E);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003948 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
3949 SE->getString()));
Zhongxing Xubece5d62009-01-16 01:13:29 +00003950 }
3951
Chris Lattner9af40c12009-04-25 06:12:16 +00003952 // Copy the parameter declarations from the declarator D to the function
3953 // declaration NewFD, if they are available. First scavenge them into Params.
3954 llvm::SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara6d810632010-12-14 22:11:44 +00003955 if (D.isFunctionDeclarator()) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003956 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xubece5d62009-01-16 01:13:29 +00003957
Zhongxing Xubece5d62009-01-16 01:13:29 +00003958 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
3959 // function that takes no arguments, not a function that takes a
3960 // single void argument.
3961 // We let through "const void" here because Sema::GetTypeForDeclarator
3962 // already checks for that case.
3963 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3964 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00003965 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
Chris Lattner9af40c12009-04-25 06:12:16 +00003966 // Empty arg list, don't push any params.
John McCall48871652010-08-21 09:40:31 +00003967 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[0].Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00003968
3969 // In C++, the empty parameter-type-list must be spelled "void"; a
3970 // typedef of void is not permitted.
3971 if (getLangOptions().CPlusPlus &&
Chris Lattner3f863f62009-04-25 05:44:12 +00003972 Param->getType().getUnqualifiedType() != Context.VoidTy)
Douglas Gregor170512f2009-04-01 23:51:29 +00003973 Diag(Param->getLocation(), diag::err_param_typedef_of_void);
Zhongxing Xubece5d62009-01-16 01:13:29 +00003974 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00003975 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +00003976 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00003977 assert(Param->getDeclContext() != NewFD && "Was set before ?");
3978 Param->setDeclContext(NewFD);
3979 Params.push_back(Param);
John McCallb7238602010-04-14 01:27:20 +00003980
3981 if (Param->isInvalidDecl())
3982 NewFD->setInvalidDecl();
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00003983 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00003984 }
Mike Stump11289f42009-09-09 15:08:12 +00003985
John McCall9dd450b2009-09-21 23:43:11 +00003986 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner47c0d002009-04-25 06:03:53 +00003987 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xubece5d62009-01-16 01:13:29 +00003988 // following example, we'll need to synthesize (unnamed)
3989 // parameters for use in the declaration.
3990 //
3991 // @code
3992 // typedef void fn(int);
3993 // fn f;
3994 // @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003995
Chris Lattner47c0d002009-04-25 06:03:53 +00003996 // Synthesize a parameter for each argument type.
Chris Lattner47c0d002009-04-25 06:03:53 +00003997 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
3998 AE = FT->arg_type_end(); AI != AE; ++AI) {
John McCalla3ccba02010-06-04 11:21:44 +00003999 ParmVarDecl *Param =
4000 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
Chris Lattner47c0d002009-04-25 06:03:53 +00004001 Params.push_back(Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00004002 }
Chris Lattner49303b22009-04-25 18:38:18 +00004003 } else {
4004 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
4005 "Should not need args for typedef of non-prototype fn");
Zhongxing Xubece5d62009-01-16 01:13:29 +00004006 }
Chris Lattner9af40c12009-04-25 06:12:16 +00004007 // Finally, we know we have the right number of parameters, install them.
Douglas Gregord5058122010-02-11 01:19:42 +00004008 NewFD->setParams(Params.data(), Params.size());
Mike Stump11289f42009-09-09 15:08:12 +00004009
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004010 // Process the non-inheritable attributes on this declaration.
4011 ProcessDeclAttributes(S, NewFD, D,
4012 /*NonInheritable=*/true, /*Inheritable=*/false);
4013
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004014 if (!getLangOptions().CPlusPlus) {
4015 // Perform semantic checking on the function declaration.
Fariborz Jahanian352d5e52010-12-10 17:05:33 +00004016 bool isExplctSpecialization=false;
4017 CheckFunctionDeclaration(S, NewFD, Previous, isExplctSpecialization,
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004018 Redeclaration);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004019 assert((NewFD->isInvalidDecl() || !Redeclaration ||
4020 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
4021 "previous declaration set still overloaded");
4022 } else {
4023 // If the declarator is a template-id, translate the parser's template
4024 // argument list into our AST format.
4025 bool HasExplicitTemplateArgs = false;
4026 TemplateArgumentListInfo TemplateArgs;
4027 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4028 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4029 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4030 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
4031 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4032 TemplateId->getTemplateArgs(),
4033 TemplateId->NumArgs);
4034 translateTemplateArguments(TemplateArgsPtr,
4035 TemplateArgs);
4036 TemplateArgsPtr.release();
Douglas Gregor0e876e02009-09-25 23:53:26 +00004037
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004038 HasExplicitTemplateArgs = true;
Douglas Gregor0e876e02009-09-25 23:53:26 +00004039
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004040 if (FunctionTemplate) {
Douglas Gregora5f6f9c2011-01-24 18:54:39 +00004041 // Function template with explicit template arguments.
4042 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
4043 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
4044
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004045 HasExplicitTemplateArgs = false;
4046 } else if (!isFunctionTemplateSpecialization &&
4047 !D.getDeclSpec().isFriendSpecified()) {
4048 // We have encountered something that the user meant to be a
4049 // specialization (because it has explicitly-specified template
4050 // arguments) but that was not introduced with a "template<>" (or had
4051 // too few of them).
4052 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
4053 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
4054 << FixItHint::CreateInsertion(
4055 D.getDeclSpec().getSourceRange().getBegin(),
4056 "template<> ");
4057 isFunctionTemplateSpecialization = true;
John McCallf7cfb222010-10-13 05:45:15 +00004058 } else {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004059 // "friend void foo<>(int);" is an implicit specialization decl.
4060 isFunctionTemplateSpecialization = true;
Francois Pichet6d76e6c2010-10-01 21:19:28 +00004061 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004062 } else if (isFriend && isFunctionTemplateSpecialization) {
4063 // This combination is only possible in a recovery case; the user
4064 // wrote something like:
4065 // template <> friend void foo(int);
4066 // which we're recovering from as if the user had written:
4067 // friend void foo<>(int);
4068 // Go ahead and fake up a template id.
4069 HasExplicitTemplateArgs = true;
4070 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
4071 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004072 }
John McCallf7cfb222010-10-13 05:45:15 +00004073
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004074 // If it's a friend (and only if it's a friend), it's possible
4075 // that either the specialized function type or the specialized
4076 // template is dependent, and therefore matching will fail. In
4077 // this case, don't check the specialization yet.
4078 if (isFunctionTemplateSpecialization && isFriend &&
4079 (NewFD->getType()->isDependentType() || DC->isDependentContext())) {
4080 assert(HasExplicitTemplateArgs &&
4081 "friend function specialization without template args");
4082 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
4083 Previous))
4084 NewFD->setInvalidDecl();
4085 } else if (isFunctionTemplateSpecialization) {
Douglas Gregor6203d492011-03-08 02:04:14 +00004086 if (CurContext->isDependentContext() && CurContext->isRecord()) {
4087 Diag(NewFD->getLocation(), diag::err_function_specialization_in_class)
4088 << NewFD->getDeclName();
4089 NewFD->setInvalidDecl();
4090 return 0;
4091 } else if (CheckFunctionTemplateSpecialization(NewFD,
4092 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
4093 Previous))
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004094 NewFD->setInvalidDecl();
4095 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
4096 if (CheckMemberSpecialization(NewFD, Previous))
4097 NewFD->setInvalidDecl();
4098 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004099
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004100 // Perform semantic checking on the function declaration.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004101 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization,
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004102 Redeclaration);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004103
4104 assert((NewFD->isInvalidDecl() || !Redeclaration ||
4105 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
4106 "previous declaration set still overloaded");
4107
4108 NamedDecl *PrincipalDecl = (FunctionTemplate
4109 ? cast<NamedDecl>(FunctionTemplate)
4110 : NewFD);
4111
4112 if (isFriend && Redeclaration) {
4113 AccessSpecifier Access = AS_public;
4114 if (!NewFD->isInvalidDecl())
4115 Access = NewFD->getPreviousDeclaration()->getAccess();
4116
4117 NewFD->setAccess(Access);
4118 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
4119
4120 PrincipalDecl->setObjectOfFriendDecl(true);
4121 }
4122
4123 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
4124 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4125 PrincipalDecl->setNonMemberOperator();
4126
4127 // If we have a function template, check the template parameter
4128 // list. This will check and merge default template arguments.
4129 if (FunctionTemplate) {
4130 FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration();
4131 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
4132 PrevTemplate? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregora99fb4c2011-02-04 04:20:44 +00004133 D.getDeclSpec().isFriendSpecified()
4134 ? (IsFunctionDefinition
4135 ? TPC_FriendFunctionTemplateDefinition
4136 : TPC_FriendFunctionTemplate)
4137 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor4d5c2972011-02-04 12:22:53 +00004138 DC && DC->isRecord() &&
4139 DC->isDependentContext())
Douglas Gregora99fb4c2011-02-04 04:20:44 +00004140 ? TPC_ClassTemplateMember
4141 : TPC_FunctionTemplate);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004142 }
4143
4144 if (NewFD->isInvalidDecl()) {
4145 // Ignore all the rest of this.
4146 } else if (!Redeclaration) {
4147 // Fake up an access specifier if it's supposed to be a class member.
4148 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
4149 NewFD->setAccess(AS_public);
4150
4151 // Qualified decls generally require a previous declaration.
4152 if (D.getCXXScopeSpec().isSet()) {
4153 // ...with the major exception of templated-scope or
4154 // dependent-scope friend declarations.
4155
4156 // TODO: we currently also suppress this check in dependent
4157 // contexts because (1) the parameter depth will be off when
4158 // matching friend templates and (2) we might actually be
4159 // selecting a friend based on a dependent factor. But there
4160 // are situations where these conditions don't apply and we
4161 // can actually do this check immediately.
4162 if (isFriend &&
4163 (NumMatchedTemplateParamLists ||
4164 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
4165 CurContext->isDependentContext())) {
4166 // ignore these
4167 } else {
4168 // The user tried to provide an out-of-line definition for a
4169 // function that is a member of a class or namespace, but there
4170 // was no such member function declared (C++ [class.mfct]p2,
4171 // C++ [namespace.memdef]p2). For example:
4172 //
4173 // class X {
4174 // void f() const;
4175 // };
4176 //
4177 // void X::f() { } // ill-formed
4178 //
4179 // Complain about this problem, and attempt to suggest close
4180 // matches (e.g., those that differ only in cv-qualifiers and
4181 // whether the parameter types are references).
4182 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
4183 << Name << DC << D.getCXXScopeSpec().getRange();
4184 NewFD->setInvalidDecl();
4185
4186 DiagnoseInvalidRedeclaration(*this, NewFD);
4187 }
4188
4189 // Unqualified local friend declarations are required to resolve
4190 // to something.
4191 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
4192 Diag(D.getIdentifierLoc(), diag::err_no_matching_local_friend);
4193 NewFD->setInvalidDecl();
4194 DiagnoseInvalidRedeclaration(*this, NewFD);
4195 }
4196
4197 } else if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
4198 !isFriend && !isFunctionTemplateSpecialization &&
4199 !isExplicitSpecialization) {
4200 // An out-of-line member function declaration must also be a
4201 // definition (C++ [dcl.meaning]p1).
4202 // Note that this is not the case for explicit specializations of
4203 // function templates or member functions of class templates, per
4204 // C++ [temp.expl.spec]p2. We also allow these declarations as an extension
4205 // for compatibility with old SWIG code which likes to generate them.
4206 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
4207 << D.getCXXScopeSpec().getRange();
4208 }
4209 }
4210
4211
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004212 // Handle attributes. We need to have merged decls when handling attributes
4213 // (for example to check for conflicts, etc).
4214 // FIXME: This needs to happen before we merge declarations. Then,
4215 // let attribute merging cope with attribute conflicts.
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004216 ProcessDeclAttributes(S, NewFD, D,
4217 /*NonInheritable=*/false, /*Inheritable=*/true);
Ryan Flynne5dc8592009-07-25 22:29:44 +00004218
4219 // attributes declared post-definition are currently ignored
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004220 // FIXME: This should happen during attribute merging
John McCall1f82f242009-11-18 22:49:29 +00004221 if (Redeclaration && Previous.isSingleResult()) {
4222 const FunctionDecl *Def;
4223 FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00004224 if (PrevFD && PrevFD->hasBody(Def) && D.hasAttributes()) {
Ryan Flynne5dc8592009-07-25 22:29:44 +00004225 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
4226 Diag(Def->getLocation(), diag::note_previous_definition);
4227 }
4228 }
4229
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004230 AddKnownFunctionAttributes(NewFD);
4231
Douglas Gregor72609052010-08-06 13:50:58 +00004232 if (NewFD->hasAttr<OverloadableAttr>() &&
4233 !NewFD->getType()->getAs<FunctionProtoType>()) {
4234 Diag(NewFD->getLocation(),
4235 diag::err_attribute_overloadable_no_prototype)
4236 << NewFD;
4237
4238 // Turn this into a variadic function with no parameters.
4239 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
John McCalldb40c7f2010-12-14 08:05:40 +00004240 FunctionProtoType::ExtProtoInfo EPI;
4241 EPI.Variadic = true;
4242 EPI.ExtInfo = FT->getExtInfo();
4243
4244 QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI);
Douglas Gregor72609052010-08-06 13:50:58 +00004245 NewFD->setType(R);
4246 }
4247
Eli Friedman570024a2010-08-05 06:57:20 +00004248 // If there's a #pragma GCC visibility in scope, and this isn't a class
4249 // member, set the visibility of this function.
4250 if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
4251 AddPushedVisibilityAttribute(NewFD);
4252
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004253 // If this is a locally-scoped extern C function, update the
4254 // map of such names.
Douglas Gregor16618f22009-09-12 00:17:51 +00004255 if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004256 && !NewFD->isInvalidDecl())
John McCall1f82f242009-11-18 22:49:29 +00004257 RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004258
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00004259 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraea947882011-03-08 16:41:52 +00004260 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00004261
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004262 if (getLangOptions().CPlusPlus) {
4263 if (FunctionTemplate) {
4264 if (NewFD->isInvalidDecl())
4265 FunctionTemplate->setInvalidDecl();
4266 return FunctionTemplate;
4267 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004268 }
Mike Stump11289f42009-09-09 15:08:12 +00004269
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004270 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004271
4272 if (getLangOptions().CUDA)
4273 if (IdentifierInfo *II = NewFD->getIdentifier())
4274 if (!NewFD->isInvalidDecl() &&
4275 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
4276 if (II->isStr("cudaConfigureCall")) {
4277 if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
4278 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
4279
4280 Context.setcudaConfigureCallDecl(NewFD);
4281 }
4282 }
4283
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004284 return NewFD;
4285}
4286
4287/// \brief Perform semantic checking of a new function declaration.
4288///
4289/// Performs semantic analysis of the new function declaration
4290/// NewFD. This routine performs all semantic checking that does not
4291/// require the actual declarator involved in the declaration, and is
4292/// used both for the declaration of functions as they are parsed
4293/// (called via ActOnDeclarator) and for the declaration of functions
4294/// that have been instantiated via C++ template instantiation (called
4295/// via InstantiateDecl).
4296///
Douglas Gregorcf915552009-10-13 16:30:37 +00004297/// \param IsExplicitSpecialiation whether this new function declaration is
4298/// an explicit specialization of the previous declaration.
4299///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004300/// This sets NewFD->isInvalidDecl() to true if there was an error.
John McCall84d87672009-12-10 09:41:52 +00004301void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall1f82f242009-11-18 22:49:29 +00004302 LookupResult &Previous,
Douglas Gregorcf915552009-10-13 16:30:37 +00004303 bool IsExplicitSpecialization,
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004304 bool &Redeclaration) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004305 // If NewFD is already known erroneous, don't do any of this checking.
John McCall12d53da2010-08-12 00:57:17 +00004306 if (NewFD->isInvalidDecl()) {
4307 // If this is a class member, mark the class invalid immediately.
4308 // This avoids some consistency errors later.
4309 if (isa<CXXMethodDecl>(NewFD))
4310 cast<CXXMethodDecl>(NewFD)->getParent()->setInvalidDecl();
4311
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004312 return;
John McCall12d53da2010-08-12 00:57:17 +00004313 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004314
Eli Friedman54135832009-05-16 12:15:55 +00004315 if (NewFD->getResultType()->isVariablyModifiedType()) {
4316 // Functions returning a variably modified type violate C99 6.7.5.2p2
4317 // because all functions have linkage.
4318 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
4319 return NewFD->setInvalidDecl();
4320 }
4321
Douglas Gregor16618f22009-09-12 00:17:51 +00004322 if (NewFD->isMain())
4323 CheckMain(NewFD);
John McCalld9baf6a2009-07-24 03:03:21 +00004324
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004325 // Check for a previous declaration of this name.
John McCall1f82f242009-11-18 22:49:29 +00004326 if (Previous.empty() && NewFD->isExternC()) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004327 // Since we did not find anything by this name and we're declaring
4328 // an extern "C" function, look for a non-visible extern "C"
4329 // declaration with the same name.
4330 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004331 = LocallyScopedExternalDecls.find(NewFD->getDeclName());
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004332 if (Pos != LocallyScopedExternalDecls.end())
John McCall1f82f242009-11-18 22:49:29 +00004333 Previous.addDecl(Pos->second);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004334 }
4335
Douglas Gregore62c0a42009-02-24 01:23:02 +00004336 // Merge or overload the declaration with an existing declaration of
4337 // the same name, if appropriate.
John McCall1f82f242009-11-18 22:49:29 +00004338 if (!Previous.empty()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00004339 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xubece5d62009-01-16 01:13:29 +00004340 // a declaration that requires merging. If it's an overload,
4341 // there's no more work to do here; we'll just add the new
4342 // function to the scope.
Douglas Gregor633b7372009-02-13 00:26:38 +00004343
John McCall1f82f242009-11-18 22:49:29 +00004344 NamedDecl *OldDecl = 0;
John McCalldaa3d6b2009-12-09 03:35:25 +00004345 if (!AllowOverloadingOfFunction(Previous, Context)) {
4346 Redeclaration = true;
4347 OldDecl = Previous.getFoundDecl();
4348 } else {
John McCalle9cccd82010-06-16 08:42:20 +00004349 switch (CheckOverload(S, NewFD, Previous, OldDecl,
4350 /*NewIsUsingDecl*/ false)) {
John McCalldaa3d6b2009-12-09 03:35:25 +00004351 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00004352 Redeclaration = true;
John McCalldaa3d6b2009-12-09 03:35:25 +00004353 break;
4354
4355 case Ovl_NonFunction:
4356 Redeclaration = true;
4357 break;
4358
4359 case Ovl_Overload:
4360 Redeclaration = false;
4361 break;
John McCall1f82f242009-11-18 22:49:29 +00004362 }
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004363
4364 if (!getLangOptions().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
4365 // If a function name is overloadable in C, then every function
4366 // with that name must be marked "overloadable".
4367 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
4368 << Redeclaration << NewFD;
4369 NamedDecl *OverloadedDecl = 0;
4370 if (Redeclaration)
4371 OverloadedDecl = OldDecl;
4372 else if (!Previous.empty())
4373 OverloadedDecl = Previous.getRepresentativeDecl();
4374 if (OverloadedDecl)
4375 Diag(OverloadedDecl->getLocation(),
4376 diag::note_attribute_overloadable_prev_overload);
4377 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
4378 Context));
4379 }
John McCall1f82f242009-11-18 22:49:29 +00004380 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004381
John McCall1f82f242009-11-18 22:49:29 +00004382 if (Redeclaration) {
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004383 // NewFD and OldDecl represent declarations that need to be
Mike Stump11289f42009-09-09 15:08:12 +00004384 // merged.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00004385 if (MergeFunctionDecl(NewFD, OldDecl))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004386 return NewFD->setInvalidDecl();
Zhongxing Xubece5d62009-01-16 01:13:29 +00004387
John McCall1f82f242009-11-18 22:49:29 +00004388 Previous.clear();
4389 Previous.addDecl(OldDecl);
4390
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004391 if (FunctionTemplateDecl *OldTemplateDecl
Douglas Gregorca027af2009-10-12 22:27:17 +00004392 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
Douglas Gregorcf915552009-10-13 16:30:37 +00004393 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
Douglas Gregorca027af2009-10-12 22:27:17 +00004394 FunctionTemplateDecl *NewTemplateDecl
4395 = NewFD->getDescribedFunctionTemplate();
4396 assert(NewTemplateDecl && "Template/non-template mismatch");
4397 if (CXXMethodDecl *Method
4398 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
4399 Method->setAccess(OldTemplateDecl->getAccess());
4400 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
4401 }
Douglas Gregorcf915552009-10-13 16:30:37 +00004402
4403 // If this is an explicit specialization of a member that is a function
4404 // template, mark it as a member specialization.
4405 if (IsExplicitSpecialization &&
4406 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
4407 NewTemplateDecl->setMemberSpecialization();
4408 assert(OldTemplateDecl->isMemberSpecialization());
4409 }
Douglas Gregorca027af2009-10-12 22:27:17 +00004410 } else {
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00004411 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
4412 NewFD->setAccess(OldDecl->getAccess());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004413 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00004414 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004415 }
Douglas Gregor8af63e42009-02-06 17:46:57 +00004416 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004417
Anders Carlsson1b12ed42009-09-13 21:33:06 +00004418 // Semantic checking for this function declaration (in isolation).
4419 if (getLangOptions().CPlusPlus) {
4420 // C++-specific checks.
4421 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
4422 CheckConstructor(Constructor);
Anders Carlsson2a50e952009-11-15 22:49:34 +00004423 } else if (CXXDestructorDecl *Destructor =
4424 dyn_cast<CXXDestructorDecl>(NewFD)) {
4425 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson1b12ed42009-09-13 21:33:06 +00004426 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson2a50e952009-11-15 22:49:34 +00004427
Douglas Gregor7454c562010-07-02 20:37:36 +00004428 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson2a50e952009-11-15 22:49:34 +00004429 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson1b12ed42009-09-13 21:33:06 +00004430 if (!ClassType->isDependentType()) {
4431 DeclarationName Name
4432 = Context.DeclarationNames.getCXXDestructorName(
4433 Context.getCanonicalType(ClassType));
4434 if (NewFD->getDeclName() != Name) {
4435 Diag(NewFD->getLocation(), diag::err_destructor_name);
4436 return NewFD->setInvalidDecl();
4437 }
4438 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00004439 } else if (CXXConversionDecl *Conversion
Douglas Gregor21920e372009-12-01 17:24:26 +00004440 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00004441 ActOnConversionDeclarator(Conversion);
Douglas Gregor21920e372009-12-01 17:24:26 +00004442 }
4443
4444 // Find any virtual functions that this function overrides.
Douglas Gregor6be3de32009-12-01 17:35:23 +00004445 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
4446 if (!Method->isFunctionTemplateSpecialization() &&
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004447 !Method->getDescribedFunctionTemplate()) {
4448 if (AddOverriddenMethods(Method->getParent(), Method)) {
4449 // If the function was marked as "static", we have a problem.
4450 if (NewFD->getStorageClass() == SC_Static) {
4451 Diag(NewFD->getLocation(), diag::err_static_overrides_virtual)
4452 << NewFD->getDeclName();
4453 for (CXXMethodDecl::method_iterator
4454 Overridden = Method->begin_overridden_methods(),
4455 OverriddenEnd = Method->end_overridden_methods();
4456 Overridden != OverriddenEnd;
4457 ++Overridden) {
4458 Diag((*Overridden)->getLocation(),
4459 diag::note_overridden_virtual_function);
4460 }
4461 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004462 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004463 }
Douglas Gregor6be3de32009-12-01 17:35:23 +00004464 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00004465
4466 // Extra checking for C++ overloaded operators (C++ [over.oper]).
4467 if (NewFD->isOverloadedOperator() &&
4468 CheckOverloadedOperatorDeclaration(NewFD))
4469 return NewFD->setInvalidDecl();
Alexis Huntc88db062010-01-13 09:01:02 +00004470
4471 // Extra checking for C++0x literal operators (C++0x [over.literal]).
4472 if (NewFD->getLiteralIdentifier() &&
4473 CheckLiteralOperatorDeclaration(NewFD))
4474 return NewFD->setInvalidDecl();
4475
Anders Carlsson1b12ed42009-09-13 21:33:06 +00004476 // In C++, check default arguments now that we have merged decls. Unless
4477 // the lexical context is the class, because in this case this is done
4478 // during delayed parsing anyway.
4479 if (!CurContext->isRecord())
4480 CheckCXXDefaultArguments(NewFD);
Douglas Gregor9246b682010-12-21 19:47:46 +00004481
4482 // If this function declares a builtin function, check the type of this
4483 // declaration against the expected type for the builtin.
4484 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
4485 ASTContext::GetBuiltinTypeError Error;
4486 QualType T = Context.GetBuiltinType(BuiltinID, Error);
4487 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
4488 // The type of this function differs from the type of the builtin,
4489 // so forget about the builtin entirely.
4490 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
4491 }
4492 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00004493 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004494}
4495
John McCalld9baf6a2009-07-24 03:03:21 +00004496void Sema::CheckMain(FunctionDecl* FD) {
John McCall02dee0a2009-07-25 04:36:53 +00004497 // C++ [basic.start.main]p3: A program that declares main to be inline
4498 // or static is ill-formed.
4499 // C99 6.7.4p4: In a hosted environment, the inline function specifier
4500 // shall not appear in a declaration of main.
4501 // static main is not an error under C99, but we should warn about it.
Douglas Gregor35b57532009-10-27 21:01:01 +00004502 bool isInline = FD->isInlineSpecified();
John McCall8e7d6562010-08-26 03:08:43 +00004503 bool isStatic = FD->getStorageClass() == SC_Static;
John McCall02dee0a2009-07-25 04:36:53 +00004504 if (isInline || isStatic) {
4505 unsigned diagID = diag::warn_unusual_main_decl;
4506 if (isInline || getLangOptions().CPlusPlus)
4507 diagID = diag::err_unusual_main_decl;
4508
4509 int which = isStatic + (isInline << 1) - 1;
4510 Diag(FD->getLocation(), diagID) << which;
4511 }
4512
4513 QualType T = FD->getType();
4514 assert(T->isFunctionType() && "function decl is not of function type");
John McCall9dd450b2009-09-21 23:43:11 +00004515 const FunctionType* FT = T->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00004516
John McCall02dee0a2009-07-25 04:36:53 +00004517 if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
Douglas Gregorf05c0952011-02-19 19:04:23 +00004518 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
John McCall02dee0a2009-07-25 04:36:53 +00004519 FD->setInvalidDecl(true);
4520 }
4521
4522 // Treat protoless main() as nullary.
4523 if (isa<FunctionNoProtoType>(FT)) return;
4524
4525 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
4526 unsigned nparams = FTP->getNumArgs();
4527 assert(FD->getNumParams() == nparams);
4528
John McCall0e21fcc2009-12-24 09:58:38 +00004529 bool HasExtraParameters = (nparams > 3);
4530
4531 // Darwin passes an undocumented fourth argument of type char**. If
4532 // other platforms start sprouting these, the logic below will start
4533 // getting shifty.
4534 if (nparams == 4 &&
4535 Context.Target.getTriple().getOS() == llvm::Triple::Darwin)
4536 HasExtraParameters = false;
4537
4538 if (HasExtraParameters) {
John McCall02dee0a2009-07-25 04:36:53 +00004539 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
4540 FD->setInvalidDecl(true);
4541 nparams = 3;
4542 }
4543
4544 // FIXME: a lot of the following diagnostics would be improved
4545 // if we had some location information about types.
4546
4547 QualType CharPP =
4548 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall0e21fcc2009-12-24 09:58:38 +00004549 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall02dee0a2009-07-25 04:36:53 +00004550
4551 for (unsigned i = 0; i < nparams; ++i) {
4552 QualType AT = FTP->getArgType(i);
4553
4554 bool mismatch = true;
4555
4556 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
4557 mismatch = false;
4558 else if (Expected[i] == CharPP) {
4559 // As an extension, the following forms are okay:
4560 // char const **
4561 // char const * const *
4562 // char * const *
4563
John McCall8ccfcb52009-09-24 19:53:00 +00004564 QualifierCollector qs;
John McCall02dee0a2009-07-25 04:36:53 +00004565 const PointerType* PT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004566 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
4567 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
John McCall02dee0a2009-07-25 04:36:53 +00004568 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
4569 qs.removeConst();
4570 mismatch = !qs.empty();
4571 }
4572 }
4573
4574 if (mismatch) {
4575 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
4576 // TODO: suggest replacing given type with expected type
4577 FD->setInvalidDecl(true);
4578 }
4579 }
4580
4581 if (nparams == 1 && !FD->isInvalidDecl()) {
4582 Diag(FD->getLocation(), diag::warn_main_one_arg);
4583 }
Douglas Gregorbff62032010-10-21 16:57:46 +00004584
4585 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
4586 Diag(FD->getLocation(), diag::err_main_template_decl);
4587 FD->setInvalidDecl();
4588 }
John McCalld9baf6a2009-07-24 03:03:21 +00004589}
4590
Eli Friedmand5a55bd2008-05-20 13:48:25 +00004591bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00004592 // FIXME: Need strict checking. In C89, we need to check for
4593 // any assignment, increment, decrement, function-calls, or
4594 // commas outside of a sizeof. In C99, it's the same list,
4595 // except that the aforementioned are allowed in unevaluated
4596 // expressions. Everything else falls under the
4597 // "may accept other forms of constant expressions" exception.
4598 // (We never end up here for C++, so the constant expression
4599 // rules there don't matter.)
John McCall8b0f4ff2010-08-02 21:13:48 +00004600 if (Init->isConstantInitializer(Context, false))
Eli Friedman7bfab362009-02-22 06:45:27 +00004601 return false;
Eli Friedman4f294cf2009-02-26 04:47:58 +00004602 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
4603 << Init->getSourceRange();
Eli Friedmand5a55bd2008-05-20 13:48:25 +00004604 return true;
Steve Naroff98f72032008-01-10 22:15:12 +00004605}
4606
Douglas Gregor5fb53972009-01-14 15:45:31 +00004607/// AddInitializerToDecl - Adds the initializer Init to the
4608/// declaration dcl. If DirectInit is true, this is C++ direct
4609/// initialization rather than copy initialization.
Richard Smith30482bc2011-02-20 03:19:35 +00004610void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
4611 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner8beb9de2007-10-19 20:10:30 +00004612 // If there is no declaration, there was an error parsing it. Just ignore
4613 // the initializer.
Richard Smith30482bc2011-02-20 03:19:35 +00004614 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner8beb9de2007-10-19 20:10:30 +00004615 return;
Mike Stump11289f42009-09-09 15:08:12 +00004616
Douglas Gregor0c880302009-03-11 23:00:04 +00004617 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
4618 // With declarators parsed the way they are, the parser cannot
4619 // distinguish between a normal initializer and a pure-specifier.
4620 // Thus this grotesque test.
4621 IntegerLiteral *IL;
Douglas Gregor0c880302009-03-11 23:00:04 +00004622 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor21920e372009-12-01 17:24:26 +00004623 Context.getCanonicalType(IL->getType()) == Context.IntTy)
4624 CheckPureMethod(Method, Init->getSourceRange());
4625 else {
Douglas Gregor0c880302009-03-11 23:00:04 +00004626 Diag(Method->getLocation(), diag::err_member_function_initialization)
4627 << Method->getDeclName() << Init->getSourceRange();
4628 Method->setInvalidDecl();
4629 }
4630 return;
4631 }
4632
Steve Naroff437b4d82007-09-12 20:13:48 +00004633 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4634 if (!VDecl) {
Douglas Gregor0c880302009-03-11 23:00:04 +00004635 if (getLangOptions().CPlusPlus &&
4636 RealDecl->getLexicalDeclContext()->isRecord() &&
4637 isa<NamedDecl>(RealDecl))
John McCalldb768922010-09-10 23:21:22 +00004638 Diag(RealDecl->getLocation(), diag::err_member_initialization);
Douglas Gregor0c880302009-03-11 23:00:04 +00004639 else
4640 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +00004641 RealDecl->setInvalidDecl();
4642 return;
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00004643 }
4644
Richard Smith30482bc2011-02-20 03:19:35 +00004645 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
4646 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00004647 QualType DeducedType;
4648 if (!DeduceAutoType(VDecl->getType(), Init, DeducedType)) {
4649 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
4650 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4651 << Init->getSourceRange();
4652 RealDecl->setInvalidDecl();
4653 return;
4654 }
4655 VDecl->setType(DeducedType);
4656
4657 // If this is a redeclaration, check that the type we just deduced matches
4658 // the previously declared type.
4659 if (VarDecl *Old = VDecl->getPreviousDeclaration())
4660 MergeVarDeclTypes(VDecl, Old);
4661 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00004662
4663
Eli Friedmanc9827d12009-11-14 03:40:14 +00004664 // A definition must end up with a complete type, which means it must be
4665 // complete with the restriction that an array type might be completed by the
4666 // initializer; note that later code assumes this restriction.
4667 QualType BaseDeclType = VDecl->getType();
4668 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
4669 BaseDeclType = Array->getElementType();
4670 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
Eli Friedman337cd3a2009-04-13 21:28:54 +00004671 diag::err_typecheck_decl_incomplete_type)) {
4672 RealDecl->setInvalidDecl();
4673 return;
4674 }
4675
Douglas Gregorc99f1552009-12-03 18:33:45 +00004676 // The variable can not have an abstract class type.
4677 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4678 diag::err_abstract_type_in_decl,
4679 AbstractVariableType))
4680 VDecl->setInvalidDecl();
4681
Sebastian Redl5ca79842010-02-01 20:16:42 +00004682 const VarDecl *Def;
4683 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00004684 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor0760fa12009-03-10 23:43:53 +00004685 << VDecl->getDeclName();
4686 Diag(Def->getLocation(), diag::note_previous_definition);
4687 VDecl->setInvalidDecl();
4688 return;
4689 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00004690
Douglas Gregorf0f83692010-08-24 05:27:49 +00004691 const VarDecl* PrevInit = 0;
Douglas Gregor71f39c92010-12-16 01:31:22 +00004692 if (getLangOptions().CPlusPlus) {
4693 // C++ [class.static.data]p4
4694 // If a static data member is of const integral or const
4695 // enumeration type, its declaration in the class definition can
4696 // specify a constant-initializer which shall be an integral
4697 // constant expression (5.19). In that case, the member can appear
4698 // in integral constant expressions. The member shall still be
4699 // defined in a namespace scope if it is used in the program and the
4700 // namespace scope definition shall not contain an initializer.
4701 //
4702 // We already performed a redefinition check above, but for static
4703 // data members we also need to check whether there was an in-class
4704 // declaration with an initializer.
4705 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
4706 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
4707 Diag(PrevInit->getLocation(), diag::note_previous_definition);
4708 return;
4709 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00004710
Douglas Gregor71f39c92010-12-16 01:31:22 +00004711 if (VDecl->hasLocalStorage())
4712 getCurFunction()->setHasBranchProtectedScope();
4713
4714 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
4715 VDecl->setInvalidDecl();
4716 return;
4717 }
4718 }
John McCalld4e1b762010-08-01 01:24:59 +00004719
Douglas Gregor85dabae2009-12-16 01:38:02 +00004720 // Capture the variable that is being initialized and the style of
4721 // initialization.
4722 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4723
4724 // FIXME: Poor source location information.
4725 InitializationKind Kind
4726 = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(),
4727 Init->getLocStart(),
4728 Init->getLocEnd())
4729 : InitializationKind::CreateCopy(VDecl->getLocation(),
4730 Init->getLocStart());
4731
Steve Naroff61091402007-09-12 14:07:44 +00004732 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +00004733 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +00004734 QualType DclT = VDecl->getType(), SavT = DclT;
John McCall1c9c3fd2010-10-15 04:57:14 +00004735 if (VDecl->isLocalVarDecl()) {
Daniel Dunbar0ca16602009-04-14 02:25:56 +00004736 if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
Steve Naroff437b4d82007-09-12 20:13:48 +00004737 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff08899ff2008-04-15 22:42:06 +00004738 VDecl->setInvalidDecl();
4739 } else if (!VDecl->isInvalidDecl()) {
Eli Friedman78275202009-12-19 08:11:05 +00004740 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
John McCalldadc5752010-08-24 06:29:42 +00004741 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00004742 MultiExprArg(*this, &Init, 1),
Eli Friedman463e5232009-12-22 02:10:53 +00004743 &DclT);
4744 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00004745 VDecl->setInvalidDecl();
Eli Friedman78275202009-12-19 08:11:05 +00004746 return;
4747 }
Mike Stump11289f42009-09-09 15:08:12 +00004748
Eli Friedman463e5232009-12-22 02:10:53 +00004749 Init = Result.takeAs<Expr>();
4750
Anders Carlsson41e08812008-08-22 05:00:02 +00004751 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmance982572009-02-20 01:34:21 +00004752 // Don't check invalid declarations to avoid emitting useless diagnostics.
4753 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
John McCall8e7d6562010-08-26 03:08:43 +00004754 if (VDecl->getStorageClass() == SC_Static) // C99 6.7.8p4.
Anders Carlsson41e08812008-08-22 05:00:02 +00004755 CheckForConstantInitializer(Init, DclT);
4756 }
Steve Naroff61091402007-09-12 14:07:44 +00004757 }
Mike Stump11289f42009-09-09 15:08:12 +00004758 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor0c880302009-03-11 23:00:04 +00004759 VDecl->getLexicalDeclContext()->isRecord()) {
4760 // This is an in-class initialization for a static data member, e.g.,
4761 //
4762 // struct S {
4763 // static const int value = 17;
4764 // };
4765
John McCalldb768922010-09-10 23:21:22 +00004766 // Try to perform the initialization regardless.
4767 if (!VDecl->isInvalidDecl()) {
4768 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
4769 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
4770 MultiExprArg(*this, &Init, 1),
4771 &DclT);
4772 if (Result.isInvalid()) {
4773 VDecl->setInvalidDecl();
4774 return;
4775 }
4776
4777 Init = Result.takeAs<Expr>();
4778 }
Douglas Gregor0c880302009-03-11 23:00:04 +00004779
4780 // C++ [class.mem]p4:
4781 // A member-declarator can contain a constant-initializer only
4782 // if it declares a static member (9.4) of const integral or
4783 // const enumeration type, see 9.4.2.
4784 QualType T = VDecl->getType();
John McCalldb768922010-09-10 23:21:22 +00004785
4786 // Do nothing on dependent types.
4787 if (T->isDependentType()) {
4788
4789 // Require constness.
4790 } else if (!T.isConstQualified()) {
4791 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
4792 << Init->getSourceRange();
Douglas Gregor0c880302009-03-11 23:00:04 +00004793 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00004794
4795 // We allow integer constant expressions in all cases.
4796 } else if (T->isIntegralOrEnumerationType()) {
4797 if (!Init->isValueDependent()) {
Douglas Gregor0c880302009-03-11 23:00:04 +00004798 // Check whether the expression is a constant expression.
4799 llvm::APSInt Value;
4800 SourceLocation Loc;
4801 if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) {
4802 Diag(Loc, diag::err_in_class_initializer_non_constant)
4803 << Init->getSourceRange();
4804 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00004805 }
4806 }
4807
4808 // We allow floating-point constants as an extension in C++03, and
4809 // C++0x has far more complicated rules that we don't really
4810 // implement fully.
4811 } else {
4812 bool Allowed = false;
4813 if (getLangOptions().CPlusPlus0x) {
4814 Allowed = T->isLiteralType();
4815 } else if (T->isFloatingType()) { // also permits complex, which is ok
4816 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
4817 << T << Init->getSourceRange();
4818 Allowed = true;
4819 }
4820
4821 if (!Allowed) {
4822 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
4823 << T << Init->getSourceRange();
4824 VDecl->setInvalidDecl();
4825
4826 // TODO: there are probably expressions that pass here that shouldn't.
4827 } else if (!Init->isValueDependent() &&
4828 !Init->isConstantInitializer(Context, false)) {
4829 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
4830 << Init->getSourceRange();
4831 VDecl->setInvalidDecl();
Douglas Gregor0c880302009-03-11 23:00:04 +00004832 }
4833 }
Steve Naroff08899ff2008-04-15 22:42:06 +00004834 } else if (VDecl->isFileVarDecl()) {
Douglas Gregord4e1fb52010-10-15 01:21:46 +00004835 if (VDecl->getStorageClassAsWritten() == SC_Extern &&
Douglas Gregorfceea362010-04-22 14:36:26 +00004836 (!getLangOptions().CPlusPlus ||
4837 !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
Steve Naroff437b4d82007-09-12 20:13:48 +00004838 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedman463e5232009-12-22 02:10:53 +00004839 if (!VDecl->isInvalidDecl()) {
4840 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
John McCalldadc5752010-08-24 06:29:42 +00004841 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00004842 MultiExprArg(*this, &Init, 1),
Eli Friedman463e5232009-12-22 02:10:53 +00004843 &DclT);
4844 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00004845 VDecl->setInvalidDecl();
Eli Friedman463e5232009-12-22 02:10:53 +00004846 return;
4847 }
4848
4849 Init = Result.takeAs<Expr>();
4850 }
Mike Stump11289f42009-09-09 15:08:12 +00004851
Anders Carlsson41e08812008-08-22 05:00:02 +00004852 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmance982572009-02-20 01:34:21 +00004853 // Don't check invalid declarations to avoid emitting useless diagnostics.
4854 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
Anders Carlsson41e08812008-08-22 05:00:02 +00004855 // C99 6.7.8p4. All file scoped initializers need to be constant.
4856 CheckForConstantInitializer(Init, DclT);
4857 }
Steve Naroff61091402007-09-12 14:07:44 +00004858 }
4859 // If the type changed, it means we had an incomplete type that was
Mike Stump11289f42009-09-09 15:08:12 +00004860 // completed by the initializer. For example:
Steve Naroff61091402007-09-12 14:07:44 +00004861 // int ary[] = { 1, 3, 5 };
4862 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb2ed9afd2007-11-29 19:09:19 +00004863 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff437b4d82007-09-12 20:13:48 +00004864 VDecl->setType(DclT);
Christopher Lamb2ed9afd2007-11-29 19:09:19 +00004865 Init->setType(DclT);
4866 }
Mike Stump11289f42009-09-09 15:08:12 +00004867
Chris Lattner88fdea82010-10-10 18:16:20 +00004868
4869 // If this variable is a local declaration with record type, make sure it
4870 // doesn't have a flexible member initialization. We only support this as a
4871 // global/static definition.
4872 if (VDecl->hasLocalStorage())
4873 if (const RecordType *RT = VDecl->getType()->getAs<RecordType>())
Douglas Gregor1f81ced2010-10-15 23:53:28 +00004874 if (RT->getDecl()->hasFlexibleArrayMember()) {
4875 // Check whether the initializer tries to initialize the flexible
4876 // array member itself to anything other than an empty initializer list.
4877 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
4878 unsigned Index = std::distance(RT->getDecl()->field_begin(),
4879 RT->getDecl()->field_end()) - 1;
4880 if (Index < ILE->getNumInits() &&
4881 !(isa<InitListExpr>(ILE->getInit(Index)) &&
4882 cast<InitListExpr>(ILE->getInit(Index))->getNumInits() == 0)) {
4883 Diag(VDecl->getLocation(), diag::err_nonstatic_flexible_variable);
4884 VDecl->setInvalidDecl();
4885 }
4886 }
Chris Lattner88fdea82010-10-10 18:16:20 +00004887 }
4888
John McCallacf0ee52010-10-08 02:01:28 +00004889 // Check any implicit conversions within the expression.
4890 CheckImplicitConversions(Init, VDecl->getLocation());
4891
John McCall5d413782010-12-06 08:20:24 +00004892 Init = MaybeCreateExprWithCleanups(Init);
Steve Naroff61091402007-09-12 14:07:44 +00004893 // Attach the initializer to the decl.
Douglas Gregord5058122010-02-11 01:19:42 +00004894 VDecl->setInit(Init);
Douglas Gregorbeecd582009-04-21 17:11:58 +00004895
John McCall8b7fd8f12011-01-19 11:48:09 +00004896 CheckCompleteVariableDeclaration(VDecl);
Steve Naroff61091402007-09-12 14:07:44 +00004897}
4898
John McCalleae5acb2010-03-31 02:13:20 +00004899/// ActOnInitializerError - Given that there was an error parsing an
4900/// initializer for the given declaration, try to return to some form
4901/// of sanity.
John McCall48871652010-08-21 09:40:31 +00004902void Sema::ActOnInitializerError(Decl *D) {
John McCalleae5acb2010-03-31 02:13:20 +00004903 // Our main concern here is re-establishing invariants like "a
4904 // variable's type is either dependent or complete".
John McCalleae5acb2010-03-31 02:13:20 +00004905 if (!D || D->isInvalidDecl()) return;
4906
4907 VarDecl *VD = dyn_cast<VarDecl>(D);
4908 if (!VD) return;
4909
Richard Smith30482bc2011-02-20 03:19:35 +00004910 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smithb2bc2e62011-02-21 20:05:19 +00004911 if (ParsingInitForAutoVars.count(D)) {
4912 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00004913 return;
4914 }
4915
John McCalleae5acb2010-03-31 02:13:20 +00004916 QualType Ty = VD->getType();
4917 if (Ty->isDependentType()) return;
4918
4919 // Require a complete type.
4920 if (RequireCompleteType(VD->getLocation(),
4921 Context.getBaseElementType(Ty),
4922 diag::err_typecheck_decl_incomplete_type)) {
4923 VD->setInvalidDecl();
4924 return;
4925 }
4926
4927 // Require an abstract type.
4928 if (RequireNonAbstractType(VD->getLocation(), Ty,
4929 diag::err_abstract_type_in_decl,
4930 AbstractVariableType)) {
4931 VD->setInvalidDecl();
4932 return;
4933 }
4934
4935 // Don't bother complaining about constructors or destructors,
4936 // though.
4937}
4938
John McCall48871652010-08-21 09:40:31 +00004939void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith30482bc2011-02-20 03:19:35 +00004940 bool TypeMayContainAuto) {
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00004941 // If there is no declaration, there was an error parsing it. Just ignore it.
4942 if (RealDecl == 0)
4943 return;
4944
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004945 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
4946 QualType Type = Var->getType();
Douglas Gregorbeecd582009-04-21 17:11:58 +00004947
Anders Carlssonae019932009-07-11 00:34:39 +00004948 // C++0x [dcl.spec.auto]p3
Richard Smith30482bc2011-02-20 03:19:35 +00004949 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlssonae019932009-07-11 00:34:39 +00004950 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
4951 << Var->getDeclName() << Type;
4952 Var->setInvalidDecl();
4953 return;
4954 }
Mike Stump11289f42009-09-09 15:08:12 +00004955
Douglas Gregore6565622010-02-09 07:26:29 +00004956 switch (Var->isThisDeclarationADefinition()) {
4957 case VarDecl::Definition:
4958 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
4959 break;
4960
4961 // We have an out-of-line definition of a static data member
4962 // that has an in-class initializer, so we type-check this like
4963 // a declaration.
4964 //
4965 // Fall through
4966
4967 case VarDecl::DeclarationOnly:
4968 // It's only a declaration.
4969
4970 // Block scope. C99 6.7p7: If an identifier for an object is
4971 // declared with no linkage (C99 6.2.2p6), the type for the
4972 // object shall be complete.
John McCall1c9c3fd2010-10-15 04:57:14 +00004973 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Douglas Gregore6565622010-02-09 07:26:29 +00004974 !Var->getLinkage() && !Var->isInvalidDecl() &&
4975 RequireCompleteType(Var->getLocation(), Type,
4976 diag::err_typecheck_decl_incomplete_type))
4977 Var->setInvalidDecl();
4978
4979 // Make sure that the type is not abstract.
4980 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
4981 RequireNonAbstractType(Var->getLocation(), Type,
4982 diag::err_abstract_type_in_decl,
4983 AbstractVariableType))
4984 Var->setInvalidDecl();
4985 return;
4986
4987 case VarDecl::TentativeDefinition:
4988 // File scope. C99 6.9.2p2: A declaration of an identifier for an
4989 // object that has file scope without an initializer, and without a
4990 // storage-class specifier or with the storage-class specifier "static",
4991 // constitutes a tentative definition. Note: A tentative definition with
4992 // external linkage is valid (C99 6.2.2p5).
4993 if (!Var->isInvalidDecl()) {
4994 if (const IncompleteArrayType *ArrayT
4995 = Context.getAsIncompleteArrayType(Type)) {
4996 if (RequireCompleteType(Var->getLocation(),
4997 ArrayT->getElementType(),
4998 diag::err_illegal_decl_array_incomplete_type))
4999 Var->setInvalidDecl();
John McCall8e7d6562010-08-26 03:08:43 +00005000 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregore6565622010-02-09 07:26:29 +00005001 // C99 6.9.2p3: If the declaration of an identifier for an object is
5002 // a tentative definition and has internal linkage (C99 6.2.2p3), the
5003 // declared type shall not be an incomplete type.
5004 // NOTE: code such as the following
5005 // static struct s;
5006 // struct s { int a; };
5007 // is accepted by gcc. Hence here we issue a warning instead of
5008 // an error and we do not invalidate the static declaration.
5009 // NOTE: to avoid multiple warnings, only check the first declaration.
5010 if (Var->getPreviousDeclaration() == 0)
5011 RequireCompleteType(Var->getLocation(), Type,
5012 diag::ext_typecheck_decl_incomplete_type);
5013 }
5014 }
5015
5016 // Record the tentative definition; we're done.
5017 if (!Var->isInvalidDecl())
5018 TentativeDefinitions.push_back(Var);
5019 return;
5020 }
5021
5022 // Provide a specific diagnostic for uninitialized variable
5023 // definitions with incomplete array type.
5024 if (Type->isIncompleteArrayType()) {
Sebastian Redl10600672009-11-05 19:47:47 +00005025 Diag(Var->getLocation(),
5026 diag::err_typecheck_incomplete_array_needs_initializer);
5027 Var->setInvalidDecl();
5028 return;
5029 }
5030
John McCalla755f0f2010-08-01 01:25:24 +00005031 // Provide a specific diagnostic for uninitialized variable
5032 // definitions with reference type.
5033 if (Type->isReferenceType()) {
5034 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
5035 << Var->getDeclName()
5036 << SourceRange(Var->getLocation(), Var->getLocation());
5037 Var->setInvalidDecl();
5038 return;
5039 }
Douglas Gregore6565622010-02-09 07:26:29 +00005040
5041 // Do not attempt to type-check the default initializer for a
5042 // variable with dependent type.
5043 if (Type->isDependentType())
Douglas Gregor86d142a2009-10-08 07:24:58 +00005044 return;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005045
Douglas Gregore6565622010-02-09 07:26:29 +00005046 if (Var->isInvalidDecl())
5047 return;
Douglas Gregorc99f1552009-12-03 18:33:45 +00005048
Douglas Gregore6565622010-02-09 07:26:29 +00005049 if (RequireCompleteType(Var->getLocation(),
5050 Context.getBaseElementType(Type),
5051 diag::err_typecheck_decl_incomplete_type)) {
5052 Var->setInvalidDecl();
5053 return;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00005054 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005055
Douglas Gregore6565622010-02-09 07:26:29 +00005056 // The variable can not have an abstract class type.
5057 if (RequireNonAbstractType(Var->getLocation(), Type,
5058 diag::err_abstract_type_in_decl,
5059 AbstractVariableType)) {
5060 Var->setInvalidDecl();
5061 return;
5062 }
5063
Douglas Gregor589973b2010-03-08 02:45:10 +00005064 const RecordType *Record
5065 = Context.getBaseElementType(Type)->getAs<RecordType>();
5066 if (Record && getLangOptions().CPlusPlus && !getLangOptions().CPlusPlus0x &&
5067 cast<CXXRecordDecl>(Record->getDecl())->isPOD()) {
5068 // C++03 [dcl.init]p9:
5069 // If no initializer is specified for an object, and the
5070 // object is of (possibly cv-qualified) non-POD class type (or
5071 // array thereof), the object shall be default-initialized; if
5072 // the object is of const-qualified type, the underlying class
5073 // type shall have a user-declared default
5074 // constructor. Otherwise, if no initializer is specified for
5075 // a non- static object, the object and its subobjects, if
5076 // any, have an indeterminate initial value); if the object
5077 // or any of its subobjects are of const-qualified type, the
5078 // program is ill-formed.
5079 // FIXME: DPG thinks it is very fishy that C++0x disables this.
5080 } else {
John McCalld4e1b762010-08-01 01:24:59 +00005081 // Check for jumps past the implicit initializer. C++0x
5082 // clarifies that this applies to a "variable with automatic
5083 // storage duration", not a "local variable".
5084 if (getLangOptions().CPlusPlus && Var->hasLocalStorage())
John McCallaab3e412010-08-25 08:40:02 +00005085 getCurFunction()->setHasBranchProtectedScope();
John McCalld4e1b762010-08-01 01:24:59 +00005086
Douglas Gregor589973b2010-03-08 02:45:10 +00005087 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
5088 InitializationKind Kind
5089 = InitializationKind::CreateDefault(Var->getLocation());
Douglas Gregore6565622010-02-09 07:26:29 +00005090
Douglas Gregor589973b2010-03-08 02:45:10 +00005091 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00005092 ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
5093 MultiExprArg(*this, 0, 0));
Douglas Gregor589973b2010-03-08 02:45:10 +00005094 if (Init.isInvalid())
5095 Var->setInvalidDecl();
John McCall8b7fd8f12011-01-19 11:48:09 +00005096 else if (Init.get())
Douglas Gregora40433a2010-12-07 00:41:46 +00005097 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Douglas Gregore6565622010-02-09 07:26:29 +00005098 }
Douglas Gregor589973b2010-03-08 02:45:10 +00005099
John McCall8b7fd8f12011-01-19 11:48:09 +00005100 CheckCompleteVariableDeclaration(Var);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005101 }
5102}
5103
John McCall8b7fd8f12011-01-19 11:48:09 +00005104void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
5105 if (var->isInvalidDecl()) return;
5106
5107 // All the following checks are C++ only.
5108 if (!getLangOptions().CPlusPlus) return;
5109
5110 QualType baseType = Context.getBaseElementType(var->getType());
5111 if (baseType->isDependentType()) return;
5112
5113 // __block variables might require us to capture a copy-initializer.
5114 if (var->hasAttr<BlocksAttr>()) {
5115 // It's currently invalid to ever have a __block variable with an
5116 // array type; should we diagnose that here?
5117
5118 // Regardless, we don't want to ignore array nesting when
5119 // constructing this copy.
5120 QualType type = var->getType();
5121
5122 if (type->isStructureOrClassType()) {
5123 SourceLocation poi = var->getLocation();
5124 Expr *varRef = new (Context) DeclRefExpr(var, type, VK_LValue, poi);
5125 ExprResult result =
5126 PerformCopyInitialization(
5127 InitializedEntity::InitializeBlock(poi, type, false),
5128 poi, Owned(varRef));
5129 if (!result.isInvalid()) {
5130 result = MaybeCreateExprWithCleanups(result);
5131 Expr *init = result.takeAs<Expr>();
5132 Context.setBlockVarCopyInits(var, init);
5133 }
5134 }
5135 }
5136
5137 // Check for global constructors.
5138 if (!var->getDeclContext()->isDependentContext() &&
5139 var->hasGlobalStorage() &&
5140 !var->isStaticLocal() &&
5141 var->getInit() &&
5142 !var->getInit()->isConstantInitializer(Context,
5143 baseType->isReferenceType()))
5144 Diag(var->getLocation(), diag::warn_global_constructor)
5145 << var->getInit()->getSourceRange();
5146
5147 // Require the destructor.
5148 if (const RecordType *recordType = baseType->getAs<RecordType>())
5149 FinalizeVarWithDestructor(var, recordType);
5150}
5151
Richard Smithb2bc2e62011-02-21 20:05:19 +00005152/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
5153/// any semantic actions necessary after any initializer has been attached.
5154void
5155Sema::FinalizeDeclaration(Decl *ThisDecl) {
5156 // Note that we are no longer parsing the initializer for this declaration.
5157 ParsingInitForAutoVars.erase(ThisDecl);
5158}
5159
John McCallba7bf592010-08-24 05:47:05 +00005160Sema::DeclGroupPtrTy
5161Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
5162 Decl **Group, unsigned NumDecls) {
Chris Lattner5bbb3c82009-03-29 16:50:03 +00005163 llvm::SmallVector<Decl*, 8> Decls;
Eli Friedman55b9ecb2009-05-29 01:49:24 +00005164
5165 if (DS.isTypeSpecOwned())
John McCallba7bf592010-08-24 05:47:05 +00005166 Decls.push_back(DS.getRepAsDecl());
Eli Friedman55b9ecb2009-05-29 01:49:24 +00005167
Richard Smith2abf6762011-02-23 00:37:57 +00005168 for (unsigned i = 0; i != NumDecls; ++i)
5169 if (Decl *D = Group[i])
5170 Decls.push_back(D);
5171
5172 return BuildDeclaratorGroup(Decls.data(), Decls.size(),
5173 DS.getTypeSpecType() == DeclSpec::TST_auto);
5174}
5175
5176/// BuildDeclaratorGroup - convert a list of declarations into a declaration
5177/// group, performing any necessary semantic checking.
5178Sema::DeclGroupPtrTy
5179Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
5180 bool TypeMayContainAuto) {
Richard Smith30482bc2011-02-20 03:19:35 +00005181 // C++0x [dcl.spec.auto]p7:
5182 // If the type deduced for the template parameter U is not the same in each
5183 // deduction, the program is ill-formed.
5184 // FIXME: When initializer-list support is added, a distinction is needed
5185 // between the deduced type U and the deduced type which 'auto' stands for.
5186 // auto a = 0, b = { 1, 2, 3 };
5187 // is legal because the deduced type U is 'int' in both cases.
Richard Smith2abf6762011-02-23 00:37:57 +00005188 if (TypeMayContainAuto && NumDecls > 1) {
Richard Smith30482bc2011-02-20 03:19:35 +00005189 QualType Deduced;
5190 CanQualType DeducedCanon;
5191 VarDecl *DeducedDecl = 0;
5192 for (unsigned i = 0; i != NumDecls; ++i) {
5193 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
5194 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith2abf6762011-02-23 00:37:57 +00005195 // Don't reissue diagnostics when instantiating a template.
5196 if (AT && D->isInvalidDecl())
5197 break;
Richard Smith30482bc2011-02-20 03:19:35 +00005198 if (AT && AT->isDeduced()) {
5199 QualType U = AT->getDeducedType();
5200 CanQualType UCanon = Context.getCanonicalType(U);
5201 if (Deduced.isNull()) {
5202 Deduced = U;
5203 DeducedCanon = UCanon;
5204 DeducedDecl = D;
5205 } else if (DeducedCanon != UCanon) {
Richard Smith2abf6762011-02-23 00:37:57 +00005206 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
5207 diag::err_auto_different_deductions)
Richard Smith30482bc2011-02-20 03:19:35 +00005208 << Deduced << DeducedDecl->getDeclName()
5209 << U << D->getDeclName()
5210 << DeducedDecl->getInit()->getSourceRange()
5211 << D->getInit()->getSourceRange();
Richard Smith2abf6762011-02-23 00:37:57 +00005212 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00005213 break;
5214 }
5215 }
5216 }
5217 }
5218 }
5219
Richard Smith2abf6762011-02-23 00:37:57 +00005220 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls));
Chris Lattner776fac82007-06-09 00:53:06 +00005221}
Steve Naroff7e6f7c22007-08-28 03:03:08 +00005222
Chris Lattner5bbb3c82009-03-29 16:50:03 +00005223
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005224/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
5225/// to introduce parameters into function prototype scope.
John McCall48871652010-08-21 09:40:31 +00005226Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattnercf31de32008-06-26 06:49:43 +00005227 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorad590502008-12-15 23:53:10 +00005228
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005229 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
John McCall8e7d6562010-08-26 03:08:43 +00005230 VarDecl::StorageClass StorageClass = SC_None;
5231 VarDecl::StorageClass StorageClassAsWritten = SC_None;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00005232 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCall8e7d6562010-08-26 03:08:43 +00005233 StorageClass = SC_Register;
5234 StorageClassAsWritten = SC_Register;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00005235 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005236 Diag(DS.getStorageClassSpecLoc(),
5237 diag::err_invalid_storage_class_in_func_decl);
Chris Lattnercf31de32008-06-26 06:49:43 +00005238 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005239 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005240
5241 if (D.getDeclSpec().isThreadSpecified())
5242 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
5243
Eli Friedman574c7452009-04-07 19:37:57 +00005244 DiagnoseFunctionSpecifiers(D);
5245
Douglas Gregord6ab8742009-05-28 23:31:59 +00005246 TagDecl *OwnedDecl = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00005247 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedDecl);
5248 QualType parmDeclType = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005249
Douglas Gregor27b4c162010-12-23 22:44:42 +00005250 if (getLangOptions().CPlusPlus) {
5251 // Check that there are no default arguments inside the type of this
5252 // parameter.
5253 CheckExtraCXXDefaultArguments(D);
5254
5255 if (OwnedDecl && OwnedDecl->isDefinition()) {
5256 // C++ [dcl.fct]p6:
5257 // Types shall not be defined in return or parameter types.
5258 Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
5259 << Context.getTypeDeclType(OwnedDecl);
5260 }
5261
5262 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
5263 if (D.getCXXScopeSpec().isSet()) {
5264 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
5265 << D.getCXXScopeSpec().getRange();
5266 D.getCXXScopeSpec().clear();
5267 }
Douglas Gregord6ab8742009-05-28 23:31:59 +00005268 }
5269
Alexis Hunta56cbcc2010-11-03 01:07:06 +00005270 // Ensure we have a valid name
5271 IdentifierInfo *II = 0;
5272 if (D.hasName()) {
5273 II = D.getIdentifier();
5274 if (!II) {
5275 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
5276 << GetNameForDeclarator(D).getName().getAsString();
5277 D.setInvalidType(true);
5278 }
5279 }
5280
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00005281 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnerd9773512009-01-21 02:38:50 +00005282 if (II) {
John McCall84f02672010-03-18 06:42:38 +00005283 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
5284 ForRedeclaration);
5285 LookupName(R, S);
5286 if (R.isSingleResult()) {
5287 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnerd9773512009-01-21 02:38:50 +00005288 if (PrevDecl->isTemplateParameter()) {
5289 // Maybe we will complain about the shadowed template parameter.
5290 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5291 // Just pretend that we didn't see the previous declaration.
5292 PrevDecl = 0;
John McCall48871652010-08-21 09:40:31 +00005293 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerd9773512009-01-21 02:38:50 +00005294 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00005295 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005296
Chris Lattnerd9773512009-01-21 02:38:50 +00005297 // Recover by removing the name
5298 II = 0;
5299 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00005300 D.setInvalidType(true);
Chris Lattnerd9773512009-01-21 02:38:50 +00005301 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005302 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00005303 }
Steve Naroff773df5c2007-08-07 22:44:21 +00005304
John McCallf7b2fb52010-01-22 00:28:27 +00005305 // Temporarily put parameter variables in the translation unit, not
5306 // the enclosing context. This prevents them from accidentally
5307 // looking like class members in C++.
Douglas Gregor940bca72010-04-12 07:48:19 +00005308 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00005309 D.getSourceRange().getBegin(),
5310 D.getIdentifierLoc(), II,
5311 parmDeclType, TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00005312 StorageClass, StorageClassAsWritten);
Mike Stump11289f42009-09-09 15:08:12 +00005313
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005314 if (D.isInvalidType())
Douglas Gregor940bca72010-04-12 07:48:19 +00005315 New->setInvalidDecl();
5316
Douglas Gregor91f84212008-12-11 16:49:14 +00005317 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00005318 S->AddDecl(New);
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00005319 if (II)
Douglas Gregor91f84212008-12-11 16:49:14 +00005320 IdResolver.AddDecl(New);
Nate Begemand8c41562008-02-17 21:20:31 +00005321
Douglas Gregor758a8692009-06-17 21:51:59 +00005322 ProcessDeclAttributes(S, New, D);
Mike Stumpe9efa802009-04-30 00:19:40 +00005323
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005324 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00005325 Diag(New->getLocation(), diag::err_block_on_nonlocal);
5326 }
John McCall48871652010-08-21 09:40:31 +00005327 return New;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00005328}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +00005329
John McCalla3ccba02010-06-04 11:21:44 +00005330/// \brief Synthesizes a variable for a parameter arising from a
5331/// typedef.
5332ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
5333 SourceLocation Loc,
5334 QualType T) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00005335 /* FIXME: setting StartLoc == Loc.
5336 Would it be worth to modify callers so as to provide proper source
5337 location for the unnamed parameters, embedding the parameter's type? */
5338 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCalla3ccba02010-06-04 11:21:44 +00005339 T, Context.getTrivialTypeSourceInfo(T, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00005340 SC_None, SC_None, 0);
John McCalla3ccba02010-06-04 11:21:44 +00005341 Param->setImplicit();
5342 return Param;
5343}
5344
John McCallc5990642010-08-24 09:05:15 +00005345void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
5346 ParmVarDecl * const *ParamEnd) {
John McCallc5990642010-08-24 09:05:15 +00005347 // Don't diagnose unused-parameter errors in template instantiations; we
5348 // will already have done so in the template itself.
5349 if (!ActiveTemplateInstantiations.empty())
5350 return;
5351
5352 for (; Param != ParamEnd; ++Param) {
5353 if (!(*Param)->isUsed() && (*Param)->getDeclName() &&
5354 !(*Param)->hasAttr<UnusedAttr>()) {
5355 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
5356 << (*Param)->getDeclName();
5357 }
5358 }
5359}
5360
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00005361void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
5362 ParmVarDecl * const *ParamEnd,
5363 QualType ReturnTy,
5364 NamedDecl *D) {
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00005365 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00005366 return;
5367
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00005368 // Warn if the return value is pass-by-value and larger than the specified
5369 // threshold.
Argyrios Kyrtzidis745f9992010-11-18 18:51:03 +00005370 if (ReturnTy->isPODType()) {
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00005371 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00005372 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00005373 Diag(D->getLocation(), diag::warn_return_value_size)
5374 << D->getDeclName() << Size;
5375 }
5376
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00005377 // Warn if any parameter is pass-by-value and larger than the specified
5378 // threshold.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00005379 for (; Param != ParamEnd; ++Param) {
5380 QualType T = (*Param)->getType();
5381 if (!T->isPODType())
5382 continue;
5383 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00005384 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00005385 Diag((*Param)->getLocation(), diag::warn_parameter_size)
5386 << (*Param)->getDeclName() << Size;
5387 }
5388}
5389
Abramo Bagnaradff19302011-03-08 08:55:46 +00005390ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
5391 SourceLocation NameLoc, IdentifierInfo *Name,
5392 QualType T, TypeSourceInfo *TSInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00005393 VarDecl::StorageClass StorageClass,
5394 VarDecl::StorageClass StorageClassAsWritten) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00005395 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
5396 adjustParameterType(T), TSInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00005397 StorageClass, StorageClassAsWritten,
5398 0);
Douglas Gregor940bca72010-04-12 07:48:19 +00005399
5400 // Parameters can not be abstract class types.
5401 // For record types, this is done by the AbstractClassUsageDiagnoser once
5402 // the class has been completely parsed.
5403 if (!CurContext->isRecord() &&
5404 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
5405 AbstractParamType))
5406 New->setInvalidDecl();
5407
5408 // Parameter declarators cannot be interface types. All ObjC objects are
5409 // passed by reference.
John McCall8b07ec22010-05-15 11:32:37 +00005410 if (T->isObjCObjectType()) {
Douglas Gregor940bca72010-04-12 07:48:19 +00005411 Diag(NameLoc,
5412 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
5413 New->setInvalidDecl();
5414 }
5415
5416 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
5417 // duration shall not be qualified by an address-space qualifier."
5418 // Since all parameters have automatic store duration, they can not have
5419 // an address space.
5420 if (T.getAddressSpace() != 0) {
5421 Diag(NameLoc, diag::err_arg_with_address_space);
5422 New->setInvalidDecl();
5423 }
5424
5425 return New;
5426}
5427
Douglas Gregor170512f2009-04-01 23:51:29 +00005428void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
5429 SourceLocation LocAfterDecls) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005430 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005431
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00005432 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
5433 // for a K&R function.
5434 if (!FTI.hasPrototype) {
Douglas Gregor862ffb12009-04-02 03:14:12 +00005435 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
5436 --i;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005437 if (FTI.ArgInfo[i].Param == 0) {
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00005438 llvm::SmallString<256> Code;
5439 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar07d07852009-10-18 21:17:35 +00005440 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00005441 << ";\n";
Chris Lattner4bd8dd82008-11-19 08:23:25 +00005442 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregor170512f2009-04-01 23:51:29 +00005443 << FTI.ArgInfo[i].Ident
Douglas Gregora771f462010-03-31 17:46:05 +00005444 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregor170512f2009-04-01 23:51:29 +00005445
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00005446 // Implicitly declare the argument as type 'int' for lack of a better
5447 // type.
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005448 DeclSpec DS;
5449 const char* PrevSpec; // unused
John McCall49bfce42009-08-03 20:12:06 +00005450 unsigned DiagID; // unused
Mike Stump11289f42009-09-09 15:08:12 +00005451 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCall49bfce42009-08-03 20:12:06 +00005452 PrevSpec, DiagID);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005453 Declarator ParamD(DS, Declarator::KNRTypeListContext);
5454 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregor9aa89042009-01-23 16:23:13 +00005455 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00005456 }
5457 }
Mike Stump11289f42009-09-09 15:08:12 +00005458 }
Douglas Gregor9aa89042009-01-23 16:23:13 +00005459}
5460
John McCall48871652010-08-21 09:40:31 +00005461Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
5462 Declarator &D) {
Douglas Gregor9aa89042009-01-23 16:23:13 +00005463 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005464 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregorad590502008-12-15 23:53:10 +00005465 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +00005466
John McCall48871652010-08-21 09:40:31 +00005467 Decl *DP = HandleDeclarator(ParentScope, D,
5468 MultiTemplateParamsArg(*this),
5469 /*IsFunctionDefinition=*/true);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00005470 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005471}
5472
Anders Carlsson31c7e882009-12-09 03:30:09 +00005473static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
5474 // Don't warn about invalid declarations.
5475 if (FD->isInvalidDecl())
5476 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00005477
Anders Carlsson31c7e882009-12-09 03:30:09 +00005478 // Or declarations that aren't global.
5479 if (!FD->isGlobal())
5480 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00005481
Anders Carlsson31c7e882009-12-09 03:30:09 +00005482 // Don't warn about C++ member functions.
5483 if (isa<CXXMethodDecl>(FD))
5484 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00005485
Anders Carlsson31c7e882009-12-09 03:30:09 +00005486 // Don't warn about 'main'.
5487 if (FD->isMain())
5488 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00005489
Anders Carlsson31c7e882009-12-09 03:30:09 +00005490 // Don't warn about inline functions.
5491 if (FD->isInlineSpecified())
5492 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00005493
5494 // Don't warn about function templates.
5495 if (FD->getDescribedFunctionTemplate())
5496 return false;
5497
5498 // Don't warn about function template specializations.
5499 if (FD->isFunctionTemplateSpecialization())
5500 return false;
5501
Anders Carlsson31c7e882009-12-09 03:30:09 +00005502 bool MissingPrototype = true;
5503 for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
5504 Prev; Prev = Prev->getPreviousDeclaration()) {
5505 // Ignore any declarations that occur in function or method
5506 // scope, because they aren't visible from the header.
5507 if (Prev->getDeclContext()->isFunctionOrMethod())
5508 continue;
5509
5510 MissingPrototype = !Prev->getType()->isFunctionProtoType();
5511 break;
5512 }
5513
5514 return MissingPrototype;
5515}
5516
John McCall48871652010-08-21 09:40:31 +00005517Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson561f7932009-10-29 15:46:07 +00005518 // Clear the last template instantiation error context.
5519 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
5520
Douglas Gregor17a7c122009-06-24 00:54:41 +00005521 if (!D)
5522 return D;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00005523 FunctionDecl *FD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005524
John McCall48871652010-08-21 09:40:31 +00005525 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregorc45a40a2009-08-22 00:34:47 +00005526 FD = FunTmpl->getTemplatedDecl();
5527 else
John McCall48871652010-08-21 09:40:31 +00005528 FD = cast<FunctionDecl>(D);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00005529
Douglas Gregor9a28e842010-03-01 23:15:13 +00005530 // Enter a new function scope
5531 PushFunctionScope();
Mike Stump11289f42009-09-09 15:08:12 +00005532
Douglas Gregorcad304ba2008-10-29 15:10:40 +00005533 // See if this is a redefinition.
Charles Davisfea48452010-02-18 02:00:42 +00005534 // But don't complain if we're in GNU89 mode and the previous definition
5535 // was an extern inline function.
Douglas Gregorcad304ba2008-10-29 15:10:40 +00005536 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00005537 if (FD->hasBody(Definition) &&
Charles Davisfea48452010-02-18 02:00:42 +00005538 !canRedefineFunction(Definition, getLangOptions())) {
Douglas Gregora7d6e3d2010-09-07 15:51:01 +00005539 if (getLangOptions().GNUMode && Definition->isInlineSpecified() &&
5540 Definition->getStorageClass() == SC_Extern)
5541 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
5542 << FD->getDeclName() << getLangOptions().CPlusPlus;
5543 else
5544 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00005545 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00005546 }
5547
Douglas Gregor75a45ba2009-02-16 17:45:42 +00005548 // Builtin functions cannot be defined.
Douglas Gregor15fc9562009-09-12 00:22:50 +00005549 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor7a0febe2009-02-17 16:03:01 +00005550 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00005551 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor7a0febe2009-02-17 16:03:01 +00005552 FD->setInvalidDecl();
5553 }
Douglas Gregor75a45ba2009-02-16 17:45:42 +00005554 }
5555
Eli Friedman9ad72442009-03-04 07:30:59 +00005556 // The return type of a function definition must be complete
Douglas Gregorac1fb652009-03-24 19:52:54 +00005557 // (C99 6.9.1p3, C++ [dcl.fct]p6).
5558 QualType ResultType = FD->getResultType();
5559 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner0f94c5a2009-04-29 05:12:23 +00005560 !FD->isInvalidDecl() &&
Douglas Gregorac1fb652009-03-24 19:52:54 +00005561 RequireCompleteType(FD->getLocation(), ResultType,
5562 diag::err_func_def_incomplete_result))
Eli Friedman9ad72442009-03-04 07:30:59 +00005563 FD->setInvalidDecl();
Eli Friedman9ad72442009-03-04 07:30:59 +00005564
Douglas Gregorf1b876d2009-03-31 16:35:03 +00005565 // GNU warning -Wmissing-prototypes:
5566 // Warn if a global function is defined without a previous
5567 // prototype declaration. This warning is issued even if the
5568 // definition itself provides a prototype. The aim is to detect
5569 // global functions that fail to be declared in header files.
Anders Carlsson31c7e882009-12-09 03:30:09 +00005570 if (ShouldWarnAboutMissingPrototype(FD))
5571 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Douglas Gregorf1b876d2009-03-31 16:35:03 +00005572
Douglas Gregor67da0d92009-05-15 17:59:04 +00005573 if (FnBodyScope)
5574 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00005575
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005576 // Check the validity of our function parameters
Douglas Gregorb524d902010-11-01 18:37:59 +00005577 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
5578 /*CheckParameterNames=*/true);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005579
5580 // Introduce our parameters into the function scope
5581 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
5582 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc72e6452009-01-09 18:51:29 +00005583 Param->setOwningFunction(FD);
5584
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005585 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00005586 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005587 CheckShadow(FnBodyScope, Param);
John McCalldf8b37c2010-03-22 09:20:08 +00005588
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00005589 PushOnScopeChains(Param, FnBodyScope);
John McCalldf8b37c2010-03-22 09:20:08 +00005590 }
Chris Lattnerf61c8a82007-01-21 19:04:43 +00005591 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005592
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00005593 // Checking attributes of current function definition
5594 // dllimport attribute.
Alexis Huntdcfba7b2010-08-18 23:23:40 +00005595 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
5596 if (DA && (!FD->getAttr<DLLExportAttr>())) {
5597 // dllimport attribute cannot be directly applied to definition.
5598 if (!DA->isInherited()) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00005599 Diag(FD->getLocation(),
5600 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
5601 << "dllimport";
5602 FD->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +00005603 return FD;
Ted Kremeneka3cfc4d2010-02-21 05:12:53 +00005604 }
5605
5606 // Visual C++ appears to not think this is an issue, so only issue
5607 // a warning when Microsoft extensions are disabled.
5608 if (!LangOpts.Microsoft) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00005609 // If a symbol previously declared dllimport is later defined, the
5610 // attribute is ignored in subsequent references, and a warning is
5611 // emitted.
5612 Diag(FD->getLocation(),
5613 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Daniel Dunbar56df9772010-08-17 22:39:59 +00005614 << FD->getName() << "dllimport";
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00005615 }
5616 }
John McCall48871652010-08-21 09:40:31 +00005617 return FD;
Chris Lattnere168f762006-11-10 05:29:30 +00005618}
5619
Douglas Gregor6fd1b182010-05-15 06:01:05 +00005620/// \brief Given the set of return statements within a function body,
5621/// compute the variables that are subject to the named return value
5622/// optimization.
5623///
5624/// Each of the variables that is subject to the named return value
5625/// optimization will be marked as NRVO variables in the AST, and any
5626/// return statement that has a marked NRVO variable as its NRVO candidate can
5627/// use the named return value optimization.
5628///
5629/// This function applies a very simplistic algorithm for NRVO: if every return
5630/// statement in the function has the same NRVO candidate, that candidate is
5631/// the NRVO variable.
5632///
5633/// FIXME: Employ a smarter algorithm that accounts for multiple return
5634/// statements and the lifetimes of the NRVO candidates. We should be able to
5635/// find a maximal set of NRVO variables.
John McCallaab3e412010-08-25 08:40:02 +00005636static void ComputeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
5637 ReturnStmt **Returns = Scope->Returns.data();
5638
Douglas Gregor6fd1b182010-05-15 06:01:05 +00005639 const VarDecl *NRVOCandidate = 0;
John McCallaab3e412010-08-25 08:40:02 +00005640 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00005641 if (!Returns[I]->getNRVOCandidate())
5642 return;
5643
5644 if (!NRVOCandidate)
5645 NRVOCandidate = Returns[I]->getNRVOCandidate();
5646 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
5647 return;
5648 }
5649
5650 if (NRVOCandidate)
5651 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
5652}
5653
John McCallfaf5fb42010-08-26 23:41:50 +00005654Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Douglas Gregor67da0d92009-05-15 17:59:04 +00005655 return ActOnFinishFunctionBody(D, move(BodyArg), false);
5656}
5657
John McCallb268a282010-08-23 23:25:46 +00005658Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
5659 bool IsInstantiation) {
Douglas Gregorc45a40a2009-08-22 00:34:47 +00005660 FunctionDecl *FD = 0;
5661 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
5662 if (FunTmpl)
5663 FD = FunTmpl->getTemplatedDecl();
5664 else
5665 FD = dyn_cast_or_null<FunctionDecl>(dcl);
5666
Ted Kremenek0b405322010-03-23 00:13:23 +00005667 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek1767a272011-02-23 01:51:48 +00005668 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenek918fe842010-03-20 21:06:02 +00005669
Douglas Gregorc45a40a2009-08-22 00:34:47 +00005670 if (FD) {
Chris Lattner960cc522009-04-18 09:36:27 +00005671 FD->setBody(Body);
Ted Kremenek918fe842010-03-20 21:06:02 +00005672 if (FD->isMain()) {
Mike Stump8e79f992009-07-24 02:49:01 +00005673 // C and C++ allow for main to automagically return 0.
John McCallcaa19452009-07-28 01:00:58 +00005674 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
5675 FD->setHasImplicitReturnZero(true);
Ted Kremenek0b405322010-03-23 00:13:23 +00005676 WP.disableCheckFallThrough();
Ted Kremenek918fe842010-03-20 21:06:02 +00005677 }
Mike Stump11289f42009-09-09 15:08:12 +00005678
Douglas Gregor88d292c2010-05-13 16:44:06 +00005679 if (!FD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005680 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00005681 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
5682 FD->getResultType(), FD);
Douglas Gregor88d292c2010-05-13 16:44:06 +00005683
5684 // If this is a constructor, we need a vtable.
5685 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
5686 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor6fd1b182010-05-15 06:01:05 +00005687
John McCallaab3e412010-08-25 08:40:02 +00005688 ComputeNRVO(Body, getCurFunction());
Douglas Gregor88d292c2010-05-13 16:44:06 +00005689 }
5690
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00005691 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff542cd5d2008-07-25 17:57:26 +00005692 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattner1598a3a2009-02-16 19:27:54 +00005693 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattner960cc522009-04-18 09:36:27 +00005694 MD->setBody(Body);
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00005695 if (Body)
5696 MD->setEndLoc(Body->getLocEnd());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00005697 if (!MD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005698 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00005699 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
5700 MD->getResultType(), MD);
5701 }
Ted Kremenek5a201952009-02-07 01:47:29 +00005702 } else {
John McCall48871652010-08-21 09:40:31 +00005703 return 0;
Ted Kremenek5a201952009-02-07 01:47:29 +00005704 }
Douglas Gregor67da0d92009-05-15 17:59:04 +00005705
Chris Lattnere2473062007-05-28 06:28:18 +00005706 // Verify and clean out per-function state.
Douglas Gregor9a28e842010-03-01 23:15:13 +00005707 if (Body) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00005708 // C++ constructors that have function-try-blocks can't have return
5709 // statements in the handlers of that block. (C++ [except.handle]p14)
5710 // Verify this.
5711 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
5712 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
5713
Ted Kremenek918fe842010-03-20 21:06:02 +00005714 // Verify that that gotos and switch cases don't jump into scopes illegally.
5715 // Verify that that gotos and switch cases don't jump into scopes illegally.
John McCallaab3e412010-08-25 08:40:02 +00005716 if (getCurFunction()->NeedsScopeChecking() &&
John McCall58efb8e2010-05-20 07:13:26 +00005717 !dcl->isInvalidDecl() &&
John McCalldeb5e722010-05-20 07:05:55 +00005718 !hasAnyErrorsInThisFunction())
Douglas Gregor9a28e842010-03-01 23:15:13 +00005719 DiagnoseInvalidJumps(Body);
Mike Stump11289f42009-09-09 15:08:12 +00005720
John McCalldeb646e2010-08-04 01:04:25 +00005721 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
5722 if (!Destructor->getParent()->isDependentType())
5723 CheckDestructor(Destructor);
5724
John McCalla6309952010-03-16 21:39:52 +00005725 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
5726 Destructor->getParent());
John McCalldeb646e2010-08-04 01:04:25 +00005727 }
Douglas Gregor9a28e842010-03-01 23:15:13 +00005728
5729 // If any errors have occurred, clear out any temporaries that may have
5730 // been leftover. This ensures that these temporaries won't be picked up for
5731 // deletion in some later function.
Douglas Gregor550b98b2011-03-04 23:08:02 +00005732 if (PP.getDiagnostics().hasErrorOccurred() ||
5733 PP.getDiagnostics().getSuppressAllDiagnostics())
Douglas Gregor9a28e842010-03-01 23:15:13 +00005734 ExprTemporaries.clear();
Ted Kremenek918fe842010-03-20 21:06:02 +00005735 else if (!isa<FunctionTemplateDecl>(dcl)) {
5736 // Since the body is valid, issue any analysis-based warnings that are
5737 // enabled.
Ted Kremenek1767a272011-02-23 01:51:48 +00005738 ActivePolicy = &WP;
Ted Kremenek918fe842010-03-20 21:06:02 +00005739 }
5740
Douglas Gregor9a28e842010-03-01 23:15:13 +00005741 assert(ExprTemporaries.empty() && "Leftover temporaries in function");
5742 }
5743
John McCalle99d5f32010-03-25 22:08:03 +00005744 if (!IsInstantiation)
5745 PopDeclContext();
5746
Ted Kremenek1767a272011-02-23 01:51:48 +00005747 PopFunctionOrBlockScope(ActivePolicy, dcl);
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00005748
Douglas Gregora7e3ea32009-11-15 07:07:58 +00005749 // If any errors have occurred, clear out any temporaries that may have
5750 // been leftover. This ensures that these temporaries won't be picked up for
5751 // deletion in some later function.
Chris Lattner30d0cfd2010-03-01 20:59:53 +00005752 if (getDiagnostics().hasErrorOccurred())
Douglas Gregora7e3ea32009-11-15 07:07:58 +00005753 ExprTemporaries.clear();
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00005754
John McCall48871652010-08-21 09:40:31 +00005755 return dcl;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +00005756}
5757
Chris Lattnerac18be92006-11-20 06:49:47 +00005758/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
5759/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump11289f42009-09-09 15:08:12 +00005760NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005761 IdentifierInfo &II, Scope *S) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00005762 // Before we produce a declaration for an implicitly defined
5763 // function, see whether there was a locally-scoped declaration of
5764 // this name as a function or variable. If so, use that
5765 // (non-visible) declaration, and complain about it.
5766 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
5767 = LocallyScopedExternalDecls.find(&II);
5768 if (Pos != LocallyScopedExternalDecls.end()) {
5769 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
5770 Diag(Pos->second->getLocation(), diag::note_previous_declaration);
5771 return Pos->second;
5772 }
5773
Chris Lattner00e26072008-05-05 21:18:06 +00005774 // Extension in C99. Legal in C90, but warn about it.
Daniel Dunbar07d07852009-10-18 21:17:35 +00005775 if (II.getName().startswith("__builtin_"))
Douglas Gregor56fbc372009-09-28 21:14:19 +00005776 Diag(Loc, diag::warn_builtin_unknown) << &II;
5777 else if (getLangOptions().C99)
Chris Lattner4bd8dd82008-11-19 08:23:25 +00005778 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner00e26072008-05-05 21:18:06 +00005779 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +00005780 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Mike Stump11289f42009-09-09 15:08:12 +00005781
Chris Lattnerac18be92006-11-20 06:49:47 +00005782 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +00005783 const char *Dummy;
Chris Lattnerac18be92006-11-20 06:49:47 +00005784 DeclSpec DS;
John McCall49bfce42009-08-03 20:12:06 +00005785 unsigned DiagID;
5786 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00005787 (void)Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +00005788 assert(!Error && "Error setting up implicit decl!");
Chris Lattnerac18be92006-11-20 06:49:47 +00005789 Declarator D(DS, Declarator::BlockContext);
John McCall53fa7142010-12-24 02:08:15 +00005790 D.AddTypeInfo(DeclaratorChunk::getFunction(ParsedAttributes(),
5791 false, false, SourceLocation(), 0,
Douglas Gregor54992352011-01-26 03:43:54 +00005792 0, 0, true, SourceLocation(),
Sebastian Redl802a4532011-03-05 22:42:13 +00005793 EST_None, SourceLocation(),
5794 0, 0, 0, 0, Loc, Loc, D),
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005795 SourceLocation());
Chris Lattnerac18be92006-11-20 06:49:47 +00005796 D.SetIdentifier(&II, Loc);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005797
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00005798 // Insert this function into translation-unit scope.
5799
5800 DeclContext *PrevDC = CurContext;
5801 CurContext = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00005802
John McCall48871652010-08-21 09:40:31 +00005803 FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroff3913ea42008-04-04 14:32:09 +00005804 FD->setImplicit();
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00005805
5806 CurContext = PrevDC;
5807
Douglas Gregore711f702009-02-14 18:57:46 +00005808 AddKnownFunctionAttributes(FD);
5809
Steve Naroff3913ea42008-04-04 14:32:09 +00005810 return FD;
Chris Lattnerac18be92006-11-20 06:49:47 +00005811}
5812
Douglas Gregore711f702009-02-14 18:57:46 +00005813/// \brief Adds any function attributes that we know a priori based on
5814/// the declaration of this function.
5815///
5816/// These attributes can apply both to implicitly-declared builtins
5817/// (like __builtin___printf_chk) or to library-declared functions
5818/// like NSLog or printf.
5819void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
5820 if (FD->isInvalidDecl())
5821 return;
5822
5823 // If this is a built-in function, map its builtin attributes to
5824 // actual attributes.
Douglas Gregor15fc9562009-09-12 00:22:50 +00005825 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregore711f702009-02-14 18:57:46 +00005826 // Handle printf-formatting attributes.
5827 unsigned FormatIdx;
5828 bool HasVAListArg;
5829 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005830 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00005831 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
5832 "printf", FormatIdx+1,
Ted Kremenek7f4945a2010-02-11 05:28:37 +00005833 HasVAListArg ? 0 : FormatIdx+2));
Douglas Gregore711f702009-02-14 18:57:46 +00005834 }
Ted Kremenek5932c352010-07-16 02:11:15 +00005835 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
5836 HasVAListArg)) {
5837 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00005838 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
5839 "scanf", FormatIdx+1,
Ted Kremenek5932c352010-07-16 02:11:15 +00005840 HasVAListArg ? 0 : FormatIdx+2));
5841 }
Daniel Dunbar8eb018a2009-02-16 22:43:43 +00005842
5843 // Mark const if we don't care about errno and that is the only
5844 // thing preventing the function from being const. This allows
5845 // IRgen to use LLVM intrinsics for such functions.
5846 if (!getLangOptions().MathErrno &&
5847 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005848 if (!FD->getAttr<ConstAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00005849 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Daniel Dunbar8eb018a2009-02-16 22:43:43 +00005850 }
Mike Stumpca6c8752009-07-27 19:14:18 +00005851
Chris Lattner8977c432009-12-30 22:06:22 +00005852 if (Context.BuiltinInfo.isNoThrow(BuiltinID))
Alexis Huntdcfba7b2010-08-18 23:23:40 +00005853 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
Chris Lattner8977c432009-12-30 22:06:22 +00005854 if (Context.BuiltinInfo.isConst(BuiltinID))
Alexis Huntdcfba7b2010-08-18 23:23:40 +00005855 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Douglas Gregore711f702009-02-14 18:57:46 +00005856 }
5857
5858 IdentifierInfo *Name = FD->getIdentifier();
5859 if (!Name)
5860 return;
Mike Stump11289f42009-09-09 15:08:12 +00005861 if ((!getLangOptions().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +00005862 FD->getDeclContext()->isTranslationUnit()) ||
5863 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +00005864 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregore711f702009-02-14 18:57:46 +00005865 LinkageSpecDecl::lang_c)) {
5866 // Okay: this could be a libc/libm/Objective-C function we know
5867 // about.
5868 } else
5869 return;
5870
Douglas Gregorfedd4282009-04-22 20:56:09 +00005871 if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
Mike Stump82a9e442009-07-28 00:07:08 +00005872 // FIXME: NSLog and NSLogv should be target specific
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005873 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
Douglas Gregore711f702009-02-14 18:57:46 +00005874 // FIXME: We known better than our headers.
Ted Kremenek7f4945a2010-02-11 05:28:37 +00005875 const_cast<FormatAttr *>(Format)->setType(Context, "printf");
Mike Stump11289f42009-09-09 15:08:12 +00005876 } else
Alexis Huntdcfba7b2010-08-18 23:23:40 +00005877 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
5878 "printf", 1,
Eli Friedmanf4799842009-06-10 04:01:38 +00005879 Name->isStr("NSLogv") ? 0 : 2));
Douglas Gregorfedd4282009-04-22 20:56:09 +00005880 } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump82a9e442009-07-28 00:07:08 +00005881 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump11289f42009-09-09 15:08:12 +00005882 // target-specific builtins, perhaps?
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005883 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00005884 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
5885 "printf", 2,
Eli Friedmanf4799842009-06-10 04:01:38 +00005886 Name->isStr("vasprintf") ? 0 : 3));
Mike Stumpa4de80b2009-07-28 02:25:19 +00005887 }
Douglas Gregore711f702009-02-14 18:57:46 +00005888}
Chris Lattner302b4be2006-11-19 02:31:38 +00005889
John McCall703a3f82009-10-24 08:00:42 +00005890TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCallbcd03502009-12-07 02:54:59 +00005891 TypeSourceInfo *TInfo) {
Chris Lattner776fac82007-06-09 00:53:06 +00005892 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +00005893 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump11289f42009-09-09 15:08:12 +00005894
John McCallbcd03502009-12-07 02:54:59 +00005895 if (!TInfo) {
John McCall703a3f82009-10-24 08:00:42 +00005896 assert(D.isInvalidType() && "no declarator info for valid type");
John McCallbcd03502009-12-07 02:54:59 +00005897 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCall703a3f82009-10-24 08:00:42 +00005898 }
5899
Chris Lattner18b19622007-01-22 07:39:13 +00005900 // Scope manipulation handled by caller.
Chris Lattnerc5ffed42008-04-04 06:12:32 +00005901 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00005902 D.getSourceRange().getBegin(),
Chris Lattnerc5ffed42008-04-04 06:12:32 +00005903 D.getIdentifierLoc(),
Mike Stump11289f42009-09-09 15:08:12 +00005904 D.getIdentifier(),
John McCallbcd03502009-12-07 02:54:59 +00005905 TInfo);
Mike Stump11289f42009-09-09 15:08:12 +00005906
John McCall04fcd0d2011-02-01 08:20:08 +00005907 // Bail out immediately if we have an invalid declaration.
5908 if (D.isInvalidType()) {
5909 NewTD->setInvalidDecl();
5910 return NewTD;
Anders Carlsson02751152009-03-10 17:07:44 +00005911 }
5912
John McCall04fcd0d2011-02-01 08:20:08 +00005913 // C++ [dcl.typedef]p8:
5914 // If the typedef declaration defines an unnamed class (or
5915 // enum), the first typedef-name declared by the declaration
5916 // to be that class type (or enum type) is used to denote the
5917 // class type (or enum type) for linkage purposes only.
5918 // We need to check whether the type was declared in the declaration.
5919 switch (D.getDeclSpec().getTypeSpecType()) {
5920 case TST_enum:
5921 case TST_struct:
5922 case TST_union:
5923 case TST_class: {
5924 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
5925
5926 // Do nothing if the tag is not anonymous or already has an
5927 // associated typedef (from an earlier typedef in this decl group).
5928 if (tagFromDeclSpec->getIdentifier()) break;
5929 if (tagFromDeclSpec->getTypedefForAnonDecl()) break;
5930
5931 // A well-formed anonymous tag must always be a TUK_Definition.
5932 assert(tagFromDeclSpec->isThisDeclarationADefinition());
5933
5934 // The type must match the tag exactly; no qualifiers allowed.
5935 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
5936 break;
5937
5938 // Otherwise, set this is the anon-decl typedef for the tag.
5939 tagFromDeclSpec->setTypedefForAnonDecl(NewTD);
5940 break;
5941 }
5942
5943 default:
5944 break;
5945 }
5946
Steve Narofff93b6722007-08-28 20:14:24 +00005947 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +00005948}
5949
Douglas Gregord9034f02009-05-14 16:41:31 +00005950
5951/// \brief Determine whether a tag with a given kind is acceptable
5952/// as a redeclaration of the given tag declaration.
5953///
5954/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005955bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Abramo Bagnara6150c882010-05-11 21:36:43 +00005956 TagTypeKind NewTag,
Douglas Gregord9034f02009-05-14 16:41:31 +00005957 SourceLocation NewTagLoc,
5958 const IdentifierInfo &Name) {
5959 // C++ [dcl.type.elab]p3:
5960 // The class-key or enum keyword present in the
5961 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara6150c882010-05-11 21:36:43 +00005962 // declaration to which the name in the elaborated-type-specifier
Douglas Gregord9034f02009-05-14 16:41:31 +00005963 // refers. This rule also applies to the form of
5964 // elaborated-type-specifier that declares a class-name or
5965 // friend class since it can be construed as referring to the
5966 // definition of the class. Thus, in any
5967 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara6150c882010-05-11 21:36:43 +00005968 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregord9034f02009-05-14 16:41:31 +00005969 // used to refer to a union (clause 9), and either the class or
5970 // struct class-key shall be used to refer to a class (clause 9)
5971 // declared using the class or struct class-key.
Abramo Bagnara6150c882010-05-11 21:36:43 +00005972 TagTypeKind OldTag = Previous->getTagKind();
Douglas Gregord9034f02009-05-14 16:41:31 +00005973 if (OldTag == NewTag)
5974 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005975
Abramo Bagnara6150c882010-05-11 21:36:43 +00005976 if ((OldTag == TTK_Struct || OldTag == TTK_Class) &&
5977 (NewTag == TTK_Struct || NewTag == TTK_Class)) {
Douglas Gregord9034f02009-05-14 16:41:31 +00005978 // Warn about the struct/class tag mismatch.
5979 bool isTemplate = false;
5980 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
5981 isTemplate = Record->getDescribedClassTemplate();
5982
5983 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Abramo Bagnara6150c882010-05-11 21:36:43 +00005984 << (NewTag == TTK_Class)
Douglas Gregord9034f02009-05-14 16:41:31 +00005985 << isTemplate << &Name
Douglas Gregora771f462010-03-31 17:46:05 +00005986 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Abramo Bagnara6150c882010-05-11 21:36:43 +00005987 OldTag == TTK_Class? "class" : "struct");
Douglas Gregord9034f02009-05-14 16:41:31 +00005988 Diag(Previous->getLocation(), diag::note_previous_use);
5989 return true;
5990 }
5991 return false;
5992}
5993
Steve Naroff30d242c2007-09-15 18:49:24 +00005994/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +00005995/// former case, Name will be non-null. In the later case, Name will be null.
John McCall9bb74a52009-07-31 02:45:11 +00005996/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Chris Lattner1300fb92007-01-23 23:42:53 +00005997/// reference/declaration/definition of a tag.
John McCall48871652010-08-21 09:40:31 +00005998Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor009f6992010-09-16 23:58:57 +00005999 SourceLocation KWLoc, CXXScopeSpec &SS,
6000 IdentifierInfo *Name, SourceLocation NameLoc,
6001 AttributeList *Attr, AccessSpecifier AS,
6002 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00006003 bool &OwnedDecl, bool &IsDependent,
6004 bool ScopedEnum, bool ScopedEnumUsesClassTag,
Douglas Gregor0bf31402010-10-08 23:50:27 +00006005 TypeResult UnderlyingType) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006006 // If this is not a definition, it must have a name.
John McCall9bb74a52009-07-31 02:45:11 +00006007 assert((Name != 0 || TUK == TUK_Definition) &&
Chris Lattner7b9ace62007-01-23 20:11:08 +00006008 "Nameless record must be a definition!");
John McCallace48cd2010-10-19 01:40:49 +00006009 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregorded2d7b2009-02-04 19:02:06 +00006010
Douglas Gregord6ab8742009-05-28 23:31:59 +00006011 OwnedDecl = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +00006012 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00006013
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006014 // FIXME: Check explicit specializations more carefully.
6015 bool isExplicitSpecialization = false;
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006016 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006017 bool Invalid = false;
John McCallace48cd2010-10-19 01:40:49 +00006018
6019 // We only need to do this matching if we have template parameters
6020 // or a scope specifier, which also conveniently avoids this work
6021 // for non-C++ cases.
6022 if (NumMatchedTemplateParamLists ||
6023 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Douglas Gregore93e46c2009-07-22 23:48:44 +00006024 if (TemplateParameterList *TemplateParams
6025 = MatchTemplateParametersToScopeSpecifier(KWLoc, SS,
John McCallc9739e32010-10-16 07:23:36 +00006026 TemplateParameterLists.get(),
6027 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00006028 TUK == TUK_Friend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006029 isExplicitSpecialization,
6030 Invalid)) {
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006031 // All but one template parameter lists have been matching.
6032 --NumMatchedTemplateParamLists;
6033
Douglas Gregor3dad8422009-09-26 06:47:28 +00006034 if (TemplateParams->size() > 0) {
Douglas Gregore93e46c2009-07-22 23:48:44 +00006035 // This is a declaration or definition of a class template (which may
6036 // be a member of another template).
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006037 if (Invalid)
John McCall48871652010-08-21 09:40:31 +00006038 return 0;
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006039
Douglas Gregore93e46c2009-07-22 23:48:44 +00006040 OwnedDecl = false;
John McCall9bb74a52009-07-31 02:45:11 +00006041 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +00006042 SS, Name, NameLoc, Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006043 TemplateParams,
Douglas Gregore93e46c2009-07-22 23:48:44 +00006044 AS);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00006045 TemplateParameterLists.release();
Douglas Gregore93e46c2009-07-22 23:48:44 +00006046 return Result.get();
6047 } else {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006048 // The "template<>" header is extraneous.
6049 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara6150c882010-05-11 21:36:43 +00006050 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006051 isExplicitSpecialization = true;
Douglas Gregore93e46c2009-07-22 23:48:44 +00006052 }
Mike Stump11289f42009-09-09 15:08:12 +00006053 }
6054 }
6055
Douglas Gregor0bf31402010-10-08 23:50:27 +00006056 // Figure out the underlying type if this a enum declaration. We need to do
6057 // this early, because it's needed to detect if this is an incompatible
6058 // redeclaration.
6059 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
6060
6061 if (Kind == TTK_Enum) {
6062 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
6063 // No underlying type explicitly specified, or we failed to parse the
6064 // type, default to int.
6065 EnumUnderlying = Context.IntTy.getTypePtr();
6066 else if (UnderlyingType.get()) {
6067 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
6068 // integral type; any cv-qualification is ignored.
6069 TypeSourceInfo *TI = 0;
6070 QualType T = GetTypeFromParser(UnderlyingType.get(), &TI);
6071 EnumUnderlying = TI;
6072
6073 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
6074
6075 if (!T->isDependentType() && !T->isIntegralType(Context)) {
6076 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
6077 << T;
6078 // Recover by falling back to int.
6079 EnumUnderlying = Context.IntTy.getTypePtr();
6080 }
Douglas Gregor2b988fd2010-12-16 00:24:44 +00006081
6082 if (DiagnoseUnexpandedParameterPack(UnderlyingLoc, TI,
6083 UPPC_FixedUnderlyingType))
6084 EnumUnderlying = Context.IntTy.getTypePtr();
6085
Francois Picheta3108062010-10-18 15:01:13 +00006086 } else if (getLangOptions().Microsoft)
6087 // Microsoft enums are always of int type.
6088 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006089 }
6090
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00006091 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00006092 DeclContext *DC = CurContext;
Douglas Gregor87f54062009-09-15 22:30:29 +00006093 bool isStdBadAlloc = false;
Douglas Gregordee1be82009-01-17 00:42:38 +00006094
Chandler Carrutha419dbb2010-03-01 21:17:36 +00006095 RedeclarationKind Redecl = ForRedeclaration;
6096 if (TUK == TUK_Friend || TUK == TUK_Reference)
6097 Redecl = NotForRedeclaration;
John McCall1f82f242009-11-18 22:49:29 +00006098
6099 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
John McCall6538c932009-10-10 05:48:19 +00006100
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00006101 if (Name && SS.isNotEmpty()) {
6102 // We have a nested-name tag ('struct foo::bar').
6103
6104 // Check for invalid 'foo::'.
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00006105 if (SS.isInvalid()) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00006106 Name = 0;
6107 goto CreateNewDecl;
6108 }
6109
John McCall7f41d982009-09-11 04:59:25 +00006110 // If this is a friend or a reference to a class in a dependent
6111 // context, don't try to make a decl for it.
6112 if (TUK == TUK_Friend || TUK == TUK_Reference) {
6113 DC = computeDeclContext(SS, false);
6114 if (!DC) {
6115 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +00006116 return 0;
John McCall7f41d982009-09-11 04:59:25 +00006117 }
John McCall0b66eb32010-05-01 00:40:08 +00006118 } else {
6119 DC = computeDeclContext(SS, true);
6120 if (!DC) {
6121 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
6122 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00006123 return 0;
John McCall0b66eb32010-05-01 00:40:08 +00006124 }
John McCall7f41d982009-09-11 04:59:25 +00006125 }
6126
John McCall0b66eb32010-05-01 00:40:08 +00006127 if (RequireCompleteDeclContext(SS, DC))
John McCall48871652010-08-21 09:40:31 +00006128 return 0;
Douglas Gregor2ec748c2009-05-14 00:28:11 +00006129
Douglas Gregor8761da52009-02-03 00:34:39 +00006130 SearchDC = DC;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00006131 // Look-up name inside 'foo::'.
John McCall1f82f242009-11-18 22:49:29 +00006132 LookupQualifiedName(Previous, DC);
John McCall6538c932009-10-10 05:48:19 +00006133
John McCall1f82f242009-11-18 22:49:29 +00006134 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006135 return 0;
John McCall6538c932009-10-10 05:48:19 +00006136
John McCall1f82f242009-11-18 22:49:29 +00006137 if (Previous.empty()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00006138 // Name lookup did not find anything. However, if the
6139 // nested-name-specifier refers to the current instantiation,
6140 // and that current instantiation has any dependent base
6141 // classes, we might find something at instantiation time: treat
6142 // this as a dependent elaborated-type-specifier.
John McCallace48cd2010-10-19 01:40:49 +00006143 // But this only makes any sense for reference-like lookups.
6144 if (Previous.wasNotFoundInCurrentInstantiation() &&
6145 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00006146 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +00006147 return 0;
Douglas Gregord2e6a452010-01-14 17:47:39 +00006148 }
6149
6150 // A tag 'foo::bar' must already exist.
Douglas Gregorf5af3582010-03-31 23:17:41 +00006151 Diag(NameLoc, diag::err_not_tag_in_scope)
6152 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00006153 Name = 0;
Douglas Gregorb8006faf2009-05-27 17:30:49 +00006154 Invalid = true;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00006155 goto CreateNewDecl;
6156 }
Chris Lattnerd9773512009-01-21 02:38:50 +00006157 } else if (Name) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00006158 // If this is a named struct, check to see if there was a previous forward
6159 // declaration or definition.
Douglas Gregor889ceb72009-02-03 19:21:40 +00006160 // FIXME: We're looking into outer scopes here, even when we
6161 // shouldn't be. Doing so can result in ambiguities that we
6162 // shouldn't be diagnosing.
John McCall1f82f242009-11-18 22:49:29 +00006163 LookupName(Previous, S);
6164
6165 // Note: there used to be some attempt at recovery here.
6166 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006167 return 0;
Douglas Gregor82ac25e2009-01-08 20:45:30 +00006168
John McCall9bb74a52009-07-31 02:45:11 +00006169 if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor82ac25e2009-01-08 20:45:30 +00006170 // FIXME: This makes sure that we ignore the contexts associated
6171 // with C structs, unions, and enums when looking for a matching
6172 // tag declaration or definition. See the similar lookup tweak
Douglas Gregored8f2882009-01-30 01:04:22 +00006173 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00006174 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
6175 SearchDC = SearchDC->getParent();
Douglas Gregor82ac25e2009-01-08 20:45:30 +00006176 }
Douglas Gregor009f6992010-09-16 23:58:57 +00006177 } else if (S->isFunctionPrototypeScope()) {
6178 // If this is an enum declaration in function prototype scope, set its
6179 // initial context to the translation unit.
6180 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00006181 }
6182
John McCall1f82f242009-11-18 22:49:29 +00006183 if (Previous.isSingleResult() &&
6184 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00006185 // Maybe we will complain about the shadowed template parameter.
John McCall1f82f242009-11-18 22:49:29 +00006186 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor5101c242008-12-05 18:15:24 +00006187 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00006188 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00006189 }
6190
Douglas Gregor87f54062009-09-15 22:30:29 +00006191 if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006192 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor87f54062009-09-15 22:30:29 +00006193 // This is a declaration of or a reference to "std::bad_alloc".
6194 isStdBadAlloc = true;
6195
John McCall1f82f242009-11-18 22:49:29 +00006196 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor87f54062009-09-15 22:30:29 +00006197 // std::bad_alloc has been implicitly declared (but made invisible to
6198 // name lookup). Fill in this implicit declaration as the previous
6199 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006200 Previous.addDecl(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +00006201 }
6202 }
John McCall1f82f242009-11-18 22:49:29 +00006203
John McCalle9eaf8e2010-03-25 21:28:06 +00006204 // If we didn't find a previous declaration, and this is a reference
6205 // (or friend reference), move to the correct scope. In C++, we
6206 // also need to do a redeclaration lookup there, just in case
6207 // there's a shadow friend decl.
6208 if (Name && Previous.empty() &&
6209 (TUK == TUK_Reference || TUK == TUK_Friend)) {
6210 if (Invalid) goto CreateNewDecl;
6211 assert(SS.isEmpty());
6212
6213 if (TUK == TUK_Reference) {
6214 // C++ [basic.scope.pdecl]p5:
6215 // -- for an elaborated-type-specifier of the form
6216 //
6217 // class-key identifier
6218 //
6219 // if the elaborated-type-specifier is used in the
6220 // decl-specifier-seq or parameter-declaration-clause of a
6221 // function defined in namespace scope, the identifier is
6222 // declared as a class-name in the namespace that contains
6223 // the declaration; otherwise, except as a friend
6224 // declaration, the identifier is declared in the smallest
6225 // non-class, non-function-prototype scope that contains the
6226 // declaration.
6227 //
6228 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
6229 // C structs and unions.
6230 //
6231 // It is an error in C++ to declare (rather than define) an enum
6232 // type, including via an elaborated type specifier. We'll
6233 // diagnose that later; for now, declare the enum in the same
6234 // scope as we would have picked for any other tag type.
6235 //
6236 // GNU C also supports this behavior as part of its incomplete
6237 // enum types extension, while GNU C++ does not.
6238 //
6239 // Find the context where we'll be declaring the tag.
6240 // FIXME: We would like to maintain the current DeclContext as the
6241 // lexical context,
Rafael Espindola9e976dc2011-01-20 02:26:24 +00006242 while (SearchDC->isRecord() || SearchDC->isTransparentContext())
John McCalle9eaf8e2010-03-25 21:28:06 +00006243 SearchDC = SearchDC->getParent();
6244
6245 // Find the scope where we'll be declaring the tag.
6246 while (S->isClassScope() ||
6247 (getLangOptions().CPlusPlus &&
6248 S->isFunctionPrototypeScope()) ||
6249 ((S->getFlags() & Scope::DeclScope) == 0) ||
6250 (S->getEntity() &&
6251 ((DeclContext *)S->getEntity())->isTransparentContext()))
6252 S = S->getParent();
6253 } else {
6254 assert(TUK == TUK_Friend);
6255 // C++ [namespace.memdef]p3:
6256 // If a friend declaration in a non-local class first declares a
6257 // class or function, the friend class or function is a member of
6258 // the innermost enclosing namespace.
6259 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCalle9eaf8e2010-03-25 21:28:06 +00006260 }
6261
John McCalle87beb22010-04-23 18:46:30 +00006262 // In C++, we need to do a redeclaration lookup to properly
6263 // diagnose some problems.
John McCalle9eaf8e2010-03-25 21:28:06 +00006264 if (getLangOptions().CPlusPlus) {
6265 Previous.setRedeclarationKind(ForRedeclaration);
6266 LookupQualifiedName(Previous, SearchDC);
6267 }
6268 }
6269
John McCall1f82f242009-11-18 22:49:29 +00006270 if (!Previous.empty()) {
Douglas Gregorce40e2e2010-04-12 16:00:01 +00006271 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
John McCalle87beb22010-04-23 18:46:30 +00006272
6273 // It's okay to have a tag decl in the same scope as a typedef
6274 // which hides a tag decl in the same scope. Finding this
6275 // insanity with a redeclaration lookup can only actually happen
6276 // in C++.
6277 //
6278 // This is also okay for elaborated-type-specifiers, which is
6279 // technically forbidden by the current standard but which is
6280 // okay according to the likely resolution of an open issue;
6281 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
6282 if (getLangOptions().CPlusPlus) {
6283 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(PrevDecl)) {
6284 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
6285 TagDecl *Tag = TT->getDecl();
6286 if (Tag->getDeclName() == Name &&
Sebastian Redl50c68252010-08-31 00:36:30 +00006287 Tag->getDeclContext()->getRedeclContext()
6288 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCalle87beb22010-04-23 18:46:30 +00006289 PrevDecl = Tag;
6290 Previous.clear();
6291 Previous.addDecl(Tag);
Douglas Gregorfcee9462010-08-27 22:55:10 +00006292 Previous.resolveKind();
John McCalle87beb22010-04-23 18:46:30 +00006293 }
6294 }
6295 }
6296 }
6297
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006298 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +00006299 // If this is a use of a previous tag, or if the tag is already declared
6300 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006301 // rementions the tag), reuse the decl.
John McCall07e91c02009-08-06 02:15:43 +00006302 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Douglas Gregordb446112011-03-07 16:54:27 +00006303 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +00006304 // Make sure that this wasn't declared as an enum and now used as a
6305 // struct or something similar.
Douglas Gregord9034f02009-05-14 16:41:31 +00006306 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00006307 bool SafeToContinue
Abramo Bagnara6150c882010-05-11 21:36:43 +00006308 = (PrevTagDecl->getTagKind() != TTK_Enum &&
6309 Kind != TTK_Enum);
Douglas Gregor170512f2009-04-01 23:51:29 +00006310 if (SafeToContinue)
Mike Stump11289f42009-09-09 15:08:12 +00006311 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00006312 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00006313 << FixItHint::CreateReplacement(SourceRange(KWLoc),
6314 PrevTagDecl->getKindName());
Douglas Gregor170512f2009-04-01 23:51:29 +00006315 else
6316 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall1f82f242009-11-18 22:49:29 +00006317 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00006318
Mike Stump11289f42009-09-09 15:08:12 +00006319 if (SafeToContinue)
Douglas Gregor170512f2009-04-01 23:51:29 +00006320 Kind = PrevTagDecl->getTagKind();
6321 else {
6322 // Recover by making this an anonymous redefinition.
6323 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00006324 Previous.clear();
Douglas Gregor170512f2009-04-01 23:51:29 +00006325 Invalid = true;
6326 }
6327 }
6328
Douglas Gregor0bf31402010-10-08 23:50:27 +00006329 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
6330 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
6331
6332 // All conflicts with previous declarations are recovered by
6333 // returning the previous declaration.
6334 if (ScopedEnum != PrevEnum->isScoped()) {
6335 Diag(KWLoc, diag::err_enum_redeclare_scoped_mismatch)
6336 << PrevEnum->isScoped();
6337 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
6338 return PrevTagDecl;
6339 }
6340 else if (EnumUnderlying && PrevEnum->isFixed()) {
6341 QualType T;
6342 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
6343 T = TI->getType();
6344 else
6345 T = QualType(EnumUnderlying.get<const Type*>(), 0);
6346
6347 if (!Context.hasSameUnqualifiedType(T, PrevEnum->getIntegerType())) {
Douglas Gregor1a099ba2010-12-01 16:10:38 +00006348 Diag(NameLoc.isValid() ? NameLoc : KWLoc,
6349 diag::err_enum_redeclare_type_mismatch)
6350 << T
6351 << PrevEnum->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006352 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
6353 return PrevTagDecl;
6354 }
6355 }
6356 else if (!EnumUnderlying.isNull() != PrevEnum->isFixed()) {
6357 Diag(KWLoc, diag::err_enum_redeclare_fixed_mismatch)
6358 << PrevEnum->isFixed();
6359 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
6360 return PrevTagDecl;
6361 }
6362 }
6363
Douglas Gregor170512f2009-04-01 23:51:29 +00006364 if (!Invalid) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006365 // If this is a use, just return the declaration we found.
Chris Lattner9ff58d72008-07-03 03:30:58 +00006366
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006367 // FIXME: In the future, return a variant or some other clue
6368 // for the consumer of this Decl to know it doesn't own it.
6369 // For our current ASTs this shouldn't be a problem, but will
6370 // need to be changed with DeclGroups.
Douglas Gregor6f2e0952010-06-08 21:27:36 +00006371 if ((TUK == TUK_Reference && !PrevTagDecl->getFriendObjectKind()) ||
6372 TUK == TUK_Friend)
John McCall48871652010-08-21 09:40:31 +00006373 return PrevTagDecl;
Douglas Gregorded2d7b2009-02-04 19:02:06 +00006374
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006375 // Diagnose attempts to redefine a tag.
John McCall9bb74a52009-07-31 02:45:11 +00006376 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00006377 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00006378 // If we're defining a specialization and the previous definition
6379 // is from an implicit instantiation, don't emit an error
6380 // here; we'll catch this in the general case below.
6381 if (!isExplicitSpecialization ||
6382 !isa<CXXRecordDecl>(Def) ||
6383 cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
6384 == TSK_ExplicitSpecialization) {
6385 Diag(NameLoc, diag::err_redefinition) << Name;
6386 Diag(Def->getLocation(), diag::note_previous_definition);
6387 // If this is a redefinition, recover by making this
6388 // struct be anonymous, which will make any later
6389 // references get the previous definition.
6390 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00006391 Previous.clear();
Douglas Gregor06db9f52009-10-12 20:18:28 +00006392 Invalid = true;
6393 }
Douglas Gregordee1be82009-01-17 00:42:38 +00006394 } else {
6395 // If the type is currently being defined, complain
6396 // about a nested redefinition.
John McCall424cec92011-01-19 06:33:43 +00006397 const TagType *Tag
6398 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregordee1be82009-01-17 00:42:38 +00006399 if (Tag->isBeingDefined()) {
6400 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump11289f42009-09-09 15:08:12 +00006401 Diag(PrevTagDecl->getLocation(),
Douglas Gregordee1be82009-01-17 00:42:38 +00006402 diag::note_previous_definition);
6403 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00006404 Previous.clear();
Douglas Gregordee1be82009-01-17 00:42:38 +00006405 Invalid = true;
6406 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006407 }
Douglas Gregordee1be82009-01-17 00:42:38 +00006408
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006409 // Okay, this is definition of a previously declared or referenced
6410 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregordee1be82009-01-17 00:42:38 +00006411 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006412 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006413 // If we get here we have (another) forward declaration or we
John McCall07e91c02009-08-06 02:15:43 +00006414 // have a definition. Just create a new decl.
6415
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006416 } else {
6417 // If we get here, this is a definition of a new tag type in a nested
Mike Stump11289f42009-09-09 15:08:12 +00006418 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006419 // new decl/type. We set PrevDecl to NULL so that the entities
6420 // have distinct types.
John McCall1f82f242009-11-18 22:49:29 +00006421 Previous.clear();
Chris Lattner7b9ace62007-01-23 20:11:08 +00006422 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006423 // If we get here, we're going to create a new Decl. If PrevDecl
6424 // is non-NULL, it's a definition of the tag declared by
6425 // PrevDecl. If it's NULL, we have a new definition.
John McCalle87beb22010-04-23 18:46:30 +00006426
6427
6428 // Otherwise, PrevDecl is not a tag, but was found with tag
6429 // lookup. This is only actually possible in C++, where a few
6430 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006431 } else {
John McCalle87beb22010-04-23 18:46:30 +00006432 assert(getLangOptions().CPlusPlus);
6433
6434 // Use a better diagnostic if an elaborated-type-specifier
6435 // found the wrong kind of type on the first
6436 // (non-redeclaration) lookup.
6437 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
6438 !Previous.isForRedeclaration()) {
6439 unsigned Kind = 0;
6440 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
6441 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 2;
6442 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
6443 Diag(PrevDecl->getLocation(), diag::note_declared_at);
6444 Invalid = true;
6445
6446 // Otherwise, only diagnose if the declaration is in scope.
Douglas Gregordb446112011-03-07 16:54:27 +00006447 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
6448 isExplicitSpecialization)) {
John McCalle87beb22010-04-23 18:46:30 +00006449 // do nothing
6450
6451 // Diagnose implicit declarations introduced by elaborated types.
6452 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
6453 unsigned Kind = 0;
6454 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
6455 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 2;
6456 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
6457 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
6458 Invalid = true;
6459
6460 // Otherwise it's a declaration. Call out a particularly common
6461 // case here.
6462 } else if (isa<TypedefDecl>(PrevDecl)) {
6463 Diag(NameLoc, diag::err_tag_definition_of_typedef)
6464 << Name
6465 << cast<TypedefDecl>(PrevDecl)->getUnderlyingType();
6466 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
6467 Invalid = true;
6468
6469 // Otherwise, diagnose.
6470 } else {
6471 // The tag name clashes with something else in the target scope,
6472 // issue an error and recover by making this tag be anonymous.
Chris Lattner4bd8dd82008-11-19 08:23:25 +00006473 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner0369c572008-11-23 23:12:31 +00006474 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +00006475 Name = 0;
Douglas Gregordee1be82009-01-17 00:42:38 +00006476 Invalid = true;
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +00006477 }
John McCalle87beb22010-04-23 18:46:30 +00006478
6479 // The existing declaration isn't relevant to us; we're in a
6480 // new scope, so clear out the previous declaration.
6481 Previous.clear();
Chris Lattner8799cf22007-01-23 01:57:16 +00006482 }
Chris Lattner18b19622007-01-22 07:39:13 +00006483 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00006484
Chris Lattner438e5012008-12-17 07:13:27 +00006485CreateNewDecl:
Mike Stump11289f42009-09-09 15:08:12 +00006486
John McCall1f82f242009-11-18 22:49:29 +00006487 TagDecl *PrevDecl = 0;
6488 if (Previous.isSingleResult())
6489 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
6490
Chris Lattnerbf0b7982007-01-23 04:27:41 +00006491 // If there is an identifier, use the location of the identifier as the
6492 // location of the decl, otherwise use the location of the struct/union
6493 // keyword.
6494 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump11289f42009-09-09 15:08:12 +00006495
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006496 // Otherwise, create a new declaration. If there is a previous
6497 // declaration of the same entity, the two will be linked via
6498 // PrevDecl.
Chris Lattner7b9ace62007-01-23 20:11:08 +00006499 TagDecl *New;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00006500
Douglas Gregor0bf31402010-10-08 23:50:27 +00006501 bool IsForwardReference = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +00006502 if (Kind == TTK_Enum) {
Chris Lattner776fac82007-06-09 00:53:06 +00006503 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
6504 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006505 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor0bf31402010-10-08 23:50:27 +00006506 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00006507 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Chris Lattner5f521502007-01-25 06:27:24 +00006508 // If this is an undefined enum, warn.
Douglas Gregorc9ea2d52010-06-22 14:26:35 +00006509 if (TUK != TUK_Definition && !Invalid) {
6510 TagDecl *Def;
Douglas Gregor0bf31402010-10-08 23:50:27 +00006511 if (getLangOptions().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) {
6512 // C++0x: 7.2p2: opaque-enum-declaration.
6513 // Conflicts are diagnosed above. Do nothing.
6514 }
6515 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorc9ea2d52010-06-22 14:26:35 +00006516 Diag(Loc, diag::ext_forward_ref_enum_def)
6517 << New;
6518 Diag(Def->getLocation(), diag::note_previous_definition);
6519 } else {
Francois Pichet488b4a72010-09-12 05:06:55 +00006520 unsigned DiagID = diag::ext_forward_ref_enum;
6521 if (getLangOptions().Microsoft)
6522 DiagID = diag::ext_ms_forward_ref_enum;
6523 else if (getLangOptions().CPlusPlus)
6524 DiagID = diag::err_forward_ref_enum;
6525 Diag(Loc, DiagID);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006526
6527 // If this is a forward-declared reference to an enumeration, make a
6528 // note of it; we won't actually be introducing the declaration into
6529 // the declaration context.
6530 if (TUK == TUK_Reference)
6531 IsForwardReference = true;
Douglas Gregorc9ea2d52010-06-22 14:26:35 +00006532 }
Douglas Gregord45b93b2009-03-06 18:34:03 +00006533 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00006534
6535 if (EnumUnderlying) {
6536 EnumDecl *ED = cast<EnumDecl>(New);
6537 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
6538 ED->setIntegerTypeSourceInfo(TI);
6539 else
6540 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
6541 ED->setPromotionType(ED->getIntegerType());
6542 }
6543
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00006544 } else {
6545 // struct/union/class
6546
Chris Lattner776fac82007-06-09 00:53:06 +00006547 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
6548 // struct X { int A; } D; D should chain to X.
Douglas Gregor87f54062009-09-15 22:30:29 +00006549 if (getLangOptions().CPlusPlus) {
Ted Kremenek6ddf53e2008-09-05 17:39:33 +00006550 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006551 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006552 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006553
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006554 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor87f54062009-09-15 22:30:29 +00006555 StdBadAlloc = cast<CXXRecordDecl>(New);
6556 } else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006557 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006558 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006559 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006560
John McCall3e11ebe2010-03-15 10:12:16 +00006561 // Maybe add qualifier info.
6562 if (SS.isNotEmpty()) {
Fariborz Jahanian862fac92010-05-14 21:35:02 +00006563 if (SS.isSet()) {
Douglas Gregor14454802011-02-25 02:25:35 +00006564 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006565 if (NumMatchedTemplateParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006566 New->setTemplateParameterListsInfo(Context,
6567 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006568 (TemplateParameterList**) TemplateParameterLists.release());
6569 }
Fariborz Jahanian862fac92010-05-14 21:35:02 +00006570 }
6571 else
6572 Invalid = true;
John McCall3e11ebe2010-03-15 10:12:16 +00006573 }
6574
Daniel Dunbar8804f2e2010-05-27 01:53:40 +00006575 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
6576 // Add alignment attributes if necessary; these attributes are checked when
6577 // the ASTContext lays out the structure.
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006578 //
6579 // It is important for implementing the correct semantics that this
6580 // happen here (in act on tag decl). The #pragma pack stack is
6581 // maintained as a result of parser callbacks which can occur at
6582 // many points during the parsing of a struct declaration (because
6583 // the #pragma tokens are effectively skipped over during the
6584 // parsing of the struct).
Daniel Dunbar8804f2e2010-05-27 01:53:40 +00006585 AddAlignmentAttributesForRecord(RD);
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006586 }
6587
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006588 // If this is a specialization of a member class (of a class template),
6589 // check the specialization.
John McCall1f82f242009-11-18 22:49:29 +00006590 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006591 Invalid = true;
Daniel Dunbar8804f2e2010-05-27 01:53:40 +00006592
Douglas Gregordee1be82009-01-17 00:42:38 +00006593 if (Invalid)
6594 New->setInvalidDecl();
6595
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006596 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00006597 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006598
Douglas Gregordee1be82009-01-17 00:42:38 +00006599 // If we're declaring or defining a tag in function prototype scope
6600 // in C, note that this type can only be used within the function.
Douglas Gregor658b9552009-01-09 22:42:13 +00006601 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
6602 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
6603
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006604 // Set the lexical context. If the tag has a C++ scope specifier, the
6605 // lexical context will be different from the semantic context.
Douglas Gregor8761da52009-02-03 00:34:39 +00006606 New->setLexicalDeclContext(CurContext);
Douglas Gregordee1be82009-01-17 00:42:38 +00006607
John McCallaa74a0c2009-08-28 07:59:38 +00006608 // Mark this as a friend decl if applicable.
6609 if (TUK == TUK_Friend)
John McCall1f82f242009-11-18 22:49:29 +00006610 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty());
John McCallaa74a0c2009-08-28 07:59:38 +00006611
Anders Carlsson5558ca12009-03-26 01:19:02 +00006612 // Set the access specifier.
John McCalle9eaf8e2010-03-25 21:28:06 +00006613 if (!Invalid && SearchDC->isRecord())
Douglas Gregorb8006faf2009-05-27 17:30:49 +00006614 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor6c2adff2009-03-25 22:00:53 +00006615
John McCall9bb74a52009-07-31 02:45:11 +00006616 if (TUK == TUK_Definition)
Douglas Gregordee1be82009-01-17 00:42:38 +00006617 New->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00006618
Chris Lattner18b19622007-01-22 07:39:13 +00006619 // If this has an identifier, add it to the scope stack.
John McCall2dc078f2009-09-02 00:55:30 +00006620 if (TUK == TUK_Friend) {
John McCallf8bd8612009-09-02 19:32:14 +00006621 // We might be replacing an existing declaration in the lookup tables;
6622 // if so, borrow its access specifier.
6623 if (PrevDecl)
6624 New->setAccess(PrevDecl->getAccess());
6625
Sebastian Redl50c68252010-08-31 00:36:30 +00006626 DeclContext *DC = New->getDeclContext()->getRedeclContext();
John McCalle9eaf8e2010-03-25 21:28:06 +00006627 DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
6628 if (Name) // can be null along some error paths
John McCall2dc078f2009-09-02 00:55:30 +00006629 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
6630 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCall2dc078f2009-09-02 00:55:30 +00006631 } else if (Name) {
Douglas Gregor45a33ec2009-01-12 18:45:55 +00006632 S = getNonFieldDeclScope(S);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006633 PushOnScopeChains(New, S, !IsForwardReference);
6634 if (IsForwardReference)
6635 SearchDC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
6636
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00006637 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006638 CurContext->addDecl(New);
Chris Lattner18b19622007-01-22 07:39:13 +00006639 }
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00006640
Douglas Gregor27821ce2009-07-07 16:35:42 +00006641 // If this is the C FILE type, notify the AST context.
6642 if (IdentifierInfo *II = New->getIdentifier())
6643 if (!New->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00006644 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor27821ce2009-07-07 16:35:42 +00006645 II->isStr("FILE"))
6646 Context.setFILEDecl(New);
Mike Stump11289f42009-09-09 15:08:12 +00006647
Douglas Gregord6ab8742009-05-28 23:31:59 +00006648 OwnedDecl = true;
John McCall48871652010-08-21 09:40:31 +00006649 return New;
Chris Lattner18b19622007-01-22 07:39:13 +00006650}
Chris Lattner1300fb92007-01-23 23:42:53 +00006651
John McCall48871652010-08-21 09:40:31 +00006652void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00006653 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00006654 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregorba41d012010-04-24 16:38:41 +00006655
Douglas Gregor82ac25e2009-01-08 20:45:30 +00006656 // Enter the tag context.
6657 PushDeclContext(S, Tag);
John McCall1c7e6ec2009-12-20 07:58:13 +00006658}
Douglas Gregor82ac25e2009-01-08 20:45:30 +00006659
John McCall48871652010-08-21 09:40:31 +00006660void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlssonfc1eef42011-01-22 17:51:53 +00006661 ClassVirtSpecifiers &CVS,
John McCall1c7e6ec2009-12-20 07:58:13 +00006662 SourceLocation LBraceLoc) {
6663 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00006664 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00006665
John McCall1c7e6ec2009-12-20 07:58:13 +00006666 FieldCollector->StartClass();
6667
6668 if (!Record->getIdentifier())
6669 return;
6670
Anders Carlsson1eb95962011-01-24 16:26:15 +00006671 if (CVS.isFinalSpecified())
6672 Record->addAttr(new (Context) FinalAttr(CVS.getFinalLoc(), Context));
6673 if (CVS.isExplicitSpecified())
6674 Record->addAttr(new (Context) ExplicitAttr(CVS.getExplicitLoc(), Context));
Anders Carlssonfc1eef42011-01-22 17:51:53 +00006675
John McCall1c7e6ec2009-12-20 07:58:13 +00006676 // C++ [class]p2:
6677 // [...] The class-name is also inserted into the scope of the
6678 // class itself; this is known as the injected-class-name. For
6679 // purposes of access checking, the injected-class-name is treated
6680 // as if it were a public member name.
6681 CXXRecordDecl *InjectedClassName
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006682 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
6683 Record->getLocStart(), Record->getLocation(),
John McCall1c7e6ec2009-12-20 07:58:13 +00006684 Record->getIdentifier(),
Argyrios Kyrtzidis470c4542010-10-14 20:14:21 +00006685 /*PrevDecl=*/0,
6686 /*DelayTypeCreation=*/true);
6687 Context.getTypeDeclType(InjectedClassName, Record);
John McCall1c7e6ec2009-12-20 07:58:13 +00006688 InjectedClassName->setImplicit();
6689 InjectedClassName->setAccess(AS_public);
6690 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
6691 InjectedClassName->setDescribedClassTemplate(Template);
6692 PushOnScopeChains(InjectedClassName, S);
6693 assert(InjectedClassName->isInjectedClassName() &&
6694 "Broken injected-class-name");
Douglas Gregor82ac25e2009-01-08 20:45:30 +00006695}
6696
John McCall48871652010-08-21 09:40:31 +00006697void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +00006698 SourceLocation RBraceLoc) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00006699 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00006700 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +00006701 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00006702
6703 if (isa<CXXRecordDecl>(Tag))
6704 FieldCollector->FinishClass();
6705
6706 // Exit this scope of this tag's definition.
6707 PopDeclContext();
Douglas Gregor859f0ae2010-01-06 17:00:51 +00006708
Douglas Gregor82ac25e2009-01-08 20:45:30 +00006709 // Notify the consumer that we've defined a tag.
6710 Consumer.HandleTagDeclDefinition(Tag);
6711}
Chris Lattner535b8302008-06-21 19:39:06 +00006712
John McCall48871652010-08-21 09:40:31 +00006713void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCall2ff380a2010-03-17 00:38:33 +00006714 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00006715 TagDecl *Tag = cast<TagDecl>(TagD);
John McCall2ff380a2010-03-17 00:38:33 +00006716 Tag->setInvalidDecl();
6717
John McCall71ba5f22010-03-17 19:25:57 +00006718 // We're undoing ActOnTagStartDefinition here, not
6719 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
6720 // the FieldCollector.
John McCall2ff380a2010-03-17 00:38:33 +00006721
6722 PopDeclContext();
6723}
6724
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00006725// Note that FieldName may be null for anonymous bitfields.
Mike Stump11289f42009-09-09 15:08:12 +00006726bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Eli Friedmanc96d4962009-08-15 21:55:26 +00006727 QualType FieldTy, const Expr *BitWidth,
6728 bool *ZeroWidth) {
6729 // Default to true; that shouldn't confuse checks for emptiness
6730 if (ZeroWidth)
6731 *ZeroWidth = true;
6732
Chris Lattner73bf7b42009-03-05 22:45:59 +00006733 // C99 6.7.2.1p4 - verify the field type.
Chris Lattnerd26760a2009-03-05 23:01:03 +00006734 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregorb90df602010-06-16 00:17:44 +00006735 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner73bf7b42009-03-05 22:45:59 +00006736 // Handle incomplete types with specific error.
Douglas Gregor81457422009-03-10 21:58:27 +00006737 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
6738 return true;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00006739 if (FieldName)
6740 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
6741 << FieldName << FieldTy << BitWidth->getSourceRange();
6742 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
6743 << FieldTy << BitWidth->getSourceRange();
Douglas Gregora02a72a2010-12-15 23:18:36 +00006744 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
6745 UPPC_BitFieldWidth))
6746 return true;
Douglas Gregor1efa4372009-03-11 18:59:21 +00006747
6748 // If the bit-width is type- or value-dependent, don't try to check
6749 // it now.
6750 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
6751 return false;
6752
Anders Carlsson5df391e2008-12-06 20:33:04 +00006753 llvm::APSInt Value;
6754 if (VerifyIntegerConstantExpression(BitWidth, &Value))
6755 return true;
6756
Eli Friedmanc96d4962009-08-15 21:55:26 +00006757 if (Value != 0 && ZeroWidth)
6758 *ZeroWidth = false;
6759
Chris Lattner81ed6802008-12-12 04:56:04 +00006760 // Zero-width bitfield is ok for anonymous field.
6761 if (Value == 0 && FieldName)
6762 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00006763
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00006764 if (Value.isSigned() && Value.isNegative()) {
6765 if (FieldName)
Mike Stump11289f42009-09-09 15:08:12 +00006766 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00006767 << FieldName << Value.toString(10);
6768 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
6769 << Value.toString(10);
6770 }
Anders Carlsson5df391e2008-12-06 20:33:04 +00006771
Douglas Gregor1efa4372009-03-11 18:59:21 +00006772 if (!FieldTy->isDependentType()) {
6773 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00006774 if (Value.getZExtValue() > TypeSize) {
Anders Carlssond5635fe2010-04-16 15:16:32 +00006775 if (!getLangOptions().CPlusPlus) {
6776 if (FieldName)
6777 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
6778 << FieldName << (unsigned)Value.getZExtValue()
6779 << (unsigned)TypeSize;
6780
6781 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
6782 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
6783 }
6784
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00006785 if (FieldName)
Anders Carlssond5635fe2010-04-16 15:16:32 +00006786 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
6787 << FieldName << (unsigned)Value.getZExtValue()
6788 << (unsigned)TypeSize;
6789 else
6790 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
6791 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00006792 }
Douglas Gregor1efa4372009-03-11 18:59:21 +00006793 }
Anders Carlsson5df391e2008-12-06 20:33:04 +00006794
6795 return false;
6796}
6797
Steve Naroff30d242c2007-09-15 18:49:24 +00006798/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +00006799/// to create a FieldDecl object for it.
John McCall48871652010-08-21 09:40:31 +00006800Decl *Sema::ActOnField(Scope *S, Decl *TagD,
Mike Stump11289f42009-09-09 15:08:12 +00006801 SourceLocation DeclStart,
Chris Lattner83f095c2009-03-28 19:18:32 +00006802 Declarator &D, ExprTy *BitfieldWidth) {
John McCall48871652010-08-21 09:40:31 +00006803 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattner83f095c2009-03-28 19:18:32 +00006804 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
6805 AS_public);
John McCall48871652010-08-21 09:40:31 +00006806 return Res;
Chris Lattner73bf7b42009-03-05 22:45:59 +00006807}
6808
6809/// HandleField - Analyze a field of a C struct or a C++ data member.
6810///
6811FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
6812 SourceLocation DeclStart,
Douglas Gregor4261e4c2009-03-11 20:50:30 +00006813 Declarator &D, Expr *BitWidth,
6814 AccessSpecifier AS) {
Chris Lattner1300fb92007-01-23 23:42:53 +00006815 IdentifierInfo *II = D.getIdentifier();
Chris Lattner1300fb92007-01-23 23:42:53 +00006816 SourceLocation Loc = DeclStart;
6817 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +00006818
John McCall8cb7bdf2010-06-04 23:28:52 +00006819 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6820 QualType T = TInfo->getType();
Douglas Gregora02a72a2010-12-15 23:18:36 +00006821 if (getLangOptions().CPlusPlus) {
Douglas Gregor1efa4372009-03-11 18:59:21 +00006822 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00006823
Douglas Gregora02a72a2010-12-15 23:18:36 +00006824 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6825 UPPC_DataMemberType)) {
6826 D.setInvalidType();
6827 T = Context.IntTy;
6828 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
6829 }
6830 }
6831
Eli Friedman574c7452009-04-07 19:37:57 +00006832 DiagnoseFunctionSpecifiers(D);
6833
Eli Friedmand5c0eed2009-04-19 20:27:55 +00006834 if (D.getDeclSpec().isThreadSpecified())
6835 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
Douglas Gregor2c7d9292010-08-30 14:32:14 +00006836
6837 // Check to see if this name was declared as a member previously
6838 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
6839 LookupName(Previous, S);
6840 assert((Previous.empty() || Previous.isOverloadedResult() ||
6841 Previous.isSingleResult())
6842 && "Lookup of member name should be either overloaded, single or null");
Eli Friedmand5c0eed2009-04-19 20:27:55 +00006843
Douglas Gregor2c7d9292010-08-30 14:32:14 +00006844 // If the name is overloaded then get any declaration else get the single result
6845 NamedDecl *PrevDecl = Previous.isOverloadedResult() ?
6846 Previous.getRepresentativeDecl() : Previous.getAsSingle<NamedDecl>();
Douglas Gregorf187420f2009-06-17 23:37:01 +00006847
6848 if (PrevDecl && PrevDecl->isTemplateParameter()) {
6849 // Maybe we will complain about the shadowed template parameter.
6850 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
6851 // Just pretend that we didn't see the previous declaration.
6852 PrevDecl = 0;
6853 }
6854
Douglas Gregor1efa4372009-03-11 18:59:21 +00006855 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
6856 PrevDecl = 0;
6857
Steve Naroff5ec6ff72009-07-14 14:58:18 +00006858 bool Mutable
6859 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
6860 SourceLocation TSSL = D.getSourceRange().getBegin();
6861 FieldDecl *NewFD
John McCallbcd03502009-12-07 02:54:59 +00006862 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, TSSL,
Steve Naroff5ec6ff72009-07-14 14:58:18 +00006863 AS, PrevDecl, &D);
Rafael Espindola568586f2010-03-21 22:56:43 +00006864
6865 if (NewFD->isInvalidDecl())
6866 Record->setInvalidDecl();
6867
Douglas Gregor1efa4372009-03-11 18:59:21 +00006868 if (NewFD->isInvalidDecl() && PrevDecl) {
6869 // Don't introduce NewFD into scope; there's already something
6870 // with the same name in the same scope.
6871 } else if (II) {
6872 PushOnScopeChains(NewFD, S);
6873 } else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006874 Record->addDecl(NewFD);
Douglas Gregor1efa4372009-03-11 18:59:21 +00006875
6876 return NewFD;
6877}
6878
6879/// \brief Build a new FieldDecl and check its well-formedness.
6880///
6881/// This routine builds a new FieldDecl given the fields name, type,
6882/// record, etc. \p PrevDecl should refer to any previous declaration
6883/// with the same name and in the same scope as the field to be
6884/// created.
6885///
6886/// \returns a new FieldDecl.
6887///
Mike Stump11289f42009-09-09 15:08:12 +00006888/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00006889FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCallbcd03502009-12-07 02:54:59 +00006890 TypeSourceInfo *TInfo,
Douglas Gregor1efa4372009-03-11 18:59:21 +00006891 RecordDecl *Record, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00006892 bool Mutable, Expr *BitWidth,
Steve Naroff5ec6ff72009-07-14 14:58:18 +00006893 SourceLocation TSSL,
Douglas Gregor4261e4c2009-03-11 20:50:30 +00006894 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor1efa4372009-03-11 18:59:21 +00006895 Declarator *D) {
6896 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Narofff93b6722007-08-28 20:14:24 +00006897 bool InvalidDecl = false;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006898 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006899
Douglas Gregor1efa4372009-03-11 18:59:21 +00006900 // If we receive a broken type, recover by assuming 'int' and
6901 // marking this declaration as invalid.
6902 if (T.isNull()) {
6903 InvalidDecl = true;
6904 T = Context.IntTy;
6905 }
6906
Eli Friedmand0e8de22009-12-07 00:22:08 +00006907 QualType EltTy = Context.getBaseElementType(T);
6908 if (!EltTy->isDependentType() &&
John McCall2677e102010-08-16 23:42:35 +00006909 RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
6910 // Fields of incomplete type force their record to be invalid.
6911 Record->setInvalidDecl();
Eli Friedmand0e8de22009-12-07 00:22:08 +00006912 InvalidDecl = true;
John McCall2677e102010-08-16 23:42:35 +00006913 }
Eli Friedmand0e8de22009-12-07 00:22:08 +00006914
Steve Naroff8eeeb132007-05-08 21:09:37 +00006915 // C99 6.7.2.1p8: A member of a structure or union may have any type other
6916 // than a variably modified type.
Eli Friedmand0e8de22009-12-07 00:22:08 +00006917 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00006918 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00006919 llvm::APSInt Oversized;
Eli Friedmana3b1d032009-02-21 00:44:51 +00006920 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00006921 SizeIsNegative,
6922 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00006923 if (!FixedTy.isNull()) {
6924 Diag(Loc, diag::warn_illegal_constant_array_size);
6925 T = FixedTy;
6926 } else {
6927 if (SizeIsNegative)
6928 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00006929 else if (Oversized.getBoolValue())
6930 Diag(Loc, diag::err_array_too_large)
6931 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00006932 else
6933 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00006934 InvalidDecl = true;
6935 }
Steve Naroff8eeeb132007-05-08 21:09:37 +00006936 }
Mike Stump11289f42009-09-09 15:08:12 +00006937
Anders Carlsson576cc6f2009-03-22 20:18:17 +00006938 // Fields can not have abstract class types
Eli Friedmand0e8de22009-12-07 00:22:08 +00006939 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
6940 diag::err_abstract_type_in_decl,
6941 AbstractFieldType))
Anders Carlsson576cc6f2009-03-22 20:18:17 +00006942 InvalidDecl = true;
Mike Stump11289f42009-09-09 15:08:12 +00006943
Eli Friedmanc96d4962009-08-15 21:55:26 +00006944 bool ZeroWidth = false;
Douglas Gregor1efa4372009-03-11 18:59:21 +00006945 // If this is declared as a bit-field, check the bit-field.
Eli Friedmand0e8de22009-12-07 00:22:08 +00006946 if (!InvalidDecl && BitWidth &&
6947 VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
Douglas Gregor1efa4372009-03-11 18:59:21 +00006948 InvalidDecl = true;
Douglas Gregor1efa4372009-03-11 18:59:21 +00006949 BitWidth = 0;
Eli Friedmanc96d4962009-08-15 21:55:26 +00006950 ZeroWidth = false;
Anders Carlsson5df391e2008-12-06 20:33:04 +00006951 }
Mike Stump11289f42009-09-09 15:08:12 +00006952
John McCallb1cd7da2010-06-04 08:34:12 +00006953 // Check that 'mutable' is consistent with the type of the declaration.
6954 if (!InvalidDecl && Mutable) {
6955 unsigned DiagID = 0;
6956 if (T->isReferenceType())
6957 DiagID = diag::err_mutable_reference;
6958 else if (T.isConstQualified())
6959 DiagID = diag::err_mutable_const;
6960
6961 if (DiagID) {
6962 SourceLocation ErrLoc = Loc;
6963 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
6964 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
6965 Diag(ErrLoc, DiagID);
6966 Mutable = false;
6967 InvalidDecl = true;
6968 }
6969 }
6970
Abramo Bagnaradff19302011-03-08 08:55:46 +00006971 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00006972 BitWidth, Mutable);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006973 if (InvalidDecl)
6974 NewFD->setInvalidDecl();
Douglas Gregor91f84212008-12-11 16:49:14 +00006975
Douglas Gregor1efa4372009-03-11 18:59:21 +00006976 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
6977 Diag(Loc, diag::err_duplicate_member) << II;
6978 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
6979 NewFD->setInvalidDecl();
Douglas Gregor82ac25e2009-01-08 20:45:30 +00006980 }
6981
John McCall67da35c2010-02-04 22:26:26 +00006982 if (!InvalidDecl && getLangOptions().CPlusPlus) {
Anders Carlsson2ceb3472010-11-07 19:13:55 +00006983 if (Record->isUnion()) {
6984 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
6985 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
6986 if (RDecl->getDefinition()) {
6987 // C++ [class.union]p1: An object of a class with a non-trivial
6988 // constructor, a non-trivial copy constructor, a non-trivial
6989 // destructor, or a non-trivial copy assignment operator
6990 // cannot be a member of a union, nor can an array of such
6991 // objects.
6992 // TODO: C++0x alters this restriction significantly.
6993 if (CheckNontrivialField(NewFD))
6994 NewFD->setInvalidDecl();
6995 }
6996 }
6997
6998 // C++ [class.union]p1: If a union contains a member of reference type,
6999 // the program is ill-formed.
7000 if (EltTy->isReferenceType()) {
7001 Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
7002 << NewFD->getDeclName() << EltTy;
7003 NewFD->setInvalidDecl();
Douglas Gregor8a273912009-07-22 18:25:24 +00007004 }
7005 }
7006 }
7007
Douglas Gregor1efa4372009-03-11 18:59:21 +00007008 // FIXME: We need to pass in the attributes given an AST
7009 // representation, not a parser representation.
7010 if (D)
Douglas Gregor758a8692009-06-17 21:51:59 +00007011 // FIXME: What to pass instead of TUScope?
7012 ProcessDeclAttributes(TUScope, NewFD, *D);
Douglas Gregor1efa4372009-03-11 18:59:21 +00007013
Fariborz Jahaniand29fecd2009-02-19 00:22:47 +00007014 if (T.isObjCGCWeak())
Fariborz Jahaniand35c7922009-02-18 18:14:41 +00007015 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlsson28e71082008-02-16 00:29:18 +00007016
Douglas Gregor4261e4c2009-03-11 20:50:30 +00007017 NewFD->setAccess(AS);
Steve Narofff93b6722007-08-28 20:14:24 +00007018 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +00007019}
7020
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00007021bool Sema::CheckNontrivialField(FieldDecl *FD) {
7022 assert(FD);
7023 assert(getLangOptions().CPlusPlus && "valid check only for C++");
7024
7025 if (FD->isInvalidDecl())
7026 return true;
7027
7028 QualType EltTy = Context.getBaseElementType(FD->getType());
7029 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
7030 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
7031 if (RDecl->getDefinition()) {
7032 // We check for copy constructors before constructors
7033 // because otherwise we'll never get complaints about
7034 // copy constructors.
7035
7036 CXXSpecialMember member = CXXInvalid;
7037 if (!RDecl->hasTrivialCopyConstructor())
7038 member = CXXCopyConstructor;
7039 else if (!RDecl->hasTrivialConstructor())
7040 member = CXXConstructor;
7041 else if (!RDecl->hasTrivialCopyAssignment())
7042 member = CXXCopyAssignment;
7043 else if (!RDecl->hasTrivialDestructor())
7044 member = CXXDestructor;
7045
7046 if (member != CXXInvalid) {
7047 Diag(FD->getLocation(), diag::err_illegal_union_or_anon_struct_member)
7048 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
7049 DiagnoseNontrivial(RT, member);
7050 return true;
7051 }
7052 }
7053 }
7054
7055 return false;
7056}
7057
Douglas Gregor8a273912009-07-22 18:25:24 +00007058/// DiagnoseNontrivial - Given that a class has a non-trivial
7059/// special member, figure out why.
7060void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
7061 QualType QT(T, 0U);
7062 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
7063
7064 // Check whether the member was user-declared.
7065 switch (member) {
Douglas Gregorfceea362010-04-22 14:36:26 +00007066 case CXXInvalid:
7067 break;
7068
Anders Carlsson05bf0092010-04-22 05:40:53 +00007069 case CXXConstructor:
Douglas Gregor8a273912009-07-22 18:25:24 +00007070 if (RD->hasUserDeclaredConstructor()) {
7071 typedef CXXRecordDecl::ctor_iterator ctor_iter;
Sebastian Redle24b1622009-10-25 22:31:45 +00007072 for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
7073 const FunctionDecl *body = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007074 ci->hasBody(body);
Anders Carlssonb7229932010-04-20 23:32:58 +00007075 if (!body || !cast<CXXConstructorDecl>(body)->isImplicitlyDefined()) {
Douglas Gregor8a273912009-07-22 18:25:24 +00007076 SourceLocation CtorLoc = ci->getLocation();
7077 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
7078 return;
7079 }
Sebastian Redle24b1622009-10-25 22:31:45 +00007080 }
Douglas Gregor8a273912009-07-22 18:25:24 +00007081
7082 assert(0 && "found no user-declared constructors");
7083 return;
7084 }
7085 break;
7086
7087 case CXXCopyConstructor:
7088 if (RD->hasUserDeclaredCopyConstructor()) {
7089 SourceLocation CtorLoc =
7090 RD->getCopyConstructor(Context, 0)->getLocation();
7091 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
7092 return;
7093 }
7094 break;
7095
7096 case CXXCopyAssignment:
7097 if (RD->hasUserDeclaredCopyAssignment()) {
7098 // FIXME: this should use the location of the copy
7099 // assignment, not the type.
7100 SourceLocation TyLoc = RD->getSourceRange().getBegin();
7101 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
7102 return;
7103 }
7104 break;
7105
7106 case CXXDestructor:
7107 if (RD->hasUserDeclaredDestructor()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00007108 SourceLocation DtorLoc = LookupDestructor(RD)->getLocation();
Douglas Gregor8a273912009-07-22 18:25:24 +00007109 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
7110 return;
7111 }
7112 break;
7113 }
7114
7115 typedef CXXRecordDecl::base_class_iterator base_iter;
7116
7117 // Virtual bases and members inhibit trivial copying/construction,
7118 // but not trivial destruction.
7119 if (member != CXXDestructor) {
7120 // Check for virtual bases. vbases includes indirect virtual bases,
7121 // so we just iterate through the direct bases.
7122 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
7123 if (bi->isVirtual()) {
7124 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
7125 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
7126 return;
7127 }
7128
7129 // Check for virtual methods.
7130 typedef CXXRecordDecl::method_iterator meth_iter;
7131 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
7132 ++mi) {
7133 if (mi->isVirtual()) {
7134 SourceLocation MLoc = mi->getSourceRange().getBegin();
7135 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
7136 return;
7137 }
7138 }
7139 }
Mike Stump11289f42009-09-09 15:08:12 +00007140
Douglas Gregor8a273912009-07-22 18:25:24 +00007141 bool (CXXRecordDecl::*hasTrivial)() const;
7142 switch (member) {
Anders Carlsson05bf0092010-04-22 05:40:53 +00007143 case CXXConstructor:
Douglas Gregor8a273912009-07-22 18:25:24 +00007144 hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break;
7145 case CXXCopyConstructor:
7146 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
7147 case CXXCopyAssignment:
7148 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
7149 case CXXDestructor:
7150 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
7151 default:
7152 assert(0 && "unexpected special member"); return;
7153 }
7154
7155 // Check for nontrivial bases (and recurse).
7156 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007157 const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
Sebastian Redl1054fae2009-10-25 17:03:50 +00007158 assert(BaseRT && "Don't know how to handle dependent bases");
Douglas Gregor8a273912009-07-22 18:25:24 +00007159 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
7160 if (!(BaseRecTy->*hasTrivial)()) {
7161 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
7162 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
7163 DiagnoseNontrivial(BaseRT, member);
7164 return;
7165 }
7166 }
Mike Stump11289f42009-09-09 15:08:12 +00007167
Douglas Gregor8a273912009-07-22 18:25:24 +00007168 // Check for nontrivial members (and recurse).
7169 typedef RecordDecl::field_iterator field_iter;
7170 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
7171 ++fi) {
Douglas Gregor79f83ed2009-07-23 23:49:00 +00007172 QualType EltTy = Context.getBaseElementType((*fi)->getType());
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007173 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
Douglas Gregor8a273912009-07-22 18:25:24 +00007174 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
7175
7176 if (!(EltRD->*hasTrivial)()) {
7177 SourceLocation FLoc = (*fi)->getLocation();
7178 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
7179 DiagnoseNontrivial(EltRT, member);
7180 return;
7181 }
7182 }
7183 }
7184
7185 assert(0 && "found no explanation for non-trivial member");
7186}
7187
Mike Stump11289f42009-09-09 15:08:12 +00007188/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00007189/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007190static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00007191TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +00007192 switch (ivarVisibility) {
Chris Lattner79ef8432008-10-12 00:28:42 +00007193 default: assert(0 && "Unknown visitibility kind");
7194 case tok::objc_private: return ObjCIvarDecl::Private;
7195 case tok::objc_public: return ObjCIvarDecl::Public;
7196 case tok::objc_protected: return ObjCIvarDecl::Protected;
7197 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroff2e688fd2007-09-14 23:09:53 +00007198 }
7199}
7200
Mike Stump11289f42009-09-09 15:08:12 +00007201/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian96376742008-04-11 16:55:42 +00007202/// in order to create an IvarDecl object for it.
John McCall48871652010-08-21 09:40:31 +00007203Decl *Sema::ActOnIvar(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00007204 SourceLocation DeclStart,
John McCall48871652010-08-21 09:40:31 +00007205 Decl *IntfDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00007206 Declarator &D, ExprTy *BitfieldWidth,
7207 tok::ObjCKeywordKind Visibility) {
Mike Stump11289f42009-09-09 15:08:12 +00007208
Fariborz Jahaniande615832008-04-10 23:32:45 +00007209 IdentifierInfo *II = D.getIdentifier();
7210 Expr *BitWidth = (Expr*)BitfieldWidth;
7211 SourceLocation Loc = DeclStart;
7212 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +00007213
Fariborz Jahaniande615832008-04-10 23:32:45 +00007214 // FIXME: Unnamed fields can be handled in various different ways, for
7215 // example, unnamed unions inject all members into the struct namespace!
Mike Stump11289f42009-09-09 15:08:12 +00007216
John McCall8cb7bdf2010-06-04 23:28:52 +00007217 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
7218 QualType T = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00007219
Fariborz Jahaniande615832008-04-10 23:32:45 +00007220 if (BitWidth) {
Steve Naroff17b2f5d2009-02-20 17:57:11 +00007221 // 6.7.2.1p3, 6.7.2.1p4
Chris Lattner73bf7b42009-03-05 22:45:59 +00007222 if (VerifyBitField(Loc, II, T, BitWidth)) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007223 D.setInvalidType();
Chris Lattner73bf7b42009-03-05 22:45:59 +00007224 BitWidth = 0;
7225 }
Fariborz Jahaniande615832008-04-10 23:32:45 +00007226 } else {
7227 // Not a bitfield.
Mike Stump11289f42009-09-09 15:08:12 +00007228
Fariborz Jahaniande615832008-04-10 23:32:45 +00007229 // validate II.
Mike Stump11289f42009-09-09 15:08:12 +00007230
Fariborz Jahaniande615832008-04-10 23:32:45 +00007231 }
Fariborz Jahanian0103d672010-04-26 22:07:03 +00007232 if (T->isReferenceType()) {
7233 Diag(Loc, diag::err_ivar_reference_type);
7234 D.setInvalidType();
7235 }
Fariborz Jahaniande615832008-04-10 23:32:45 +00007236 // C99 6.7.2.1p8: A member of a structure or union may have any type other
7237 // than a variably modified type.
Fariborz Jahanian0103d672010-04-26 22:07:03 +00007238 else if (T->isVariablyModifiedType()) {
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +00007239 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007240 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +00007241 }
Mike Stump11289f42009-09-09 15:08:12 +00007242
Ted Kremenek73295fa2008-07-23 18:04:17 +00007243 // Get the visibility (access control) for this ivar.
Mike Stump11289f42009-09-09 15:08:12 +00007244 ObjCIvarDecl::AccessControl ac =
Ted Kremenek73295fa2008-07-23 18:04:17 +00007245 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
7246 : ObjCIvarDecl::None;
Fariborz Jahanian68453832009-06-05 18:16:35 +00007247 // Must set ivar's DeclContext to its enclosing interface.
John McCall48871652010-08-21 09:40:31 +00007248 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(IntfDecl);
Daniel Dunbar229385c2010-04-02 18:29:09 +00007249 ObjCContainerDecl *EnclosingContext;
Mike Stump11289f42009-09-09 15:08:12 +00007250 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian68453832009-06-05 18:16:35 +00007251 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +00007252 if (!LangOpts.ObjCNonFragileABI2) {
Fariborz Jahanian68453832009-06-05 18:16:35 +00007253 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +00007254 EnclosingContext = IMPDecl->getClassInterface();
7255 assert(EnclosingContext && "Implementation has no class interface!");
7256 }
7257 else
7258 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00007259 } else {
7260 if (ObjCCategoryDecl *CDecl =
7261 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
7262 if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) {
7263 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCall48871652010-08-21 09:40:31 +00007264 return 0;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00007265 }
7266 }
Daniel Dunbar229385c2010-04-02 18:29:09 +00007267 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00007268 }
Mike Stump11289f42009-09-09 15:08:12 +00007269
Ted Kremenek73295fa2008-07-23 18:04:17 +00007270 // Construct the decl.
Abramo Bagnaradff19302011-03-08 08:55:46 +00007271 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
7272 DeclStart, Loc, II, T,
John McCallbcd03502009-12-07 02:54:59 +00007273 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump11289f42009-09-09 15:08:12 +00007274
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007275 if (II) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00007276 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall5cebab12009-11-18 07:57:50 +00007277 ForRedeclaration);
Fariborz Jahanian68453832009-06-05 18:16:35 +00007278 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007279 && !isa<TagDecl>(PrevDecl)) {
7280 Diag(Loc, diag::err_duplicate_member) << II;
7281 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
7282 NewID->setInvalidDecl();
7283 }
7284 }
7285
Ted Kremenek73295fa2008-07-23 18:04:17 +00007286 // Process attributes attached to the ivar.
Douglas Gregor758a8692009-06-17 21:51:59 +00007287 ProcessDeclAttributes(S, NewID, D);
Mike Stump11289f42009-09-09 15:08:12 +00007288
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007289 if (D.isInvalidType())
Fariborz Jahaniande615832008-04-10 23:32:45 +00007290 NewID->setInvalidDecl();
Ted Kremenek73295fa2008-07-23 18:04:17 +00007291
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007292 if (II) {
7293 // FIXME: When interfaces are DeclContexts, we'll need to add
7294 // these to the interface.
John McCall48871652010-08-21 09:40:31 +00007295 S->AddDecl(NewID);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007296 IdResolver.AddDecl(NewID);
7297 }
7298
John McCall48871652010-08-21 09:40:31 +00007299 return NewID;
Fariborz Jahaniande615832008-04-10 23:32:45 +00007300}
7301
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00007302/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
7303/// class and class extensions. For every class @interface and class
7304/// extension @interface, if the last ivar is a bitfield of any type,
7305/// then add an implicit `char :0` ivar to the end of that interface.
7306void Sema::ActOnLastBitfield(SourceLocation DeclLoc, Decl *EnclosingDecl,
7307 llvm::SmallVectorImpl<Decl *> &AllIvarDecls) {
7308 if (!LangOpts.ObjCNonFragileABI2 || AllIvarDecls.empty())
7309 return;
7310
7311 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
7312 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
7313
7314 if (!Ivar->isBitField())
7315 return;
7316 uint64_t BitFieldSize =
7317 Ivar->getBitWidth()->EvaluateAsInt(Context).getZExtValue();
7318 if (BitFieldSize == 0)
7319 return;
7320 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl);
7321 if (!ID) {
7322 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
7323 if (!CD->IsClassExtension())
7324 return;
7325 }
7326 // No need to add this to end of @implementation.
7327 else
7328 return;
7329 }
7330 // All conditions are met. Add a new bitfield to the tail end of ivars.
7331 llvm::APInt Zero(Context.getTypeSize(Context.CharTy), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007332 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.CharTy, DeclLoc);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00007333
7334 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(EnclosingDecl),
Abramo Bagnaradff19302011-03-08 08:55:46 +00007335 DeclLoc, DeclLoc, 0,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00007336 Context.CharTy,
7337 Context.CreateTypeSourceInfo(Context.CharTy),
7338 ObjCIvarDecl::Private, BW,
7339 true);
7340 AllIvarDecls.push_back(Ivar);
7341}
7342
Fariborz Jahanian343f7092007-09-29 00:54:24 +00007343void Sema::ActOnFields(Scope* S,
John McCall48871652010-08-21 09:40:31 +00007344 SourceLocation RecLoc, Decl *EnclosingDecl,
7345 Decl **Fields, unsigned NumFields,
Daniel Dunbar15619c72008-10-03 02:03:53 +00007346 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar325601a2008-10-03 17:33:35 +00007347 AttributeList *Attr) {
Steve Naroffdb47ee22007-09-14 22:20:54 +00007348 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump11289f42009-09-09 15:08:12 +00007349
Chris Lattnerd13b8b52009-02-23 22:00:08 +00007350 // If the decl this is being inserted into is invalid, then it may be a
7351 // redeclaration or some other bogus case. Don't try to add fields to it.
7352 if (EnclosingDecl->isInvalidDecl()) {
7353 // FIXME: Deallocate fields?
7354 return;
7355 }
7356
Mike Stump11289f42009-09-09 15:08:12 +00007357
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00007358 // Verify that all the fields are okay.
Chris Lattner82625602007-01-24 02:26:21 +00007359 unsigned NumNamedMembers = 0;
Chris Lattner23b7eb62007-06-15 23:05:46 +00007360 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorf4d33272009-01-07 19:46:03 +00007361
Chris Lattnerd13b8b52009-02-23 22:00:08 +00007362 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00007363 for (unsigned i = 0; i != NumFields; ++i) {
John McCall48871652010-08-21 09:40:31 +00007364 FieldDecl *FD = cast<FieldDecl>(Fields[i]);
Mike Stump11289f42009-09-09 15:08:12 +00007365
Chris Lattner720a0542007-01-25 00:44:24 +00007366 // Get the type for the field.
John McCall424cec92011-01-19 06:33:43 +00007367 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorf4d33272009-01-07 19:46:03 +00007368
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007369 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00007370 // Remember all fields written by the user.
7371 RecFields.push_back(FD);
7372 }
Mike Stump11289f42009-09-09 15:08:12 +00007373
Chris Lattner73bf7b42009-03-05 22:45:59 +00007374 // If the field is already invalid for some reason, don't emit more
7375 // diagnostics about it.
Eli Friedmand0e8de22009-12-07 00:22:08 +00007376 if (FD->isInvalidDecl()) {
7377 EnclosingDecl->setInvalidDecl();
Chris Lattner73bf7b42009-03-05 22:45:59 +00007378 continue;
Eli Friedmand0e8de22009-12-07 00:22:08 +00007379 }
Mike Stump11289f42009-09-09 15:08:12 +00007380
Douglas Gregorac1fb652009-03-24 19:52:54 +00007381 // C99 6.7.2.1p2:
7382 // A structure or union shall not contain a member with
7383 // incomplete or function type (hence, a structure shall not
7384 // contain an instance of itself, but may contain a pointer to
7385 // an instance of itself), except that the last member of a
7386 // structure with more than one named member may have incomplete
7387 // array type; such a structure (and any union containing,
7388 // possibly recursively, a member that is such a structure)
7389 // shall not be a member of a structure or an element of an
7390 // array.
Chris Lattner0fd893e2007-07-31 21:33:24 +00007391 if (FDTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00007392 // Field declared as a function.
Chris Lattner651d42d2008-11-20 06:38:18 +00007393 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007394 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +00007395 FD->setInvalidDecl();
7396 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00007397 continue;
Francois Pichetf657b632010-09-15 00:14:08 +00007398 } else if (FDTy->isIncompleteArrayType() && Record &&
7399 ((i == NumFields - 1 && !Record->isUnion()) ||
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00007400 ((getLangOptions().Microsoft || getLangOptions().CPlusPlus) &&
Francois Pichetf657b632010-09-15 00:14:08 +00007401 (i == NumFields - 1 || Record->isUnion())))) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00007402 // Flexible array member.
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00007403 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichetf657b632010-09-15 00:14:08 +00007404 // It will accept flexible array in union and also
Anders Carlsson0ea10472010-10-17 23:36:12 +00007405 // as the sole element of a struct/class.
Francois Pichetf657b632010-09-15 00:14:08 +00007406 if (getLangOptions().Microsoft) {
7407 if (Record->isUnion())
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00007408 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
Francois Pichetf657b632010-09-15 00:14:08 +00007409 << FD->getDeclName();
7410 else if (NumFields == 1)
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00007411 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
Francois Pichetf657b632010-09-15 00:14:08 +00007412 << FD->getDeclName() << Record->getTagKind();
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00007413 } else if (getLangOptions().CPlusPlus) {
7414 if (Record->isUnion())
7415 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
7416 << FD->getDeclName();
7417 else if (NumFields == 1)
7418 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
7419 << FD->getDeclName() << Record->getTagKind();
7420 } else if (NumNamedMembers < 1) {
Chris Lattner651d42d2008-11-20 06:38:18 +00007421 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007422 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +00007423 FD->setInvalidDecl();
7424 EnclosingDecl->setInvalidDecl();
Chris Lattner82625602007-01-24 02:26:21 +00007425 continue;
7426 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00007427 if (!FD->getType()->isDependentType() &&
7428 !Context.getBaseElementType(FD->getType())->isPODType()) {
7429 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
Fariborz Jahanianb0e28472010-05-26 20:46:24 +00007430 << FD->getDeclName() << FD->getType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00007431 FD->setInvalidDecl();
7432 EnclosingDecl->setInvalidDecl();
7433 continue;
7434 }
Chris Lattner720a0542007-01-25 00:44:24 +00007435 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00007436 if (Record)
7437 Record->setHasFlexibleArrayMember(true);
Douglas Gregorac1fb652009-03-24 19:52:54 +00007438 } else if (!FDTy->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00007439 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregorac1fb652009-03-24 19:52:54 +00007440 diag::err_field_incomplete)) {
7441 // Incomplete type
7442 FD->setInvalidDecl();
7443 EnclosingDecl->setInvalidDecl();
7444 continue;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007445 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Chris Lattner720a0542007-01-25 00:44:24 +00007446 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
7447 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00007448 if (Record && Record->isUnion()) {
Chris Lattner41943152007-01-25 04:52:46 +00007449 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00007450 } else {
7451 // If this is a struct/class and this is not the last element, reject
7452 // it. Note that GCC supports variable sized arrays in the middle of
7453 // structures.
Douglas Gregor3e06dbf2009-03-06 23:41:27 +00007454 if (i != NumFields-1)
7455 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattnerb28fe9e2009-04-25 18:52:45 +00007456 << FD->getDeclName() << FD->getType();
Douglas Gregor3e06dbf2009-03-06 23:41:27 +00007457 else {
7458 // We support flexible arrays at the end of structs in
7459 // other structs as an extension.
7460 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
7461 << FD->getDeclName();
7462 if (Record)
7463 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00007464 }
Chris Lattner720a0542007-01-25 00:44:24 +00007465 }
7466 }
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00007467 if (Record && FDTTy->getDecl()->hasObjectMember())
7468 Record->setHasObjectMember(true);
John McCall8b07ec22010-05-15 11:32:37 +00007469 } else if (FDTy->isObjCObjectType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00007470 /// A field cannot be an Objective-c object
Steve Naroff32606412009-02-20 22:59:16 +00007471 Diag(FD->getLocation(), diag::err_statically_allocated_object);
Fariborz Jahanianecfe4f12007-10-12 22:10:42 +00007472 FD->setInvalidDecl();
7473 EnclosingDecl->setInvalidDecl();
7474 continue;
Mike Stump12b8ce12009-08-04 21:02:39 +00007475 } else if (getLangOptions().ObjC1 &&
7476 getLangOptions().getGCMode() != LangOptions::NonGC &&
7477 Record &&
7478 (FD->getType()->isObjCObjectPointerType() ||
7479 FD->getType().isObjCGCStrong()))
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00007480 Record->setHasObjectMember(true);
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007481 else if (Context.getAsArrayType(FD->getType())) {
7482 QualType BaseType = Context.getBaseElementType(FD->getType());
7483 if (Record && BaseType->isRecordType() &&
7484 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
7485 Record->setHasObjectMember(true);
7486 }
Chris Lattner82625602007-01-24 02:26:21 +00007487 // Keep track of the number of named members.
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007488 if (FD->getIdentifier())
Chris Lattner82625602007-01-24 02:26:21 +00007489 ++NumNamedMembers;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00007490 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00007491
Chris Lattner82625602007-01-24 02:26:21 +00007492 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +00007493 if (Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00007494 bool Completed = false;
7495 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
7496 if (!CXXRecord->isInvalidDecl()) {
7497 // Set access bits correctly on the directly-declared conversions.
7498 UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions();
7499 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end();
7500 I != E; ++I)
7501 Convs->setAccess(I, (*I)->getAccess());
7502
7503 if (!CXXRecord->isDependentType()) {
7504 // Add any implicitly-declared members to this class.
7505 AddImplicitlyDeclaredMembersToClass(CXXRecord);
7506
7507 // If we have virtual base classes, we may end up finding multiple
7508 // final overriders for a given virtual function. Check for this
7509 // problem now.
7510 if (CXXRecord->getNumVBases()) {
7511 CXXFinalOverriderMap FinalOverriders;
7512 CXXRecord->getFinalOverriders(FinalOverriders);
7513
7514 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
7515 MEnd = FinalOverriders.end();
7516 M != MEnd; ++M) {
7517 for (OverridingMethods::iterator SO = M->second.begin(),
7518 SOEnd = M->second.end();
7519 SO != SOEnd; ++SO) {
7520 assert(SO->second.size() > 0 &&
7521 "Virtual function without overridding functions?");
7522 if (SO->second.size() == 1)
7523 continue;
7524
7525 // C++ [class.virtual]p2:
7526 // In a derived class, if a virtual member function of a base
7527 // class subobject has more than one final overrider the
7528 // program is ill-formed.
7529 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
7530 << (NamedDecl *)M->first << Record;
7531 Diag(M->first->getLocation(),
7532 diag::note_overridden_virtual_function);
7533 for (OverridingMethods::overriding_iterator
7534 OM = SO->second.begin(),
7535 OMEnd = SO->second.end();
7536 OM != OMEnd; ++OM)
7537 Diag(OM->Method->getLocation(), diag::note_final_overrider)
7538 << (NamedDecl *)M->first << OM->Method->getParent();
7539
7540 Record->setInvalidDecl();
7541 }
7542 }
7543 CXXRecord->completeDefinition(&FinalOverriders);
7544 Completed = true;
7545 }
7546 }
7547 }
7548 }
7549
7550 if (!Completed)
7551 Record->completeDefinition();
Chris Lattner622c1932008-02-06 00:51:33 +00007552 } else {
Jay Foad7d0479f2009-05-21 09:52:38 +00007553 ObjCIvarDecl **ClsFields =
7554 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian02225532008-12-13 20:28:25 +00007555 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattner22298722009-02-20 21:35:13 +00007556 ID->setLocEnd(RBrac);
Fariborz Jahanian68453832009-06-05 18:16:35 +00007557 // Add ivar's to class's DeclContext.
7558 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
7559 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007560 ID->addDecl(ClsFields[i]);
Fariborz Jahanian68453832009-06-05 18:16:35 +00007561 }
Fariborz Jahaniana599c132008-12-16 01:08:35 +00007562 // Must enforce the rule that ivars in the base classes may not be
7563 // duplicates.
Fariborz Jahanian545643c2010-02-23 23:41:11 +00007564 if (ID->getSuperClass())
7565 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump11289f42009-09-09 15:08:12 +00007566 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattnerd13b8b52009-02-23 22:00:08 +00007567 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007568 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian68453832009-06-05 18:16:35 +00007569 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
7570 // Ivar declared in @implementation never belongs to the implementation.
7571 // Only it is in implementation's lexical context.
Douglas Gregor5f662052009-04-23 03:23:08 +00007572 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian95b60762007-10-31 18:48:14 +00007573 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +00007574 } else if (ObjCCategoryDecl *CDecl =
7575 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00007576 // case of ivars in class extension; all other cases have been
7577 // reported as errors elsewhere.
7578 // FIXME. Class extension does not have a LocEnd field.
7579 // CDecl->setLocEnd(RBrac);
7580 // Add ivar's to class extension's DeclContext.
7581 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
7582 ClsFields[i]->setLexicalDeclContext(CDecl);
7583 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +00007584 }
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +00007585 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +00007586 }
Daniel Dunbar325601a2008-10-03 17:33:35 +00007587
7588 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00007589 ProcessDeclAttributeList(S, Record, Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00007590
7591 // If there's a #pragma GCC visibility in scope, and this isn't a subclass,
7592 // set the visibility of this record.
7593 if (Record && !Record->getDeclContext()->isRecord())
7594 AddPushedVisibilityAttribute(Record);
Chris Lattner1300fb92007-01-23 23:42:53 +00007595}
7596
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007597/// \brief Determine whether the given integral value is representable within
7598/// the given type T.
7599static bool isRepresentableIntegerValue(ASTContext &Context,
7600 llvm::APSInt &Value,
7601 QualType T) {
Douglas Gregor6972a622010-06-16 00:35:25 +00007602 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregorc1cf8142010-04-15 15:53:31 +00007603 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007604
Douglas Gregor0bf31402010-10-08 23:50:27 +00007605 if (Value.isUnsigned() || Value.isNonNegative()) {
7606 if (T->isSignedIntegerType())
7607 --BitWidth;
7608 return Value.getActiveBits() <= BitWidth;
7609 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007610 return Value.getMinSignedBits() <= BitWidth;
7611}
7612
7613// \brief Given an integral type, return the next larger integral type
7614// (or a NULL type of no such type exists).
7615static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
7616 // FIXME: Int128/UInt128 support, which also needs to be introduced into
7617 // enum checking below.
Douglas Gregor6972a622010-06-16 00:35:25 +00007618 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007619 const unsigned NumTypes = 4;
7620 QualType SignedIntegralTypes[NumTypes] = {
7621 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
7622 };
7623 QualType UnsignedIntegralTypes[NumTypes] = {
7624 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
7625 Context.UnsignedLongLongTy
7626 };
7627
7628 unsigned BitWidth = Context.getTypeSize(T);
7629 QualType *Types = T->isSignedIntegerType()? SignedIntegralTypes
7630 : UnsignedIntegralTypes;
7631 for (unsigned I = 0; I != NumTypes; ++I)
7632 if (Context.getTypeSize(Types[I]) > BitWidth)
7633 return Types[I];
7634
7635 return QualType();
7636}
7637
Douglas Gregor954f6b272009-03-17 19:05:46 +00007638EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
7639 EnumConstantDecl *LastEnumConst,
7640 SourceLocation IdLoc,
7641 IdentifierInfo *Id,
John McCallb268a282010-08-23 23:25:46 +00007642 Expr *Val) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007643 unsigned IntWidth = Context.Target.getIntWidth();
7644 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor954f6b272009-03-17 19:05:46 +00007645 QualType EltTy;
Douglas Gregor2b988fd2010-12-16 00:24:44 +00007646
7647 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
7648 Val = 0;
7649
Douglas Gregorb2186fe2009-11-06 00:03:12 +00007650 if (Val) {
Douglas Gregordc70c3a2010-03-02 17:53:14 +00007651 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregorb2186fe2009-11-06 00:03:12 +00007652 EltTy = Context.DependentTy;
7653 else {
Douglas Gregorb2186fe2009-11-06 00:03:12 +00007654 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
7655 SourceLocation ExpLoc;
Douglas Gregordc70c3a2010-03-02 17:53:14 +00007656 if (!Val->isValueDependent() &&
7657 VerifyIntegerConstantExpression(Val, &EnumVal)) {
Douglas Gregorb2186fe2009-11-06 00:03:12 +00007658 Val = 0;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007659 } else {
7660 if (!getLangOptions().CPlusPlus) {
7661 // C99 6.7.2.2p2:
7662 // The expression that defines the value of an enumeration constant
7663 // shall be an integer constant expression that has a value
7664 // representable as an int.
7665
7666 // Complain if the value is not representable in an int.
7667 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
7668 Diag(IdLoc, diag::ext_enum_value_not_int)
7669 << EnumVal.toString(10) << Val->getSourceRange()
Douglas Gregorc0b8c812010-02-17 22:40:11 +00007670 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007671 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
7672 // Force the type of the expression to 'int'.
John McCalle3027922010-08-25 11:45:40 +00007673 ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast);
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007674 }
7675 }
7676
Douglas Gregor0bf31402010-10-08 23:50:27 +00007677 if (Enum->isFixed()) {
7678 EltTy = Enum->getIntegerType();
7679
7680 // C++0x [dcl.enum]p5:
7681 // ... if the initializing value of an enumerator cannot be
7682 // represented by the underlying type, the program is ill-formed.
Francois Picheta3108062010-10-18 15:01:13 +00007683 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
7684 if (getLangOptions().Microsoft) {
7685 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
7686 ImpCastExprToType(Val, EltTy, CK_IntegralCast);
7687 } else
7688 Diag(IdLoc, diag::err_enumerator_too_large)
7689 << EltTy;
7690 } else
Douglas Gregor0bf31402010-10-08 23:50:27 +00007691 ImpCastExprToType(Val, EltTy, CK_IntegralCast);
7692 }
7693 else {
7694 // C++0x [dcl.enum]p5:
7695 // If the underlying type is not fixed, the type of each enumerator
7696 // is the type of its initializing value:
7697 // - If an initializer is specified for an enumerator, the
7698 // initializing value has the same type as the expression.
7699 EltTy = Val->getType();
7700 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +00007701 }
Douglas Gregor954f6b272009-03-17 19:05:46 +00007702 }
7703 }
Mike Stump11289f42009-09-09 15:08:12 +00007704
Douglas Gregor954f6b272009-03-17 19:05:46 +00007705 if (!Val) {
Eli Friedmand0e60972009-12-11 01:34:50 +00007706 if (Enum->isDependentType())
7707 EltTy = Context.DependentTy;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007708 else if (!LastEnumConst) {
7709 // C++0x [dcl.enum]p5:
7710 // If the underlying type is not fixed, the type of each enumerator
7711 // is the type of its initializing value:
7712 // - If no initializer is specified for the first enumerator, the
7713 // initializing value has an unspecified integral type.
7714 //
7715 // GCC uses 'int' for its unspecified integral type, as does
7716 // C99 6.7.2.2p3.
Douglas Gregor0bf31402010-10-08 23:50:27 +00007717 if (Enum->isFixed()) {
7718 EltTy = Enum->getIntegerType();
7719 }
7720 else {
7721 EltTy = Context.IntTy;
7722 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007723 } else {
Douglas Gregor954f6b272009-03-17 19:05:46 +00007724 // Assign the last value + 1.
7725 EnumVal = LastEnumConst->getInitVal();
7726 ++EnumVal;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007727 EltTy = LastEnumConst->getType();
Douglas Gregor954f6b272009-03-17 19:05:46 +00007728
7729 // Check for overflow on increment.
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007730 if (EnumVal < LastEnumConst->getInitVal()) {
7731 // C++0x [dcl.enum]p5:
7732 // If the underlying type is not fixed, the type of each enumerator
7733 // is the type of its initializing value:
7734 //
7735 // - Otherwise the type of the initializing value is the same as
7736 // the type of the initializing value of the preceding enumerator
7737 // unless the incremented value is not representable in that type,
7738 // in which case the type is an unspecified integral type
7739 // sufficient to contain the incremented value. If no such type
7740 // exists, the program is ill-formed.
7741 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor0bf31402010-10-08 23:50:27 +00007742 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007743 // There is no integral type larger enough to represent this
7744 // value. Complain, then allow the value to wrap around.
7745 EnumVal = LastEnumConst->getInitVal();
Jay Foad6d4db0c2010-12-07 08:25:34 +00007746 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor0bf31402010-10-08 23:50:27 +00007747 ++EnumVal;
7748 if (Enum->isFixed())
7749 // When the underlying type is fixed, this is ill-formed.
7750 Diag(IdLoc, diag::err_enumerator_wrapped)
7751 << EnumVal.toString(10)
7752 << EltTy;
7753 else
7754 Diag(IdLoc, diag::warn_enumerator_too_large)
7755 << EnumVal.toString(10);
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007756 } else {
7757 EltTy = T;
7758 }
7759
7760 // Retrieve the last enumerator's value, extent that type to the
7761 // type that is supposed to be large enough to represent the incremented
7762 // value, then increment.
7763 EnumVal = LastEnumConst->getInitVal();
7764 EnumVal.setIsSigned(EltTy->isSignedIntegerType());
Jay Foad6d4db0c2010-12-07 08:25:34 +00007765 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007766 ++EnumVal;
7767
7768 // If we're not in C++, diagnose the overflow of enumerator values,
7769 // which in C99 means that the enumerator value is not representable in
7770 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
7771 // permits enumerator values that are representable in some larger
7772 // integral type.
7773 if (!getLangOptions().CPlusPlus && !T.isNull())
7774 Diag(IdLoc, diag::warn_enum_value_overflow);
7775 } else if (!getLangOptions().CPlusPlus &&
7776 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
7777 // Enforce C99 6.7.2.2p2 even when we compute the next value.
7778 Diag(IdLoc, diag::ext_enum_value_not_int)
7779 << EnumVal.toString(10) << 1;
7780 }
Douglas Gregor954f6b272009-03-17 19:05:46 +00007781 }
7782 }
Mike Stump11289f42009-09-09 15:08:12 +00007783
Douglas Gregordc70c3a2010-03-02 17:53:14 +00007784 if (!EltTy->isDependentType()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007785 // Make the enumerator value match the signedness and size of the
7786 // enumerator's type.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007787 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007788 EnumVal.setIsSigned(EltTy->isSignedIntegerType());
7789 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +00007790
Douglas Gregor954f6b272009-03-17 19:05:46 +00007791 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump11289f42009-09-09 15:08:12 +00007792 Val, EnumVal);
Douglas Gregor954f6b272009-03-17 19:05:46 +00007793}
7794
7795
John McCall811a0f52010-10-22 23:36:17 +00007796Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
7797 SourceLocation IdLoc, IdentifierInfo *Id,
7798 AttributeList *Attr,
7799 SourceLocation EqualLoc, ExprTy *val) {
John McCall48871652010-08-21 09:40:31 +00007800 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Chris Lattner4ef40012007-06-11 01:28:17 +00007801 EnumConstantDecl *LastEnumConst =
John McCall48871652010-08-21 09:40:31 +00007802 cast_or_null<EnumConstantDecl>(lastEnumConst);
Chris Lattner4ef40012007-06-11 01:28:17 +00007803 Expr *Val = static_cast<Expr*>(val);
Chris Lattner8116d1b2007-01-25 22:38:29 +00007804
Chris Lattner1a76a3c2007-08-26 06:24:45 +00007805 // The scope passed in may not be a decl scope. Zip up the scope tree until
7806 // we find one that is.
Douglas Gregor45a33ec2009-01-12 18:45:55 +00007807 S = getNonFieldDeclScope(S);
Mike Stump11289f42009-09-09 15:08:12 +00007808
Chris Lattner8116d1b2007-01-25 22:38:29 +00007809 // Verify that there isn't already something declared with this name in this
7810 // scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00007811 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregor5204248f2010-01-19 06:06:57 +00007812 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +00007813 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00007814 // Maybe we will complain about the shadowed template parameter.
7815 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
7816 // Just pretend that we didn't see the previous declaration.
7817 PrevDecl = 0;
7818 }
7819
7820 if (PrevDecl) {
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +00007821 // When in C++, we may get a TagDecl with the same name; in this case the
7822 // enum constant will 'hide' the tag.
7823 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
7824 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis5b144d52008-09-09 21:18:04 +00007825 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +00007826 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner4bd8dd82008-11-19 08:23:25 +00007827 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner8116d1b2007-01-25 22:38:29 +00007828 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +00007829 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner0369c572008-11-23 23:12:31 +00007830 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00007831 return 0;
Chris Lattner8116d1b2007-01-25 22:38:29 +00007832 }
7833 }
Chris Lattner4ef40012007-06-11 01:28:17 +00007834
Douglas Gregor36c22a22010-10-15 13:21:21 +00007835 // C++ [class.mem]p13:
7836 // If T is the name of a class, then each of the following shall have a
7837 // name different from T:
7838 // - every enumerator of every member of class T that is an enumerated
7839 // type
7840 if (CXXRecordDecl *Record
7841 = dyn_cast<CXXRecordDecl>(
7842 TheEnumDecl->getDeclContext()->getRedeclContext()))
7843 if (Record->getIdentifier() && Record->getIdentifier() == Id)
7844 Diag(IdLoc, diag::err_member_name_of_class) << Id;
7845
John McCall811a0f52010-10-22 23:36:17 +00007846 EnumConstantDecl *New =
7847 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner0515e4b2007-08-27 21:16:18 +00007848
John McCall553c0792010-01-23 00:46:32 +00007849 if (New) {
John McCall811a0f52010-10-22 23:36:17 +00007850 // Process attributes.
7851 if (Attr) ProcessDeclAttributeList(S, New, Attr);
7852
7853 // Register this decl in the current scope stack.
John McCall553c0792010-01-23 00:46:32 +00007854 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor954f6b272009-03-17 19:05:46 +00007855 PushOnScopeChains(New, S);
John McCall553c0792010-01-23 00:46:32 +00007856 }
Douglas Gregor2f521192008-12-17 02:04:30 +00007857
John McCall48871652010-08-21 09:40:31 +00007858 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +00007859}
7860
Mike Stump6814d1c2009-05-16 07:06:02 +00007861void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCall48871652010-08-21 09:40:31 +00007862 SourceLocation RBraceLoc, Decl *EnumDeclX,
7863 Decl **Elements, unsigned NumElements,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00007864 Scope *S, AttributeList *Attr) {
John McCall48871652010-08-21 09:40:31 +00007865 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor07665a62009-01-05 19:45:36 +00007866 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00007867
7868 if (Attr)
7869 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump11289f42009-09-09 15:08:12 +00007870
Eli Friedmand0e60972009-12-11 01:34:50 +00007871 if (Enum->isDependentType()) {
7872 for (unsigned i = 0; i != NumElements; ++i) {
7873 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +00007874 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmand0e60972009-12-11 01:34:50 +00007875 if (!ECD) continue;
7876
7877 ECD->setType(EnumType);
7878 }
7879
John McCall9aa35be2010-05-06 08:49:23 +00007880 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmand0e60972009-12-11 01:34:50 +00007881 return;
7882 }
7883
Chris Lattner67933c02007-08-28 05:10:31 +00007884 // TODO: If the result value doesn't fit in an int, it must be a long or long
7885 // long value. ISO C does not support this, but GCC does as an extension,
7886 // emit a warning.
Chris Lattner37e05872008-03-05 18:54:05 +00007887 unsigned IntWidth = Context.Target.getIntWidth();
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00007888 unsigned CharWidth = Context.Target.getCharWidth();
7889 unsigned ShortWidth = Context.Target.getShortWidth();
Mike Stump11289f42009-09-09 15:08:12 +00007890
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007891 // Verify that all the values are okay, compute the size of the values, and
7892 // reverse the list.
7893 unsigned NumNegativeBits = 0;
7894 unsigned NumPositiveBits = 0;
Mike Stump11289f42009-09-09 15:08:12 +00007895
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007896 // Keep track of whether all elements have type int.
7897 bool AllElementsInt = true;
Mike Stump11289f42009-09-09 15:08:12 +00007898
Chris Lattnerc1915e22007-01-25 07:29:02 +00007899 for (unsigned i = 0; i != NumElements; ++i) {
7900 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +00007901 cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerc1915e22007-01-25 07:29:02 +00007902 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump11289f42009-09-09 15:08:12 +00007903
Chris Lattnerbf478cb2007-08-28 05:27:00 +00007904 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump11289f42009-09-09 15:08:12 +00007905
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007906 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +00007907 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +00007908 NumPositiveBits = std::max(NumPositiveBits,
7909 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007910 else
Chris Lattner49f980c2008-01-14 21:47:29 +00007911 NumNegativeBits = std::max(NumNegativeBits,
7912 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +00007913
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007914 // Keep track of whether every enum element has type int (very commmon).
7915 if (AllElementsInt)
Mike Stump11289f42009-09-09 15:08:12 +00007916 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattnerc1915e22007-01-25 07:29:02 +00007917 }
Mike Stump11289f42009-09-09 15:08:12 +00007918
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007919 // Figure out the type that should be used for this enum.
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007920 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +00007921 unsigned BestWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00007922
John McCall56774992009-12-09 09:09:27 +00007923 // C++0x N3000 [conv.prom]p3:
7924 // An rvalue of an unscoped enumeration type whose underlying
7925 // type is not fixed can be converted to an rvalue of the first
7926 // of the following types that can represent all the values of
7927 // the enumeration: int, unsigned int, long int, unsigned long
7928 // int, long long int, or unsigned long long int.
7929 // C99 6.4.4.3p2:
7930 // An identifier declared as an enumeration constant has type int.
7931 // The C99 rule is modified by a gcc extension
7932 QualType BestPromotionType;
7933
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00007934 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
Argyrios Kyrtzidis74825bc2010-10-08 00:25:19 +00007935 // -fshort-enums is the equivalent to specifying the packed attribute on all
7936 // enum definitions.
7937 if (LangOpts.ShortEnums)
7938 Packed = true;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00007939
Douglas Gregor0bf31402010-10-08 23:50:27 +00007940 if (Enum->isFixed()) {
7941 BestType = BestPromotionType = Enum->getIntegerType();
Duncan Sands38b918c2010-10-12 14:07:59 +00007942 // We don't need to set BestWidth, because BestType is going to be the type
7943 // of the enumerators, but we do anyway because otherwise some compilers
7944 // warn that it might be used uninitialized.
7945 BestWidth = CharWidth;
Douglas Gregor0bf31402010-10-08 23:50:27 +00007946 }
7947 else if (NumNegativeBits) {
Mike Stump11289f42009-09-09 15:08:12 +00007948 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007949 // int/long/longlong) that fits.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00007950 // If it's packed, check also if it fits a char or a short.
7951 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall56774992009-12-09 09:09:27 +00007952 BestType = Context.SignedCharTy;
7953 BestWidth = CharWidth;
Mike Stump11289f42009-09-09 15:08:12 +00007954 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00007955 NumPositiveBits < ShortWidth) {
John McCall56774992009-12-09 09:09:27 +00007956 BestType = Context.ShortTy;
7957 BestWidth = ShortWidth;
7958 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007959 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00007960 BestWidth = IntWidth;
7961 } else {
Chris Lattner37e05872008-03-05 18:54:05 +00007962 BestWidth = Context.Target.getLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +00007963
John McCall56774992009-12-09 09:09:27 +00007964 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007965 BestType = Context.LongTy;
John McCall56774992009-12-09 09:09:27 +00007966 } else {
Chris Lattner37e05872008-03-05 18:54:05 +00007967 BestWidth = Context.Target.getLongLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +00007968
Chris Lattner3a370bf2007-08-29 17:31:48 +00007969 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007970 Diag(Enum->getLocation(), diag::warn_enum_too_large);
7971 BestType = Context.LongLongTy;
7972 }
7973 }
John McCall56774992009-12-09 09:09:27 +00007974 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007975 } else {
Douglas Gregora71cc152010-02-02 20:10:50 +00007976 // If there is no negative value, figure out the smallest type that fits
7977 // all of the enumerator values.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00007978 // If it's packed, check also if it fits a char or a short.
7979 if (Packed && NumPositiveBits <= CharWidth) {
John McCall56774992009-12-09 09:09:27 +00007980 BestType = Context.UnsignedCharTy;
7981 BestPromotionType = Context.IntTy;
7982 BestWidth = CharWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00007983 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall56774992009-12-09 09:09:27 +00007984 BestType = Context.UnsignedShortTy;
7985 BestPromotionType = Context.IntTy;
7986 BestWidth = ShortWidth;
7987 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007988 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00007989 BestWidth = IntWidth;
Douglas Gregora71cc152010-02-02 20:10:50 +00007990 BestPromotionType
7991 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
7992 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00007993 } else if (NumPositiveBits <=
Chris Lattner37e05872008-03-05 18:54:05 +00007994 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007995 BestType = Context.UnsignedLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +00007996 BestPromotionType
7997 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
7998 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner37e05872008-03-05 18:54:05 +00007999 } else {
8000 BestWidth = Context.Target.getLongLongWidth();
Chris Lattner3a370bf2007-08-29 17:31:48 +00008001 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008002 "How could an initializer get larger than ULL?");
8003 BestType = Context.UnsignedLongLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +00008004 BestPromotionType
8005 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
8006 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008007 }
8008 }
Mike Stump11289f42009-09-09 15:08:12 +00008009
Chris Lattner3a370bf2007-08-29 17:31:48 +00008010 // Loop over all of the enumerator constants, changing their types to match
8011 // the type of the enum if needed.
8012 for (unsigned i = 0; i != NumElements; ++i) {
John McCall48871652010-08-21 09:40:31 +00008013 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattner3a370bf2007-08-29 17:31:48 +00008014 if (!ECD) continue; // Already issued a diagnostic.
8015
8016 // Standard C says the enumerators have int type, but we allow, as an
8017 // extension, the enumerators to be larger than int size. If each
8018 // enumerator value fits in an int, type it as an int, otherwise type it the
8019 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
8020 // that X has type 'int', not 'unsigned'.
Chris Lattner3a370bf2007-08-29 17:31:48 +00008021
8022 // Determine whether the value fits into an int.
8023 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattner3a370bf2007-08-29 17:31:48 +00008024
8025 // If it fits into an integer type, force it. Otherwise force it to match
8026 // the enum decl type.
8027 QualType NewTy;
8028 unsigned NewWidth;
8029 bool NewSign;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008030 if (!getLangOptions().CPlusPlus &&
8031 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattner3a370bf2007-08-29 17:31:48 +00008032 NewTy = Context.IntTy;
8033 NewWidth = IntWidth;
8034 NewSign = true;
8035 } else if (ECD->getType() == BestType) {
8036 // Already the right type!
Douglas Gregor1d248c52008-12-12 02:00:36 +00008037 if (getLangOptions().CPlusPlus)
8038 // C++ [dcl.enum]p4: Following the closing brace of an
8039 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +00008040 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +00008041 ECD->setType(EnumType);
Chris Lattner3a370bf2007-08-29 17:31:48 +00008042 continue;
8043 } else {
8044 NewTy = BestType;
8045 NewWidth = BestWidth;
8046 NewSign = BestType->isSignedIntegerType();
8047 }
8048
8049 // Adjust the APSInt value.
Jay Foad6d4db0c2010-12-07 08:25:34 +00008050 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattner3a370bf2007-08-29 17:31:48 +00008051 InitVal.setIsSigned(NewSign);
8052 ECD->setInitVal(InitVal);
Mike Stump11289f42009-09-09 15:08:12 +00008053
Chris Lattner3a370bf2007-08-29 17:31:48 +00008054 // Adjust the Expr initializer and type.
Abramo Bagnara77815432010-12-17 15:49:53 +00008055 if (ECD->getInitExpr() &&
8056 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallcf142162010-08-07 06:22:56 +00008057 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCalle3027922010-08-25 11:45:40 +00008058 CK_IntegralCast,
John McCallcf142162010-08-07 06:22:56 +00008059 ECD->getInitExpr(),
8060 /*base paths*/ 0,
John McCall2536c6d2010-08-25 10:28:54 +00008061 VK_RValue));
Douglas Gregor1d248c52008-12-12 02:00:36 +00008062 if (getLangOptions().CPlusPlus)
8063 // C++ [dcl.enum]p4: Following the closing brace of an
8064 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +00008065 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +00008066 ECD->setType(EnumType);
8067 else
8068 ECD->setType(NewTy);
Chris Lattner3a370bf2007-08-29 17:31:48 +00008069 }
Mike Stump11289f42009-09-09 15:08:12 +00008070
John McCall9aa35be2010-05-06 08:49:23 +00008071 Enum->completeDefinition(BestType, BestPromotionType,
8072 NumPositiveBits, NumNegativeBits);
Chris Lattnerc1915e22007-01-25 07:29:02 +00008073}
Chris Lattner1300fb92007-01-23 23:42:53 +00008074
Abramo Bagnara348823a2011-03-03 14:20:18 +00008075Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
8076 SourceLocation StartLoc,
8077 SourceLocation EndLoc) {
John McCallb268a282010-08-23 23:25:46 +00008078 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redlc675bab2008-12-13 16:23:55 +00008079
Douglas Gregor278f52e2009-05-30 00:08:05 +00008080 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara348823a2011-03-03 14:20:18 +00008081 AsmString, StartLoc,
8082 EndLoc);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008083 CurContext->addDecl(New);
John McCall48871652010-08-21 09:40:31 +00008084 return New;
Anders Carlsson5c6c0592008-02-08 00:33:21 +00008085}
Eli Friedman5ed51982009-06-05 02:44:36 +00008086
8087void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
8088 SourceLocation PragmaLoc,
8089 SourceLocation NameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00008090 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedman5ed51982009-06-05 02:44:36 +00008091
Eli Friedman5ed51982009-06-05 02:44:36 +00008092 if (PrevDecl) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00008093 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
Ryan Flynn7d470f32009-07-30 03:15:39 +00008094 } else {
8095 (void)WeakUndeclaredIdentifiers.insert(
8096 std::pair<IdentifierInfo*,WeakInfo>
8097 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedman5ed51982009-06-05 02:44:36 +00008098 }
Eli Friedman5ed51982009-06-05 02:44:36 +00008099}
8100
8101void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
8102 IdentifierInfo* AliasName,
8103 SourceLocation PragmaLoc,
8104 SourceLocation NameLoc,
8105 SourceLocation AliasNameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00008106 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
8107 LookupOrdinaryName);
Ryan Flynn7d470f32009-07-30 03:15:39 +00008108 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedman5ed51982009-06-05 02:44:36 +00008109
Eli Friedman5ed51982009-06-05 02:44:36 +00008110 if (PrevDecl) {
Ryan Flynn7d470f32009-07-30 03:15:39 +00008111 if (!PrevDecl->hasAttr<AliasAttr>())
8112 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynnd963a492009-07-31 02:52:19 +00008113 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynn7d470f32009-07-30 03:15:39 +00008114 } else {
8115 (void)WeakUndeclaredIdentifiers.insert(
8116 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedman5ed51982009-06-05 02:44:36 +00008117 }
Eli Friedman5ed51982009-06-05 02:44:36 +00008118}