blob: c9678644cb4326b72dbfa9d314f34da48b5dd7c7 [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) {
Daniel Dunbar334b2132011-03-09 23:24:34 +00004086 if (CheckFunctionTemplateSpecialization(NewFD,
4087 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
4088 Previous))
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004089 NewFD->setInvalidDecl();
4090 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
4091 if (CheckMemberSpecialization(NewFD, Previous))
4092 NewFD->setInvalidDecl();
4093 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004094
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004095 // Perform semantic checking on the function declaration.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004096 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization,
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004097 Redeclaration);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004098
4099 assert((NewFD->isInvalidDecl() || !Redeclaration ||
4100 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
4101 "previous declaration set still overloaded");
4102
4103 NamedDecl *PrincipalDecl = (FunctionTemplate
4104 ? cast<NamedDecl>(FunctionTemplate)
4105 : NewFD);
4106
4107 if (isFriend && Redeclaration) {
4108 AccessSpecifier Access = AS_public;
4109 if (!NewFD->isInvalidDecl())
4110 Access = NewFD->getPreviousDeclaration()->getAccess();
4111
4112 NewFD->setAccess(Access);
4113 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
4114
4115 PrincipalDecl->setObjectOfFriendDecl(true);
4116 }
4117
4118 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
4119 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4120 PrincipalDecl->setNonMemberOperator();
4121
4122 // If we have a function template, check the template parameter
4123 // list. This will check and merge default template arguments.
4124 if (FunctionTemplate) {
4125 FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration();
4126 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
4127 PrevTemplate? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregora99fb4c2011-02-04 04:20:44 +00004128 D.getDeclSpec().isFriendSpecified()
4129 ? (IsFunctionDefinition
4130 ? TPC_FriendFunctionTemplateDefinition
4131 : TPC_FriendFunctionTemplate)
4132 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor4d5c2972011-02-04 12:22:53 +00004133 DC && DC->isRecord() &&
4134 DC->isDependentContext())
Douglas Gregora99fb4c2011-02-04 04:20:44 +00004135 ? TPC_ClassTemplateMember
4136 : TPC_FunctionTemplate);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004137 }
4138
4139 if (NewFD->isInvalidDecl()) {
4140 // Ignore all the rest of this.
4141 } else if (!Redeclaration) {
4142 // Fake up an access specifier if it's supposed to be a class member.
4143 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
4144 NewFD->setAccess(AS_public);
4145
4146 // Qualified decls generally require a previous declaration.
4147 if (D.getCXXScopeSpec().isSet()) {
4148 // ...with the major exception of templated-scope or
4149 // dependent-scope friend declarations.
4150
4151 // TODO: we currently also suppress this check in dependent
4152 // contexts because (1) the parameter depth will be off when
4153 // matching friend templates and (2) we might actually be
4154 // selecting a friend based on a dependent factor. But there
4155 // are situations where these conditions don't apply and we
4156 // can actually do this check immediately.
4157 if (isFriend &&
4158 (NumMatchedTemplateParamLists ||
4159 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
4160 CurContext->isDependentContext())) {
4161 // ignore these
4162 } else {
4163 // The user tried to provide an out-of-line definition for a
4164 // function that is a member of a class or namespace, but there
4165 // was no such member function declared (C++ [class.mfct]p2,
4166 // C++ [namespace.memdef]p2). For example:
4167 //
4168 // class X {
4169 // void f() const;
4170 // };
4171 //
4172 // void X::f() { } // ill-formed
4173 //
4174 // Complain about this problem, and attempt to suggest close
4175 // matches (e.g., those that differ only in cv-qualifiers and
4176 // whether the parameter types are references).
4177 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
4178 << Name << DC << D.getCXXScopeSpec().getRange();
4179 NewFD->setInvalidDecl();
4180
4181 DiagnoseInvalidRedeclaration(*this, NewFD);
4182 }
4183
4184 // Unqualified local friend declarations are required to resolve
4185 // to something.
4186 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
4187 Diag(D.getIdentifierLoc(), diag::err_no_matching_local_friend);
4188 NewFD->setInvalidDecl();
4189 DiagnoseInvalidRedeclaration(*this, NewFD);
4190 }
4191
4192 } else if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
4193 !isFriend && !isFunctionTemplateSpecialization &&
4194 !isExplicitSpecialization) {
4195 // An out-of-line member function declaration must also be a
4196 // definition (C++ [dcl.meaning]p1).
4197 // Note that this is not the case for explicit specializations of
4198 // function templates or member functions of class templates, per
4199 // C++ [temp.expl.spec]p2. We also allow these declarations as an extension
4200 // for compatibility with old SWIG code which likes to generate them.
4201 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
4202 << D.getCXXScopeSpec().getRange();
4203 }
4204 }
4205
4206
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004207 // Handle attributes. We need to have merged decls when handling attributes
4208 // (for example to check for conflicts, etc).
4209 // FIXME: This needs to happen before we merge declarations. Then,
4210 // let attribute merging cope with attribute conflicts.
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004211 ProcessDeclAttributes(S, NewFD, D,
4212 /*NonInheritable=*/false, /*Inheritable=*/true);
Ryan Flynne5dc8592009-07-25 22:29:44 +00004213
4214 // attributes declared post-definition are currently ignored
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004215 // FIXME: This should happen during attribute merging
John McCall1f82f242009-11-18 22:49:29 +00004216 if (Redeclaration && Previous.isSingleResult()) {
4217 const FunctionDecl *Def;
4218 FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00004219 if (PrevFD && PrevFD->hasBody(Def) && D.hasAttributes()) {
Ryan Flynne5dc8592009-07-25 22:29:44 +00004220 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
4221 Diag(Def->getLocation(), diag::note_previous_definition);
4222 }
4223 }
4224
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004225 AddKnownFunctionAttributes(NewFD);
4226
Douglas Gregor72609052010-08-06 13:50:58 +00004227 if (NewFD->hasAttr<OverloadableAttr>() &&
4228 !NewFD->getType()->getAs<FunctionProtoType>()) {
4229 Diag(NewFD->getLocation(),
4230 diag::err_attribute_overloadable_no_prototype)
4231 << NewFD;
4232
4233 // Turn this into a variadic function with no parameters.
4234 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
John McCalldb40c7f2010-12-14 08:05:40 +00004235 FunctionProtoType::ExtProtoInfo EPI;
4236 EPI.Variadic = true;
4237 EPI.ExtInfo = FT->getExtInfo();
4238
4239 QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI);
Douglas Gregor72609052010-08-06 13:50:58 +00004240 NewFD->setType(R);
4241 }
4242
Eli Friedman570024a2010-08-05 06:57:20 +00004243 // If there's a #pragma GCC visibility in scope, and this isn't a class
4244 // member, set the visibility of this function.
4245 if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
4246 AddPushedVisibilityAttribute(NewFD);
4247
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004248 // If this is a locally-scoped extern C function, update the
4249 // map of such names.
Douglas Gregor16618f22009-09-12 00:17:51 +00004250 if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004251 && !NewFD->isInvalidDecl())
John McCall1f82f242009-11-18 22:49:29 +00004252 RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004253
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00004254 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraea947882011-03-08 16:41:52 +00004255 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00004256
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004257 if (getLangOptions().CPlusPlus) {
4258 if (FunctionTemplate) {
4259 if (NewFD->isInvalidDecl())
4260 FunctionTemplate->setInvalidDecl();
4261 return FunctionTemplate;
4262 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004263 }
Mike Stump11289f42009-09-09 15:08:12 +00004264
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004265 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004266
4267 if (getLangOptions().CUDA)
4268 if (IdentifierInfo *II = NewFD->getIdentifier())
4269 if (!NewFD->isInvalidDecl() &&
4270 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
4271 if (II->isStr("cudaConfigureCall")) {
4272 if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
4273 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
4274
4275 Context.setcudaConfigureCallDecl(NewFD);
4276 }
4277 }
4278
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004279 return NewFD;
4280}
4281
4282/// \brief Perform semantic checking of a new function declaration.
4283///
4284/// Performs semantic analysis of the new function declaration
4285/// NewFD. This routine performs all semantic checking that does not
4286/// require the actual declarator involved in the declaration, and is
4287/// used both for the declaration of functions as they are parsed
4288/// (called via ActOnDeclarator) and for the declaration of functions
4289/// that have been instantiated via C++ template instantiation (called
4290/// via InstantiateDecl).
4291///
Douglas Gregorcf915552009-10-13 16:30:37 +00004292/// \param IsExplicitSpecialiation whether this new function declaration is
4293/// an explicit specialization of the previous declaration.
4294///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004295/// This sets NewFD->isInvalidDecl() to true if there was an error.
John McCall84d87672009-12-10 09:41:52 +00004296void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall1f82f242009-11-18 22:49:29 +00004297 LookupResult &Previous,
Douglas Gregorcf915552009-10-13 16:30:37 +00004298 bool IsExplicitSpecialization,
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004299 bool &Redeclaration) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004300 // If NewFD is already known erroneous, don't do any of this checking.
John McCall12d53da2010-08-12 00:57:17 +00004301 if (NewFD->isInvalidDecl()) {
4302 // If this is a class member, mark the class invalid immediately.
4303 // This avoids some consistency errors later.
4304 if (isa<CXXMethodDecl>(NewFD))
4305 cast<CXXMethodDecl>(NewFD)->getParent()->setInvalidDecl();
4306
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004307 return;
John McCall12d53da2010-08-12 00:57:17 +00004308 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004309
Eli Friedman54135832009-05-16 12:15:55 +00004310 if (NewFD->getResultType()->isVariablyModifiedType()) {
4311 // Functions returning a variably modified type violate C99 6.7.5.2p2
4312 // because all functions have linkage.
4313 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
4314 return NewFD->setInvalidDecl();
4315 }
4316
Douglas Gregor16618f22009-09-12 00:17:51 +00004317 if (NewFD->isMain())
4318 CheckMain(NewFD);
John McCalld9baf6a2009-07-24 03:03:21 +00004319
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004320 // Check for a previous declaration of this name.
John McCall1f82f242009-11-18 22:49:29 +00004321 if (Previous.empty() && NewFD->isExternC()) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004322 // Since we did not find anything by this name and we're declaring
4323 // an extern "C" function, look for a non-visible extern "C"
4324 // declaration with the same name.
4325 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004326 = LocallyScopedExternalDecls.find(NewFD->getDeclName());
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004327 if (Pos != LocallyScopedExternalDecls.end())
John McCall1f82f242009-11-18 22:49:29 +00004328 Previous.addDecl(Pos->second);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004329 }
4330
Douglas Gregore62c0a42009-02-24 01:23:02 +00004331 // Merge or overload the declaration with an existing declaration of
4332 // the same name, if appropriate.
John McCall1f82f242009-11-18 22:49:29 +00004333 if (!Previous.empty()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00004334 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xubece5d62009-01-16 01:13:29 +00004335 // a declaration that requires merging. If it's an overload,
4336 // there's no more work to do here; we'll just add the new
4337 // function to the scope.
Douglas Gregor633b7372009-02-13 00:26:38 +00004338
John McCall1f82f242009-11-18 22:49:29 +00004339 NamedDecl *OldDecl = 0;
John McCalldaa3d6b2009-12-09 03:35:25 +00004340 if (!AllowOverloadingOfFunction(Previous, Context)) {
4341 Redeclaration = true;
4342 OldDecl = Previous.getFoundDecl();
4343 } else {
John McCalle9cccd82010-06-16 08:42:20 +00004344 switch (CheckOverload(S, NewFD, Previous, OldDecl,
4345 /*NewIsUsingDecl*/ false)) {
John McCalldaa3d6b2009-12-09 03:35:25 +00004346 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00004347 Redeclaration = true;
John McCalldaa3d6b2009-12-09 03:35:25 +00004348 break;
4349
4350 case Ovl_NonFunction:
4351 Redeclaration = true;
4352 break;
4353
4354 case Ovl_Overload:
4355 Redeclaration = false;
4356 break;
John McCall1f82f242009-11-18 22:49:29 +00004357 }
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004358
4359 if (!getLangOptions().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
4360 // If a function name is overloadable in C, then every function
4361 // with that name must be marked "overloadable".
4362 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
4363 << Redeclaration << NewFD;
4364 NamedDecl *OverloadedDecl = 0;
4365 if (Redeclaration)
4366 OverloadedDecl = OldDecl;
4367 else if (!Previous.empty())
4368 OverloadedDecl = Previous.getRepresentativeDecl();
4369 if (OverloadedDecl)
4370 Diag(OverloadedDecl->getLocation(),
4371 diag::note_attribute_overloadable_prev_overload);
4372 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
4373 Context));
4374 }
John McCall1f82f242009-11-18 22:49:29 +00004375 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004376
John McCall1f82f242009-11-18 22:49:29 +00004377 if (Redeclaration) {
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004378 // NewFD and OldDecl represent declarations that need to be
Mike Stump11289f42009-09-09 15:08:12 +00004379 // merged.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00004380 if (MergeFunctionDecl(NewFD, OldDecl))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004381 return NewFD->setInvalidDecl();
Zhongxing Xubece5d62009-01-16 01:13:29 +00004382
John McCall1f82f242009-11-18 22:49:29 +00004383 Previous.clear();
4384 Previous.addDecl(OldDecl);
4385
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004386 if (FunctionTemplateDecl *OldTemplateDecl
Douglas Gregorca027af2009-10-12 22:27:17 +00004387 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
Douglas Gregorcf915552009-10-13 16:30:37 +00004388 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
Douglas Gregorca027af2009-10-12 22:27:17 +00004389 FunctionTemplateDecl *NewTemplateDecl
4390 = NewFD->getDescribedFunctionTemplate();
4391 assert(NewTemplateDecl && "Template/non-template mismatch");
4392 if (CXXMethodDecl *Method
4393 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
4394 Method->setAccess(OldTemplateDecl->getAccess());
4395 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
4396 }
Douglas Gregorcf915552009-10-13 16:30:37 +00004397
4398 // If this is an explicit specialization of a member that is a function
4399 // template, mark it as a member specialization.
4400 if (IsExplicitSpecialization &&
4401 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
4402 NewTemplateDecl->setMemberSpecialization();
4403 assert(OldTemplateDecl->isMemberSpecialization());
4404 }
Douglas Gregorca027af2009-10-12 22:27:17 +00004405 } else {
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00004406 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
4407 NewFD->setAccess(OldDecl->getAccess());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004408 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00004409 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004410 }
Douglas Gregor8af63e42009-02-06 17:46:57 +00004411 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004412
Anders Carlsson1b12ed42009-09-13 21:33:06 +00004413 // Semantic checking for this function declaration (in isolation).
4414 if (getLangOptions().CPlusPlus) {
4415 // C++-specific checks.
4416 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
4417 CheckConstructor(Constructor);
Anders Carlsson2a50e952009-11-15 22:49:34 +00004418 } else if (CXXDestructorDecl *Destructor =
4419 dyn_cast<CXXDestructorDecl>(NewFD)) {
4420 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson1b12ed42009-09-13 21:33:06 +00004421 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson2a50e952009-11-15 22:49:34 +00004422
Douglas Gregor7454c562010-07-02 20:37:36 +00004423 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson2a50e952009-11-15 22:49:34 +00004424 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson1b12ed42009-09-13 21:33:06 +00004425 if (!ClassType->isDependentType()) {
4426 DeclarationName Name
4427 = Context.DeclarationNames.getCXXDestructorName(
4428 Context.getCanonicalType(ClassType));
4429 if (NewFD->getDeclName() != Name) {
4430 Diag(NewFD->getLocation(), diag::err_destructor_name);
4431 return NewFD->setInvalidDecl();
4432 }
4433 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00004434 } else if (CXXConversionDecl *Conversion
Douglas Gregor21920e372009-12-01 17:24:26 +00004435 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00004436 ActOnConversionDeclarator(Conversion);
Douglas Gregor21920e372009-12-01 17:24:26 +00004437 }
4438
4439 // Find any virtual functions that this function overrides.
Douglas Gregor6be3de32009-12-01 17:35:23 +00004440 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
4441 if (!Method->isFunctionTemplateSpecialization() &&
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004442 !Method->getDescribedFunctionTemplate()) {
4443 if (AddOverriddenMethods(Method->getParent(), Method)) {
4444 // If the function was marked as "static", we have a problem.
4445 if (NewFD->getStorageClass() == SC_Static) {
4446 Diag(NewFD->getLocation(), diag::err_static_overrides_virtual)
4447 << NewFD->getDeclName();
4448 for (CXXMethodDecl::method_iterator
4449 Overridden = Method->begin_overridden_methods(),
4450 OverriddenEnd = Method->end_overridden_methods();
4451 Overridden != OverriddenEnd;
4452 ++Overridden) {
4453 Diag((*Overridden)->getLocation(),
4454 diag::note_overridden_virtual_function);
4455 }
4456 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004457 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004458 }
Douglas Gregor6be3de32009-12-01 17:35:23 +00004459 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00004460
4461 // Extra checking for C++ overloaded operators (C++ [over.oper]).
4462 if (NewFD->isOverloadedOperator() &&
4463 CheckOverloadedOperatorDeclaration(NewFD))
4464 return NewFD->setInvalidDecl();
Alexis Huntc88db062010-01-13 09:01:02 +00004465
4466 // Extra checking for C++0x literal operators (C++0x [over.literal]).
4467 if (NewFD->getLiteralIdentifier() &&
4468 CheckLiteralOperatorDeclaration(NewFD))
4469 return NewFD->setInvalidDecl();
4470
Anders Carlsson1b12ed42009-09-13 21:33:06 +00004471 // In C++, check default arguments now that we have merged decls. Unless
4472 // the lexical context is the class, because in this case this is done
4473 // during delayed parsing anyway.
4474 if (!CurContext->isRecord())
4475 CheckCXXDefaultArguments(NewFD);
Douglas Gregor9246b682010-12-21 19:47:46 +00004476
4477 // If this function declares a builtin function, check the type of this
4478 // declaration against the expected type for the builtin.
4479 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
4480 ASTContext::GetBuiltinTypeError Error;
4481 QualType T = Context.GetBuiltinType(BuiltinID, Error);
4482 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
4483 // The type of this function differs from the type of the builtin,
4484 // so forget about the builtin entirely.
4485 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
4486 }
4487 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00004488 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004489}
4490
John McCalld9baf6a2009-07-24 03:03:21 +00004491void Sema::CheckMain(FunctionDecl* FD) {
John McCall02dee0a2009-07-25 04:36:53 +00004492 // C++ [basic.start.main]p3: A program that declares main to be inline
4493 // or static is ill-formed.
4494 // C99 6.7.4p4: In a hosted environment, the inline function specifier
4495 // shall not appear in a declaration of main.
4496 // static main is not an error under C99, but we should warn about it.
Douglas Gregor35b57532009-10-27 21:01:01 +00004497 bool isInline = FD->isInlineSpecified();
John McCall8e7d6562010-08-26 03:08:43 +00004498 bool isStatic = FD->getStorageClass() == SC_Static;
John McCall02dee0a2009-07-25 04:36:53 +00004499 if (isInline || isStatic) {
4500 unsigned diagID = diag::warn_unusual_main_decl;
4501 if (isInline || getLangOptions().CPlusPlus)
4502 diagID = diag::err_unusual_main_decl;
4503
4504 int which = isStatic + (isInline << 1) - 1;
4505 Diag(FD->getLocation(), diagID) << which;
4506 }
4507
4508 QualType T = FD->getType();
4509 assert(T->isFunctionType() && "function decl is not of function type");
John McCall9dd450b2009-09-21 23:43:11 +00004510 const FunctionType* FT = T->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00004511
John McCall02dee0a2009-07-25 04:36:53 +00004512 if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
Douglas Gregorf05c0952011-02-19 19:04:23 +00004513 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
John McCall02dee0a2009-07-25 04:36:53 +00004514 FD->setInvalidDecl(true);
4515 }
4516
4517 // Treat protoless main() as nullary.
4518 if (isa<FunctionNoProtoType>(FT)) return;
4519
4520 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
4521 unsigned nparams = FTP->getNumArgs();
4522 assert(FD->getNumParams() == nparams);
4523
John McCall0e21fcc2009-12-24 09:58:38 +00004524 bool HasExtraParameters = (nparams > 3);
4525
4526 // Darwin passes an undocumented fourth argument of type char**. If
4527 // other platforms start sprouting these, the logic below will start
4528 // getting shifty.
4529 if (nparams == 4 &&
4530 Context.Target.getTriple().getOS() == llvm::Triple::Darwin)
4531 HasExtraParameters = false;
4532
4533 if (HasExtraParameters) {
John McCall02dee0a2009-07-25 04:36:53 +00004534 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
4535 FD->setInvalidDecl(true);
4536 nparams = 3;
4537 }
4538
4539 // FIXME: a lot of the following diagnostics would be improved
4540 // if we had some location information about types.
4541
4542 QualType CharPP =
4543 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall0e21fcc2009-12-24 09:58:38 +00004544 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall02dee0a2009-07-25 04:36:53 +00004545
4546 for (unsigned i = 0; i < nparams; ++i) {
4547 QualType AT = FTP->getArgType(i);
4548
4549 bool mismatch = true;
4550
4551 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
4552 mismatch = false;
4553 else if (Expected[i] == CharPP) {
4554 // As an extension, the following forms are okay:
4555 // char const **
4556 // char const * const *
4557 // char * const *
4558
John McCall8ccfcb52009-09-24 19:53:00 +00004559 QualifierCollector qs;
John McCall02dee0a2009-07-25 04:36:53 +00004560 const PointerType* PT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004561 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
4562 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
John McCall02dee0a2009-07-25 04:36:53 +00004563 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
4564 qs.removeConst();
4565 mismatch = !qs.empty();
4566 }
4567 }
4568
4569 if (mismatch) {
4570 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
4571 // TODO: suggest replacing given type with expected type
4572 FD->setInvalidDecl(true);
4573 }
4574 }
4575
4576 if (nparams == 1 && !FD->isInvalidDecl()) {
4577 Diag(FD->getLocation(), diag::warn_main_one_arg);
4578 }
Douglas Gregorbff62032010-10-21 16:57:46 +00004579
4580 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
4581 Diag(FD->getLocation(), diag::err_main_template_decl);
4582 FD->setInvalidDecl();
4583 }
John McCalld9baf6a2009-07-24 03:03:21 +00004584}
4585
Eli Friedmand5a55bd2008-05-20 13:48:25 +00004586bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00004587 // FIXME: Need strict checking. In C89, we need to check for
4588 // any assignment, increment, decrement, function-calls, or
4589 // commas outside of a sizeof. In C99, it's the same list,
4590 // except that the aforementioned are allowed in unevaluated
4591 // expressions. Everything else falls under the
4592 // "may accept other forms of constant expressions" exception.
4593 // (We never end up here for C++, so the constant expression
4594 // rules there don't matter.)
John McCall8b0f4ff2010-08-02 21:13:48 +00004595 if (Init->isConstantInitializer(Context, false))
Eli Friedman7bfab362009-02-22 06:45:27 +00004596 return false;
Eli Friedman4f294cf2009-02-26 04:47:58 +00004597 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
4598 << Init->getSourceRange();
Eli Friedmand5a55bd2008-05-20 13:48:25 +00004599 return true;
Steve Naroff98f72032008-01-10 22:15:12 +00004600}
4601
Douglas Gregor5fb53972009-01-14 15:45:31 +00004602/// AddInitializerToDecl - Adds the initializer Init to the
4603/// declaration dcl. If DirectInit is true, this is C++ direct
4604/// initialization rather than copy initialization.
Richard Smith30482bc2011-02-20 03:19:35 +00004605void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
4606 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner8beb9de2007-10-19 20:10:30 +00004607 // If there is no declaration, there was an error parsing it. Just ignore
4608 // the initializer.
Richard Smith30482bc2011-02-20 03:19:35 +00004609 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner8beb9de2007-10-19 20:10:30 +00004610 return;
Mike Stump11289f42009-09-09 15:08:12 +00004611
Douglas Gregor0c880302009-03-11 23:00:04 +00004612 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
4613 // With declarators parsed the way they are, the parser cannot
4614 // distinguish between a normal initializer and a pure-specifier.
4615 // Thus this grotesque test.
4616 IntegerLiteral *IL;
Douglas Gregor0c880302009-03-11 23:00:04 +00004617 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor21920e372009-12-01 17:24:26 +00004618 Context.getCanonicalType(IL->getType()) == Context.IntTy)
4619 CheckPureMethod(Method, Init->getSourceRange());
4620 else {
Douglas Gregor0c880302009-03-11 23:00:04 +00004621 Diag(Method->getLocation(), diag::err_member_function_initialization)
4622 << Method->getDeclName() << Init->getSourceRange();
4623 Method->setInvalidDecl();
4624 }
4625 return;
4626 }
4627
Steve Naroff437b4d82007-09-12 20:13:48 +00004628 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4629 if (!VDecl) {
Douglas Gregor0c880302009-03-11 23:00:04 +00004630 if (getLangOptions().CPlusPlus &&
4631 RealDecl->getLexicalDeclContext()->isRecord() &&
4632 isa<NamedDecl>(RealDecl))
John McCalldb768922010-09-10 23:21:22 +00004633 Diag(RealDecl->getLocation(), diag::err_member_initialization);
Douglas Gregor0c880302009-03-11 23:00:04 +00004634 else
4635 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +00004636 RealDecl->setInvalidDecl();
4637 return;
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00004638 }
4639
Richard Smith30482bc2011-02-20 03:19:35 +00004640 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
4641 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00004642 QualType DeducedType;
4643 if (!DeduceAutoType(VDecl->getType(), Init, DeducedType)) {
4644 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
4645 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4646 << Init->getSourceRange();
4647 RealDecl->setInvalidDecl();
4648 return;
4649 }
4650 VDecl->setType(DeducedType);
4651
4652 // If this is a redeclaration, check that the type we just deduced matches
4653 // the previously declared type.
4654 if (VarDecl *Old = VDecl->getPreviousDeclaration())
4655 MergeVarDeclTypes(VDecl, Old);
4656 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00004657
4658
Eli Friedmanc9827d12009-11-14 03:40:14 +00004659 // A definition must end up with a complete type, which means it must be
4660 // complete with the restriction that an array type might be completed by the
4661 // initializer; note that later code assumes this restriction.
4662 QualType BaseDeclType = VDecl->getType();
4663 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
4664 BaseDeclType = Array->getElementType();
4665 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
Eli Friedman337cd3a2009-04-13 21:28:54 +00004666 diag::err_typecheck_decl_incomplete_type)) {
4667 RealDecl->setInvalidDecl();
4668 return;
4669 }
4670
Douglas Gregorc99f1552009-12-03 18:33:45 +00004671 // The variable can not have an abstract class type.
4672 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4673 diag::err_abstract_type_in_decl,
4674 AbstractVariableType))
4675 VDecl->setInvalidDecl();
4676
Sebastian Redl5ca79842010-02-01 20:16:42 +00004677 const VarDecl *Def;
4678 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00004679 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor0760fa12009-03-10 23:43:53 +00004680 << VDecl->getDeclName();
4681 Diag(Def->getLocation(), diag::note_previous_definition);
4682 VDecl->setInvalidDecl();
4683 return;
4684 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00004685
Douglas Gregorf0f83692010-08-24 05:27:49 +00004686 const VarDecl* PrevInit = 0;
Douglas Gregor71f39c92010-12-16 01:31:22 +00004687 if (getLangOptions().CPlusPlus) {
4688 // C++ [class.static.data]p4
4689 // If a static data member is of const integral or const
4690 // enumeration type, its declaration in the class definition can
4691 // specify a constant-initializer which shall be an integral
4692 // constant expression (5.19). In that case, the member can appear
4693 // in integral constant expressions. The member shall still be
4694 // defined in a namespace scope if it is used in the program and the
4695 // namespace scope definition shall not contain an initializer.
4696 //
4697 // We already performed a redefinition check above, but for static
4698 // data members we also need to check whether there was an in-class
4699 // declaration with an initializer.
4700 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
4701 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
4702 Diag(PrevInit->getLocation(), diag::note_previous_definition);
4703 return;
4704 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00004705
Douglas Gregor71f39c92010-12-16 01:31:22 +00004706 if (VDecl->hasLocalStorage())
4707 getCurFunction()->setHasBranchProtectedScope();
4708
4709 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
4710 VDecl->setInvalidDecl();
4711 return;
4712 }
4713 }
John McCalld4e1b762010-08-01 01:24:59 +00004714
Douglas Gregor85dabae2009-12-16 01:38:02 +00004715 // Capture the variable that is being initialized and the style of
4716 // initialization.
4717 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4718
4719 // FIXME: Poor source location information.
4720 InitializationKind Kind
4721 = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(),
4722 Init->getLocStart(),
4723 Init->getLocEnd())
4724 : InitializationKind::CreateCopy(VDecl->getLocation(),
4725 Init->getLocStart());
4726
Steve Naroff61091402007-09-12 14:07:44 +00004727 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +00004728 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +00004729 QualType DclT = VDecl->getType(), SavT = DclT;
John McCall1c9c3fd2010-10-15 04:57:14 +00004730 if (VDecl->isLocalVarDecl()) {
Daniel Dunbar0ca16602009-04-14 02:25:56 +00004731 if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
Steve Naroff437b4d82007-09-12 20:13:48 +00004732 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff08899ff2008-04-15 22:42:06 +00004733 VDecl->setInvalidDecl();
4734 } else if (!VDecl->isInvalidDecl()) {
Eli Friedman78275202009-12-19 08:11:05 +00004735 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
John McCalldadc5752010-08-24 06:29:42 +00004736 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00004737 MultiExprArg(*this, &Init, 1),
Eli Friedman463e5232009-12-22 02:10:53 +00004738 &DclT);
4739 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00004740 VDecl->setInvalidDecl();
Eli Friedman78275202009-12-19 08:11:05 +00004741 return;
4742 }
Mike Stump11289f42009-09-09 15:08:12 +00004743
Eli Friedman463e5232009-12-22 02:10:53 +00004744 Init = Result.takeAs<Expr>();
4745
Anders Carlsson41e08812008-08-22 05:00:02 +00004746 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmance982572009-02-20 01:34:21 +00004747 // Don't check invalid declarations to avoid emitting useless diagnostics.
4748 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
John McCall8e7d6562010-08-26 03:08:43 +00004749 if (VDecl->getStorageClass() == SC_Static) // C99 6.7.8p4.
Anders Carlsson41e08812008-08-22 05:00:02 +00004750 CheckForConstantInitializer(Init, DclT);
4751 }
Steve Naroff61091402007-09-12 14:07:44 +00004752 }
Mike Stump11289f42009-09-09 15:08:12 +00004753 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor0c880302009-03-11 23:00:04 +00004754 VDecl->getLexicalDeclContext()->isRecord()) {
4755 // This is an in-class initialization for a static data member, e.g.,
4756 //
4757 // struct S {
4758 // static const int value = 17;
4759 // };
4760
John McCalldb768922010-09-10 23:21:22 +00004761 // Try to perform the initialization regardless.
4762 if (!VDecl->isInvalidDecl()) {
4763 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
4764 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
4765 MultiExprArg(*this, &Init, 1),
4766 &DclT);
4767 if (Result.isInvalid()) {
4768 VDecl->setInvalidDecl();
4769 return;
4770 }
4771
4772 Init = Result.takeAs<Expr>();
4773 }
Douglas Gregor0c880302009-03-11 23:00:04 +00004774
4775 // C++ [class.mem]p4:
4776 // A member-declarator can contain a constant-initializer only
4777 // if it declares a static member (9.4) of const integral or
4778 // const enumeration type, see 9.4.2.
4779 QualType T = VDecl->getType();
John McCalldb768922010-09-10 23:21:22 +00004780
4781 // Do nothing on dependent types.
4782 if (T->isDependentType()) {
4783
4784 // Require constness.
4785 } else if (!T.isConstQualified()) {
4786 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
4787 << Init->getSourceRange();
Douglas Gregor0c880302009-03-11 23:00:04 +00004788 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00004789
4790 // We allow integer constant expressions in all cases.
4791 } else if (T->isIntegralOrEnumerationType()) {
4792 if (!Init->isValueDependent()) {
Douglas Gregor0c880302009-03-11 23:00:04 +00004793 // Check whether the expression is a constant expression.
4794 llvm::APSInt Value;
4795 SourceLocation Loc;
4796 if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) {
4797 Diag(Loc, diag::err_in_class_initializer_non_constant)
4798 << Init->getSourceRange();
4799 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00004800 }
4801 }
4802
4803 // We allow floating-point constants as an extension in C++03, and
4804 // C++0x has far more complicated rules that we don't really
4805 // implement fully.
4806 } else {
4807 bool Allowed = false;
4808 if (getLangOptions().CPlusPlus0x) {
4809 Allowed = T->isLiteralType();
4810 } else if (T->isFloatingType()) { // also permits complex, which is ok
4811 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
4812 << T << Init->getSourceRange();
4813 Allowed = true;
4814 }
4815
4816 if (!Allowed) {
4817 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
4818 << T << Init->getSourceRange();
4819 VDecl->setInvalidDecl();
4820
4821 // TODO: there are probably expressions that pass here that shouldn't.
4822 } else if (!Init->isValueDependent() &&
4823 !Init->isConstantInitializer(Context, false)) {
4824 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
4825 << Init->getSourceRange();
4826 VDecl->setInvalidDecl();
Douglas Gregor0c880302009-03-11 23:00:04 +00004827 }
4828 }
Steve Naroff08899ff2008-04-15 22:42:06 +00004829 } else if (VDecl->isFileVarDecl()) {
Douglas Gregord4e1fb52010-10-15 01:21:46 +00004830 if (VDecl->getStorageClassAsWritten() == SC_Extern &&
Douglas Gregorfceea362010-04-22 14:36:26 +00004831 (!getLangOptions().CPlusPlus ||
4832 !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
Steve Naroff437b4d82007-09-12 20:13:48 +00004833 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedman463e5232009-12-22 02:10:53 +00004834 if (!VDecl->isInvalidDecl()) {
4835 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
John McCalldadc5752010-08-24 06:29:42 +00004836 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00004837 MultiExprArg(*this, &Init, 1),
Eli Friedman463e5232009-12-22 02:10:53 +00004838 &DclT);
4839 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00004840 VDecl->setInvalidDecl();
Eli Friedman463e5232009-12-22 02:10:53 +00004841 return;
4842 }
4843
4844 Init = Result.takeAs<Expr>();
4845 }
Mike Stump11289f42009-09-09 15:08:12 +00004846
Anders Carlsson41e08812008-08-22 05:00:02 +00004847 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmance982572009-02-20 01:34:21 +00004848 // Don't check invalid declarations to avoid emitting useless diagnostics.
4849 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
Anders Carlsson41e08812008-08-22 05:00:02 +00004850 // C99 6.7.8p4. All file scoped initializers need to be constant.
4851 CheckForConstantInitializer(Init, DclT);
4852 }
Steve Naroff61091402007-09-12 14:07:44 +00004853 }
4854 // If the type changed, it means we had an incomplete type that was
Mike Stump11289f42009-09-09 15:08:12 +00004855 // completed by the initializer. For example:
Steve Naroff61091402007-09-12 14:07:44 +00004856 // int ary[] = { 1, 3, 5 };
4857 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb2ed9afd2007-11-29 19:09:19 +00004858 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff437b4d82007-09-12 20:13:48 +00004859 VDecl->setType(DclT);
Christopher Lamb2ed9afd2007-11-29 19:09:19 +00004860 Init->setType(DclT);
4861 }
Mike Stump11289f42009-09-09 15:08:12 +00004862
Chris Lattner88fdea82010-10-10 18:16:20 +00004863
4864 // If this variable is a local declaration with record type, make sure it
4865 // doesn't have a flexible member initialization. We only support this as a
4866 // global/static definition.
4867 if (VDecl->hasLocalStorage())
4868 if (const RecordType *RT = VDecl->getType()->getAs<RecordType>())
Douglas Gregor1f81ced2010-10-15 23:53:28 +00004869 if (RT->getDecl()->hasFlexibleArrayMember()) {
4870 // Check whether the initializer tries to initialize the flexible
4871 // array member itself to anything other than an empty initializer list.
4872 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
4873 unsigned Index = std::distance(RT->getDecl()->field_begin(),
4874 RT->getDecl()->field_end()) - 1;
4875 if (Index < ILE->getNumInits() &&
4876 !(isa<InitListExpr>(ILE->getInit(Index)) &&
4877 cast<InitListExpr>(ILE->getInit(Index))->getNumInits() == 0)) {
4878 Diag(VDecl->getLocation(), diag::err_nonstatic_flexible_variable);
4879 VDecl->setInvalidDecl();
4880 }
4881 }
Chris Lattner88fdea82010-10-10 18:16:20 +00004882 }
4883
John McCallacf0ee52010-10-08 02:01:28 +00004884 // Check any implicit conversions within the expression.
4885 CheckImplicitConversions(Init, VDecl->getLocation());
4886
John McCall5d413782010-12-06 08:20:24 +00004887 Init = MaybeCreateExprWithCleanups(Init);
Steve Naroff61091402007-09-12 14:07:44 +00004888 // Attach the initializer to the decl.
Douglas Gregord5058122010-02-11 01:19:42 +00004889 VDecl->setInit(Init);
Douglas Gregorbeecd582009-04-21 17:11:58 +00004890
John McCall8b7fd8f12011-01-19 11:48:09 +00004891 CheckCompleteVariableDeclaration(VDecl);
Steve Naroff61091402007-09-12 14:07:44 +00004892}
4893
John McCalleae5acb2010-03-31 02:13:20 +00004894/// ActOnInitializerError - Given that there was an error parsing an
4895/// initializer for the given declaration, try to return to some form
4896/// of sanity.
John McCall48871652010-08-21 09:40:31 +00004897void Sema::ActOnInitializerError(Decl *D) {
John McCalleae5acb2010-03-31 02:13:20 +00004898 // Our main concern here is re-establishing invariants like "a
4899 // variable's type is either dependent or complete".
John McCalleae5acb2010-03-31 02:13:20 +00004900 if (!D || D->isInvalidDecl()) return;
4901
4902 VarDecl *VD = dyn_cast<VarDecl>(D);
4903 if (!VD) return;
4904
Richard Smith30482bc2011-02-20 03:19:35 +00004905 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smithb2bc2e62011-02-21 20:05:19 +00004906 if (ParsingInitForAutoVars.count(D)) {
4907 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00004908 return;
4909 }
4910
John McCalleae5acb2010-03-31 02:13:20 +00004911 QualType Ty = VD->getType();
4912 if (Ty->isDependentType()) return;
4913
4914 // Require a complete type.
4915 if (RequireCompleteType(VD->getLocation(),
4916 Context.getBaseElementType(Ty),
4917 diag::err_typecheck_decl_incomplete_type)) {
4918 VD->setInvalidDecl();
4919 return;
4920 }
4921
4922 // Require an abstract type.
4923 if (RequireNonAbstractType(VD->getLocation(), Ty,
4924 diag::err_abstract_type_in_decl,
4925 AbstractVariableType)) {
4926 VD->setInvalidDecl();
4927 return;
4928 }
4929
4930 // Don't bother complaining about constructors or destructors,
4931 // though.
4932}
4933
John McCall48871652010-08-21 09:40:31 +00004934void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith30482bc2011-02-20 03:19:35 +00004935 bool TypeMayContainAuto) {
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00004936 // If there is no declaration, there was an error parsing it. Just ignore it.
4937 if (RealDecl == 0)
4938 return;
4939
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004940 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
4941 QualType Type = Var->getType();
Douglas Gregorbeecd582009-04-21 17:11:58 +00004942
Anders Carlssonae019932009-07-11 00:34:39 +00004943 // C++0x [dcl.spec.auto]p3
Richard Smith30482bc2011-02-20 03:19:35 +00004944 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlssonae019932009-07-11 00:34:39 +00004945 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
4946 << Var->getDeclName() << Type;
4947 Var->setInvalidDecl();
4948 return;
4949 }
Mike Stump11289f42009-09-09 15:08:12 +00004950
Douglas Gregore6565622010-02-09 07:26:29 +00004951 switch (Var->isThisDeclarationADefinition()) {
4952 case VarDecl::Definition:
4953 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
4954 break;
4955
4956 // We have an out-of-line definition of a static data member
4957 // that has an in-class initializer, so we type-check this like
4958 // a declaration.
4959 //
4960 // Fall through
4961
4962 case VarDecl::DeclarationOnly:
4963 // It's only a declaration.
4964
4965 // Block scope. C99 6.7p7: If an identifier for an object is
4966 // declared with no linkage (C99 6.2.2p6), the type for the
4967 // object shall be complete.
John McCall1c9c3fd2010-10-15 04:57:14 +00004968 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Douglas Gregore6565622010-02-09 07:26:29 +00004969 !Var->getLinkage() && !Var->isInvalidDecl() &&
4970 RequireCompleteType(Var->getLocation(), Type,
4971 diag::err_typecheck_decl_incomplete_type))
4972 Var->setInvalidDecl();
4973
4974 // Make sure that the type is not abstract.
4975 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
4976 RequireNonAbstractType(Var->getLocation(), Type,
4977 diag::err_abstract_type_in_decl,
4978 AbstractVariableType))
4979 Var->setInvalidDecl();
4980 return;
4981
4982 case VarDecl::TentativeDefinition:
4983 // File scope. C99 6.9.2p2: A declaration of an identifier for an
4984 // object that has file scope without an initializer, and without a
4985 // storage-class specifier or with the storage-class specifier "static",
4986 // constitutes a tentative definition. Note: A tentative definition with
4987 // external linkage is valid (C99 6.2.2p5).
4988 if (!Var->isInvalidDecl()) {
4989 if (const IncompleteArrayType *ArrayT
4990 = Context.getAsIncompleteArrayType(Type)) {
4991 if (RequireCompleteType(Var->getLocation(),
4992 ArrayT->getElementType(),
4993 diag::err_illegal_decl_array_incomplete_type))
4994 Var->setInvalidDecl();
John McCall8e7d6562010-08-26 03:08:43 +00004995 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregore6565622010-02-09 07:26:29 +00004996 // C99 6.9.2p3: If the declaration of an identifier for an object is
4997 // a tentative definition and has internal linkage (C99 6.2.2p3), the
4998 // declared type shall not be an incomplete type.
4999 // NOTE: code such as the following
5000 // static struct s;
5001 // struct s { int a; };
5002 // is accepted by gcc. Hence here we issue a warning instead of
5003 // an error and we do not invalidate the static declaration.
5004 // NOTE: to avoid multiple warnings, only check the first declaration.
5005 if (Var->getPreviousDeclaration() == 0)
5006 RequireCompleteType(Var->getLocation(), Type,
5007 diag::ext_typecheck_decl_incomplete_type);
5008 }
5009 }
5010
5011 // Record the tentative definition; we're done.
5012 if (!Var->isInvalidDecl())
5013 TentativeDefinitions.push_back(Var);
5014 return;
5015 }
5016
5017 // Provide a specific diagnostic for uninitialized variable
5018 // definitions with incomplete array type.
5019 if (Type->isIncompleteArrayType()) {
Sebastian Redl10600672009-11-05 19:47:47 +00005020 Diag(Var->getLocation(),
5021 diag::err_typecheck_incomplete_array_needs_initializer);
5022 Var->setInvalidDecl();
5023 return;
5024 }
5025
John McCalla755f0f2010-08-01 01:25:24 +00005026 // Provide a specific diagnostic for uninitialized variable
5027 // definitions with reference type.
5028 if (Type->isReferenceType()) {
5029 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
5030 << Var->getDeclName()
5031 << SourceRange(Var->getLocation(), Var->getLocation());
5032 Var->setInvalidDecl();
5033 return;
5034 }
Douglas Gregore6565622010-02-09 07:26:29 +00005035
5036 // Do not attempt to type-check the default initializer for a
5037 // variable with dependent type.
5038 if (Type->isDependentType())
Douglas Gregor86d142a2009-10-08 07:24:58 +00005039 return;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005040
Douglas Gregore6565622010-02-09 07:26:29 +00005041 if (Var->isInvalidDecl())
5042 return;
Douglas Gregorc99f1552009-12-03 18:33:45 +00005043
Douglas Gregore6565622010-02-09 07:26:29 +00005044 if (RequireCompleteType(Var->getLocation(),
5045 Context.getBaseElementType(Type),
5046 diag::err_typecheck_decl_incomplete_type)) {
5047 Var->setInvalidDecl();
5048 return;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00005049 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005050
Douglas Gregore6565622010-02-09 07:26:29 +00005051 // The variable can not have an abstract class type.
5052 if (RequireNonAbstractType(Var->getLocation(), Type,
5053 diag::err_abstract_type_in_decl,
5054 AbstractVariableType)) {
5055 Var->setInvalidDecl();
5056 return;
5057 }
5058
Douglas Gregor589973b2010-03-08 02:45:10 +00005059 const RecordType *Record
5060 = Context.getBaseElementType(Type)->getAs<RecordType>();
5061 if (Record && getLangOptions().CPlusPlus && !getLangOptions().CPlusPlus0x &&
5062 cast<CXXRecordDecl>(Record->getDecl())->isPOD()) {
5063 // C++03 [dcl.init]p9:
5064 // If no initializer is specified for an object, and the
5065 // object is of (possibly cv-qualified) non-POD class type (or
5066 // array thereof), the object shall be default-initialized; if
5067 // the object is of const-qualified type, the underlying class
5068 // type shall have a user-declared default
5069 // constructor. Otherwise, if no initializer is specified for
5070 // a non- static object, the object and its subobjects, if
5071 // any, have an indeterminate initial value); if the object
5072 // or any of its subobjects are of const-qualified type, the
5073 // program is ill-formed.
5074 // FIXME: DPG thinks it is very fishy that C++0x disables this.
5075 } else {
John McCalld4e1b762010-08-01 01:24:59 +00005076 // Check for jumps past the implicit initializer. C++0x
5077 // clarifies that this applies to a "variable with automatic
5078 // storage duration", not a "local variable".
5079 if (getLangOptions().CPlusPlus && Var->hasLocalStorage())
John McCallaab3e412010-08-25 08:40:02 +00005080 getCurFunction()->setHasBranchProtectedScope();
John McCalld4e1b762010-08-01 01:24:59 +00005081
Douglas Gregor589973b2010-03-08 02:45:10 +00005082 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
5083 InitializationKind Kind
5084 = InitializationKind::CreateDefault(Var->getLocation());
Douglas Gregore6565622010-02-09 07:26:29 +00005085
Douglas Gregor589973b2010-03-08 02:45:10 +00005086 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00005087 ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
5088 MultiExprArg(*this, 0, 0));
Douglas Gregor589973b2010-03-08 02:45:10 +00005089 if (Init.isInvalid())
5090 Var->setInvalidDecl();
John McCall8b7fd8f12011-01-19 11:48:09 +00005091 else if (Init.get())
Douglas Gregora40433a2010-12-07 00:41:46 +00005092 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Douglas Gregore6565622010-02-09 07:26:29 +00005093 }
Douglas Gregor589973b2010-03-08 02:45:10 +00005094
John McCall8b7fd8f12011-01-19 11:48:09 +00005095 CheckCompleteVariableDeclaration(Var);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005096 }
5097}
5098
John McCall8b7fd8f12011-01-19 11:48:09 +00005099void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
5100 if (var->isInvalidDecl()) return;
5101
5102 // All the following checks are C++ only.
5103 if (!getLangOptions().CPlusPlus) return;
5104
5105 QualType baseType = Context.getBaseElementType(var->getType());
5106 if (baseType->isDependentType()) return;
5107
5108 // __block variables might require us to capture a copy-initializer.
5109 if (var->hasAttr<BlocksAttr>()) {
5110 // It's currently invalid to ever have a __block variable with an
5111 // array type; should we diagnose that here?
5112
5113 // Regardless, we don't want to ignore array nesting when
5114 // constructing this copy.
5115 QualType type = var->getType();
5116
5117 if (type->isStructureOrClassType()) {
5118 SourceLocation poi = var->getLocation();
5119 Expr *varRef = new (Context) DeclRefExpr(var, type, VK_LValue, poi);
5120 ExprResult result =
5121 PerformCopyInitialization(
5122 InitializedEntity::InitializeBlock(poi, type, false),
5123 poi, Owned(varRef));
5124 if (!result.isInvalid()) {
5125 result = MaybeCreateExprWithCleanups(result);
5126 Expr *init = result.takeAs<Expr>();
5127 Context.setBlockVarCopyInits(var, init);
5128 }
5129 }
5130 }
5131
5132 // Check for global constructors.
5133 if (!var->getDeclContext()->isDependentContext() &&
5134 var->hasGlobalStorage() &&
5135 !var->isStaticLocal() &&
5136 var->getInit() &&
5137 !var->getInit()->isConstantInitializer(Context,
5138 baseType->isReferenceType()))
5139 Diag(var->getLocation(), diag::warn_global_constructor)
5140 << var->getInit()->getSourceRange();
5141
5142 // Require the destructor.
5143 if (const RecordType *recordType = baseType->getAs<RecordType>())
5144 FinalizeVarWithDestructor(var, recordType);
5145}
5146
Richard Smithb2bc2e62011-02-21 20:05:19 +00005147/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
5148/// any semantic actions necessary after any initializer has been attached.
5149void
5150Sema::FinalizeDeclaration(Decl *ThisDecl) {
5151 // Note that we are no longer parsing the initializer for this declaration.
5152 ParsingInitForAutoVars.erase(ThisDecl);
5153}
5154
John McCallba7bf592010-08-24 05:47:05 +00005155Sema::DeclGroupPtrTy
5156Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
5157 Decl **Group, unsigned NumDecls) {
Chris Lattner5bbb3c82009-03-29 16:50:03 +00005158 llvm::SmallVector<Decl*, 8> Decls;
Eli Friedman55b9ecb2009-05-29 01:49:24 +00005159
5160 if (DS.isTypeSpecOwned())
John McCallba7bf592010-08-24 05:47:05 +00005161 Decls.push_back(DS.getRepAsDecl());
Eli Friedman55b9ecb2009-05-29 01:49:24 +00005162
Richard Smith2abf6762011-02-23 00:37:57 +00005163 for (unsigned i = 0; i != NumDecls; ++i)
5164 if (Decl *D = Group[i])
5165 Decls.push_back(D);
5166
5167 return BuildDeclaratorGroup(Decls.data(), Decls.size(),
5168 DS.getTypeSpecType() == DeclSpec::TST_auto);
5169}
5170
5171/// BuildDeclaratorGroup - convert a list of declarations into a declaration
5172/// group, performing any necessary semantic checking.
5173Sema::DeclGroupPtrTy
5174Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
5175 bool TypeMayContainAuto) {
Richard Smith30482bc2011-02-20 03:19:35 +00005176 // C++0x [dcl.spec.auto]p7:
5177 // If the type deduced for the template parameter U is not the same in each
5178 // deduction, the program is ill-formed.
5179 // FIXME: When initializer-list support is added, a distinction is needed
5180 // between the deduced type U and the deduced type which 'auto' stands for.
5181 // auto a = 0, b = { 1, 2, 3 };
5182 // is legal because the deduced type U is 'int' in both cases.
Richard Smith2abf6762011-02-23 00:37:57 +00005183 if (TypeMayContainAuto && NumDecls > 1) {
Richard Smith30482bc2011-02-20 03:19:35 +00005184 QualType Deduced;
5185 CanQualType DeducedCanon;
5186 VarDecl *DeducedDecl = 0;
5187 for (unsigned i = 0; i != NumDecls; ++i) {
5188 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
5189 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith2abf6762011-02-23 00:37:57 +00005190 // Don't reissue diagnostics when instantiating a template.
5191 if (AT && D->isInvalidDecl())
5192 break;
Richard Smith30482bc2011-02-20 03:19:35 +00005193 if (AT && AT->isDeduced()) {
5194 QualType U = AT->getDeducedType();
5195 CanQualType UCanon = Context.getCanonicalType(U);
5196 if (Deduced.isNull()) {
5197 Deduced = U;
5198 DeducedCanon = UCanon;
5199 DeducedDecl = D;
5200 } else if (DeducedCanon != UCanon) {
Richard Smith2abf6762011-02-23 00:37:57 +00005201 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
5202 diag::err_auto_different_deductions)
Richard Smith30482bc2011-02-20 03:19:35 +00005203 << Deduced << DeducedDecl->getDeclName()
5204 << U << D->getDeclName()
5205 << DeducedDecl->getInit()->getSourceRange()
5206 << D->getInit()->getSourceRange();
Richard Smith2abf6762011-02-23 00:37:57 +00005207 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00005208 break;
5209 }
5210 }
5211 }
5212 }
5213 }
5214
Richard Smith2abf6762011-02-23 00:37:57 +00005215 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls));
Chris Lattner776fac82007-06-09 00:53:06 +00005216}
Steve Naroff7e6f7c22007-08-28 03:03:08 +00005217
Chris Lattner5bbb3c82009-03-29 16:50:03 +00005218
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005219/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
5220/// to introduce parameters into function prototype scope.
John McCall48871652010-08-21 09:40:31 +00005221Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattnercf31de32008-06-26 06:49:43 +00005222 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorad590502008-12-15 23:53:10 +00005223
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005224 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
John McCall8e7d6562010-08-26 03:08:43 +00005225 VarDecl::StorageClass StorageClass = SC_None;
5226 VarDecl::StorageClass StorageClassAsWritten = SC_None;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00005227 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCall8e7d6562010-08-26 03:08:43 +00005228 StorageClass = SC_Register;
5229 StorageClassAsWritten = SC_Register;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00005230 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005231 Diag(DS.getStorageClassSpecLoc(),
5232 diag::err_invalid_storage_class_in_func_decl);
Chris Lattnercf31de32008-06-26 06:49:43 +00005233 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005234 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005235
5236 if (D.getDeclSpec().isThreadSpecified())
5237 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
5238
Eli Friedman574c7452009-04-07 19:37:57 +00005239 DiagnoseFunctionSpecifiers(D);
5240
Douglas Gregord6ab8742009-05-28 23:31:59 +00005241 TagDecl *OwnedDecl = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00005242 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedDecl);
5243 QualType parmDeclType = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005244
Douglas Gregor27b4c162010-12-23 22:44:42 +00005245 if (getLangOptions().CPlusPlus) {
5246 // Check that there are no default arguments inside the type of this
5247 // parameter.
5248 CheckExtraCXXDefaultArguments(D);
5249
5250 if (OwnedDecl && OwnedDecl->isDefinition()) {
5251 // C++ [dcl.fct]p6:
5252 // Types shall not be defined in return or parameter types.
5253 Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
5254 << Context.getTypeDeclType(OwnedDecl);
5255 }
5256
5257 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
5258 if (D.getCXXScopeSpec().isSet()) {
5259 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
5260 << D.getCXXScopeSpec().getRange();
5261 D.getCXXScopeSpec().clear();
5262 }
Douglas Gregord6ab8742009-05-28 23:31:59 +00005263 }
5264
Alexis Hunta56cbcc2010-11-03 01:07:06 +00005265 // Ensure we have a valid name
5266 IdentifierInfo *II = 0;
5267 if (D.hasName()) {
5268 II = D.getIdentifier();
5269 if (!II) {
5270 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
5271 << GetNameForDeclarator(D).getName().getAsString();
5272 D.setInvalidType(true);
5273 }
5274 }
5275
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00005276 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnerd9773512009-01-21 02:38:50 +00005277 if (II) {
John McCall84f02672010-03-18 06:42:38 +00005278 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
5279 ForRedeclaration);
5280 LookupName(R, S);
5281 if (R.isSingleResult()) {
5282 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnerd9773512009-01-21 02:38:50 +00005283 if (PrevDecl->isTemplateParameter()) {
5284 // Maybe we will complain about the shadowed template parameter.
5285 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5286 // Just pretend that we didn't see the previous declaration.
5287 PrevDecl = 0;
John McCall48871652010-08-21 09:40:31 +00005288 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerd9773512009-01-21 02:38:50 +00005289 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00005290 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005291
Chris Lattnerd9773512009-01-21 02:38:50 +00005292 // Recover by removing the name
5293 II = 0;
5294 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00005295 D.setInvalidType(true);
Chris Lattnerd9773512009-01-21 02:38:50 +00005296 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005297 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00005298 }
Steve Naroff773df5c2007-08-07 22:44:21 +00005299
John McCallf7b2fb52010-01-22 00:28:27 +00005300 // Temporarily put parameter variables in the translation unit, not
5301 // the enclosing context. This prevents them from accidentally
5302 // looking like class members in C++.
Douglas Gregor940bca72010-04-12 07:48:19 +00005303 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00005304 D.getSourceRange().getBegin(),
5305 D.getIdentifierLoc(), II,
5306 parmDeclType, TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00005307 StorageClass, StorageClassAsWritten);
Mike Stump11289f42009-09-09 15:08:12 +00005308
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005309 if (D.isInvalidType())
Douglas Gregor940bca72010-04-12 07:48:19 +00005310 New->setInvalidDecl();
5311
Douglas Gregor91f84212008-12-11 16:49:14 +00005312 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00005313 S->AddDecl(New);
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00005314 if (II)
Douglas Gregor91f84212008-12-11 16:49:14 +00005315 IdResolver.AddDecl(New);
Nate Begemand8c41562008-02-17 21:20:31 +00005316
Douglas Gregor758a8692009-06-17 21:51:59 +00005317 ProcessDeclAttributes(S, New, D);
Mike Stumpe9efa802009-04-30 00:19:40 +00005318
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005319 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00005320 Diag(New->getLocation(), diag::err_block_on_nonlocal);
5321 }
John McCall48871652010-08-21 09:40:31 +00005322 return New;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00005323}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +00005324
John McCalla3ccba02010-06-04 11:21:44 +00005325/// \brief Synthesizes a variable for a parameter arising from a
5326/// typedef.
5327ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
5328 SourceLocation Loc,
5329 QualType T) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00005330 /* FIXME: setting StartLoc == Loc.
5331 Would it be worth to modify callers so as to provide proper source
5332 location for the unnamed parameters, embedding the parameter's type? */
5333 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCalla3ccba02010-06-04 11:21:44 +00005334 T, Context.getTrivialTypeSourceInfo(T, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00005335 SC_None, SC_None, 0);
John McCalla3ccba02010-06-04 11:21:44 +00005336 Param->setImplicit();
5337 return Param;
5338}
5339
John McCallc5990642010-08-24 09:05:15 +00005340void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
5341 ParmVarDecl * const *ParamEnd) {
John McCallc5990642010-08-24 09:05:15 +00005342 // Don't diagnose unused-parameter errors in template instantiations; we
5343 // will already have done so in the template itself.
5344 if (!ActiveTemplateInstantiations.empty())
5345 return;
5346
5347 for (; Param != ParamEnd; ++Param) {
5348 if (!(*Param)->isUsed() && (*Param)->getDeclName() &&
5349 !(*Param)->hasAttr<UnusedAttr>()) {
5350 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
5351 << (*Param)->getDeclName();
5352 }
5353 }
5354}
5355
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00005356void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
5357 ParmVarDecl * const *ParamEnd,
5358 QualType ReturnTy,
5359 NamedDecl *D) {
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00005360 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00005361 return;
5362
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00005363 // Warn if the return value is pass-by-value and larger than the specified
5364 // threshold.
Argyrios Kyrtzidis745f9992010-11-18 18:51:03 +00005365 if (ReturnTy->isPODType()) {
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00005366 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00005367 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00005368 Diag(D->getLocation(), diag::warn_return_value_size)
5369 << D->getDeclName() << Size;
5370 }
5371
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00005372 // Warn if any parameter is pass-by-value and larger than the specified
5373 // threshold.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00005374 for (; Param != ParamEnd; ++Param) {
5375 QualType T = (*Param)->getType();
5376 if (!T->isPODType())
5377 continue;
5378 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00005379 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00005380 Diag((*Param)->getLocation(), diag::warn_parameter_size)
5381 << (*Param)->getDeclName() << Size;
5382 }
5383}
5384
Abramo Bagnaradff19302011-03-08 08:55:46 +00005385ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
5386 SourceLocation NameLoc, IdentifierInfo *Name,
5387 QualType T, TypeSourceInfo *TSInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00005388 VarDecl::StorageClass StorageClass,
5389 VarDecl::StorageClass StorageClassAsWritten) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00005390 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
5391 adjustParameterType(T), TSInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00005392 StorageClass, StorageClassAsWritten,
5393 0);
Douglas Gregor940bca72010-04-12 07:48:19 +00005394
5395 // Parameters can not be abstract class types.
5396 // For record types, this is done by the AbstractClassUsageDiagnoser once
5397 // the class has been completely parsed.
5398 if (!CurContext->isRecord() &&
5399 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
5400 AbstractParamType))
5401 New->setInvalidDecl();
5402
5403 // Parameter declarators cannot be interface types. All ObjC objects are
5404 // passed by reference.
John McCall8b07ec22010-05-15 11:32:37 +00005405 if (T->isObjCObjectType()) {
Douglas Gregor940bca72010-04-12 07:48:19 +00005406 Diag(NameLoc,
5407 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
5408 New->setInvalidDecl();
5409 }
5410
5411 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
5412 // duration shall not be qualified by an address-space qualifier."
5413 // Since all parameters have automatic store duration, they can not have
5414 // an address space.
5415 if (T.getAddressSpace() != 0) {
5416 Diag(NameLoc, diag::err_arg_with_address_space);
5417 New->setInvalidDecl();
5418 }
5419
5420 return New;
5421}
5422
Douglas Gregor170512f2009-04-01 23:51:29 +00005423void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
5424 SourceLocation LocAfterDecls) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005425 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005426
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00005427 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
5428 // for a K&R function.
5429 if (!FTI.hasPrototype) {
Douglas Gregor862ffb12009-04-02 03:14:12 +00005430 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
5431 --i;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005432 if (FTI.ArgInfo[i].Param == 0) {
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00005433 llvm::SmallString<256> Code;
5434 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar07d07852009-10-18 21:17:35 +00005435 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00005436 << ";\n";
Chris Lattner4bd8dd82008-11-19 08:23:25 +00005437 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregor170512f2009-04-01 23:51:29 +00005438 << FTI.ArgInfo[i].Ident
Douglas Gregora771f462010-03-31 17:46:05 +00005439 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregor170512f2009-04-01 23:51:29 +00005440
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00005441 // Implicitly declare the argument as type 'int' for lack of a better
5442 // type.
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005443 DeclSpec DS;
5444 const char* PrevSpec; // unused
John McCall49bfce42009-08-03 20:12:06 +00005445 unsigned DiagID; // unused
Mike Stump11289f42009-09-09 15:08:12 +00005446 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCall49bfce42009-08-03 20:12:06 +00005447 PrevSpec, DiagID);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005448 Declarator ParamD(DS, Declarator::KNRTypeListContext);
5449 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregor9aa89042009-01-23 16:23:13 +00005450 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00005451 }
5452 }
Mike Stump11289f42009-09-09 15:08:12 +00005453 }
Douglas Gregor9aa89042009-01-23 16:23:13 +00005454}
5455
John McCall48871652010-08-21 09:40:31 +00005456Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
5457 Declarator &D) {
Douglas Gregor9aa89042009-01-23 16:23:13 +00005458 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005459 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregorad590502008-12-15 23:53:10 +00005460 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +00005461
John McCall48871652010-08-21 09:40:31 +00005462 Decl *DP = HandleDeclarator(ParentScope, D,
5463 MultiTemplateParamsArg(*this),
5464 /*IsFunctionDefinition=*/true);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00005465 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005466}
5467
Anders Carlsson31c7e882009-12-09 03:30:09 +00005468static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
5469 // Don't warn about invalid declarations.
5470 if (FD->isInvalidDecl())
5471 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00005472
Anders Carlsson31c7e882009-12-09 03:30:09 +00005473 // Or declarations that aren't global.
5474 if (!FD->isGlobal())
5475 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00005476
Anders Carlsson31c7e882009-12-09 03:30:09 +00005477 // Don't warn about C++ member functions.
5478 if (isa<CXXMethodDecl>(FD))
5479 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00005480
Anders Carlsson31c7e882009-12-09 03:30:09 +00005481 // Don't warn about 'main'.
5482 if (FD->isMain())
5483 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00005484
Anders Carlsson31c7e882009-12-09 03:30:09 +00005485 // Don't warn about inline functions.
5486 if (FD->isInlineSpecified())
5487 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00005488
5489 // Don't warn about function templates.
5490 if (FD->getDescribedFunctionTemplate())
5491 return false;
5492
5493 // Don't warn about function template specializations.
5494 if (FD->isFunctionTemplateSpecialization())
5495 return false;
5496
Anders Carlsson31c7e882009-12-09 03:30:09 +00005497 bool MissingPrototype = true;
5498 for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
5499 Prev; Prev = Prev->getPreviousDeclaration()) {
5500 // Ignore any declarations that occur in function or method
5501 // scope, because they aren't visible from the header.
5502 if (Prev->getDeclContext()->isFunctionOrMethod())
5503 continue;
5504
5505 MissingPrototype = !Prev->getType()->isFunctionProtoType();
5506 break;
5507 }
5508
5509 return MissingPrototype;
5510}
5511
John McCall48871652010-08-21 09:40:31 +00005512Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson561f7932009-10-29 15:46:07 +00005513 // Clear the last template instantiation error context.
5514 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
5515
Douglas Gregor17a7c122009-06-24 00:54:41 +00005516 if (!D)
5517 return D;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00005518 FunctionDecl *FD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005519
John McCall48871652010-08-21 09:40:31 +00005520 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregorc45a40a2009-08-22 00:34:47 +00005521 FD = FunTmpl->getTemplatedDecl();
5522 else
John McCall48871652010-08-21 09:40:31 +00005523 FD = cast<FunctionDecl>(D);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00005524
Douglas Gregor9a28e842010-03-01 23:15:13 +00005525 // Enter a new function scope
5526 PushFunctionScope();
Mike Stump11289f42009-09-09 15:08:12 +00005527
Douglas Gregorcad304ba2008-10-29 15:10:40 +00005528 // See if this is a redefinition.
Charles Davisfea48452010-02-18 02:00:42 +00005529 // But don't complain if we're in GNU89 mode and the previous definition
5530 // was an extern inline function.
Douglas Gregorcad304ba2008-10-29 15:10:40 +00005531 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00005532 if (FD->hasBody(Definition) &&
Charles Davisfea48452010-02-18 02:00:42 +00005533 !canRedefineFunction(Definition, getLangOptions())) {
Douglas Gregora7d6e3d2010-09-07 15:51:01 +00005534 if (getLangOptions().GNUMode && Definition->isInlineSpecified() &&
5535 Definition->getStorageClass() == SC_Extern)
5536 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
5537 << FD->getDeclName() << getLangOptions().CPlusPlus;
5538 else
5539 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00005540 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00005541 }
5542
Douglas Gregor75a45ba2009-02-16 17:45:42 +00005543 // Builtin functions cannot be defined.
Douglas Gregor15fc9562009-09-12 00:22:50 +00005544 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor7a0febe2009-02-17 16:03:01 +00005545 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00005546 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor7a0febe2009-02-17 16:03:01 +00005547 FD->setInvalidDecl();
5548 }
Douglas Gregor75a45ba2009-02-16 17:45:42 +00005549 }
5550
Eli Friedman9ad72442009-03-04 07:30:59 +00005551 // The return type of a function definition must be complete
Douglas Gregorac1fb652009-03-24 19:52:54 +00005552 // (C99 6.9.1p3, C++ [dcl.fct]p6).
5553 QualType ResultType = FD->getResultType();
5554 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner0f94c5a2009-04-29 05:12:23 +00005555 !FD->isInvalidDecl() &&
Douglas Gregorac1fb652009-03-24 19:52:54 +00005556 RequireCompleteType(FD->getLocation(), ResultType,
5557 diag::err_func_def_incomplete_result))
Eli Friedman9ad72442009-03-04 07:30:59 +00005558 FD->setInvalidDecl();
Eli Friedman9ad72442009-03-04 07:30:59 +00005559
Douglas Gregorf1b876d2009-03-31 16:35:03 +00005560 // GNU warning -Wmissing-prototypes:
5561 // Warn if a global function is defined without a previous
5562 // prototype declaration. This warning is issued even if the
5563 // definition itself provides a prototype. The aim is to detect
5564 // global functions that fail to be declared in header files.
Anders Carlsson31c7e882009-12-09 03:30:09 +00005565 if (ShouldWarnAboutMissingPrototype(FD))
5566 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Douglas Gregorf1b876d2009-03-31 16:35:03 +00005567
Douglas Gregor67da0d92009-05-15 17:59:04 +00005568 if (FnBodyScope)
5569 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00005570
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005571 // Check the validity of our function parameters
Douglas Gregorb524d902010-11-01 18:37:59 +00005572 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
5573 /*CheckParameterNames=*/true);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005574
5575 // Introduce our parameters into the function scope
5576 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
5577 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc72e6452009-01-09 18:51:29 +00005578 Param->setOwningFunction(FD);
5579
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005580 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00005581 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005582 CheckShadow(FnBodyScope, Param);
John McCalldf8b37c2010-03-22 09:20:08 +00005583
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00005584 PushOnScopeChains(Param, FnBodyScope);
John McCalldf8b37c2010-03-22 09:20:08 +00005585 }
Chris Lattnerf61c8a82007-01-21 19:04:43 +00005586 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005587
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00005588 // Checking attributes of current function definition
5589 // dllimport attribute.
Alexis Huntdcfba7b2010-08-18 23:23:40 +00005590 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
5591 if (DA && (!FD->getAttr<DLLExportAttr>())) {
5592 // dllimport attribute cannot be directly applied to definition.
5593 if (!DA->isInherited()) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00005594 Diag(FD->getLocation(),
5595 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
5596 << "dllimport";
5597 FD->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +00005598 return FD;
Ted Kremeneka3cfc4d2010-02-21 05:12:53 +00005599 }
5600
5601 // Visual C++ appears to not think this is an issue, so only issue
5602 // a warning when Microsoft extensions are disabled.
5603 if (!LangOpts.Microsoft) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00005604 // If a symbol previously declared dllimport is later defined, the
5605 // attribute is ignored in subsequent references, and a warning is
5606 // emitted.
5607 Diag(FD->getLocation(),
5608 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Daniel Dunbar56df9772010-08-17 22:39:59 +00005609 << FD->getName() << "dllimport";
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00005610 }
5611 }
John McCall48871652010-08-21 09:40:31 +00005612 return FD;
Chris Lattnere168f762006-11-10 05:29:30 +00005613}
5614
Douglas Gregor6fd1b182010-05-15 06:01:05 +00005615/// \brief Given the set of return statements within a function body,
5616/// compute the variables that are subject to the named return value
5617/// optimization.
5618///
5619/// Each of the variables that is subject to the named return value
5620/// optimization will be marked as NRVO variables in the AST, and any
5621/// return statement that has a marked NRVO variable as its NRVO candidate can
5622/// use the named return value optimization.
5623///
5624/// This function applies a very simplistic algorithm for NRVO: if every return
5625/// statement in the function has the same NRVO candidate, that candidate is
5626/// the NRVO variable.
5627///
5628/// FIXME: Employ a smarter algorithm that accounts for multiple return
5629/// statements and the lifetimes of the NRVO candidates. We should be able to
5630/// find a maximal set of NRVO variables.
John McCallaab3e412010-08-25 08:40:02 +00005631static void ComputeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
5632 ReturnStmt **Returns = Scope->Returns.data();
5633
Douglas Gregor6fd1b182010-05-15 06:01:05 +00005634 const VarDecl *NRVOCandidate = 0;
John McCallaab3e412010-08-25 08:40:02 +00005635 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00005636 if (!Returns[I]->getNRVOCandidate())
5637 return;
5638
5639 if (!NRVOCandidate)
5640 NRVOCandidate = Returns[I]->getNRVOCandidate();
5641 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
5642 return;
5643 }
5644
5645 if (NRVOCandidate)
5646 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
5647}
5648
John McCallfaf5fb42010-08-26 23:41:50 +00005649Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Douglas Gregor67da0d92009-05-15 17:59:04 +00005650 return ActOnFinishFunctionBody(D, move(BodyArg), false);
5651}
5652
John McCallb268a282010-08-23 23:25:46 +00005653Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
5654 bool IsInstantiation) {
Douglas Gregorc45a40a2009-08-22 00:34:47 +00005655 FunctionDecl *FD = 0;
5656 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
5657 if (FunTmpl)
5658 FD = FunTmpl->getTemplatedDecl();
5659 else
5660 FD = dyn_cast_or_null<FunctionDecl>(dcl);
5661
Ted Kremenek0b405322010-03-23 00:13:23 +00005662 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek1767a272011-02-23 01:51:48 +00005663 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenek918fe842010-03-20 21:06:02 +00005664
Douglas Gregorc45a40a2009-08-22 00:34:47 +00005665 if (FD) {
Chris Lattner960cc522009-04-18 09:36:27 +00005666 FD->setBody(Body);
Ted Kremenek918fe842010-03-20 21:06:02 +00005667 if (FD->isMain()) {
Mike Stump8e79f992009-07-24 02:49:01 +00005668 // C and C++ allow for main to automagically return 0.
John McCallcaa19452009-07-28 01:00:58 +00005669 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
5670 FD->setHasImplicitReturnZero(true);
Ted Kremenek0b405322010-03-23 00:13:23 +00005671 WP.disableCheckFallThrough();
Ted Kremenek918fe842010-03-20 21:06:02 +00005672 }
Mike Stump11289f42009-09-09 15:08:12 +00005673
Douglas Gregor88d292c2010-05-13 16:44:06 +00005674 if (!FD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005675 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00005676 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
5677 FD->getResultType(), FD);
Douglas Gregor88d292c2010-05-13 16:44:06 +00005678
5679 // If this is a constructor, we need a vtable.
5680 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
5681 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor6fd1b182010-05-15 06:01:05 +00005682
John McCallaab3e412010-08-25 08:40:02 +00005683 ComputeNRVO(Body, getCurFunction());
Douglas Gregor88d292c2010-05-13 16:44:06 +00005684 }
5685
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00005686 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff542cd5d2008-07-25 17:57:26 +00005687 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattner1598a3a2009-02-16 19:27:54 +00005688 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattner960cc522009-04-18 09:36:27 +00005689 MD->setBody(Body);
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00005690 if (Body)
5691 MD->setEndLoc(Body->getLocEnd());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00005692 if (!MD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005693 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00005694 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
5695 MD->getResultType(), MD);
5696 }
Ted Kremenek5a201952009-02-07 01:47:29 +00005697 } else {
John McCall48871652010-08-21 09:40:31 +00005698 return 0;
Ted Kremenek5a201952009-02-07 01:47:29 +00005699 }
Douglas Gregor67da0d92009-05-15 17:59:04 +00005700
Chris Lattnere2473062007-05-28 06:28:18 +00005701 // Verify and clean out per-function state.
Douglas Gregor9a28e842010-03-01 23:15:13 +00005702 if (Body) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00005703 // C++ constructors that have function-try-blocks can't have return
5704 // statements in the handlers of that block. (C++ [except.handle]p14)
5705 // Verify this.
5706 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
5707 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
5708
Ted Kremenek918fe842010-03-20 21:06:02 +00005709 // Verify that that gotos and switch cases don't jump into scopes illegally.
5710 // Verify that that gotos and switch cases don't jump into scopes illegally.
John McCallaab3e412010-08-25 08:40:02 +00005711 if (getCurFunction()->NeedsScopeChecking() &&
John McCall58efb8e2010-05-20 07:13:26 +00005712 !dcl->isInvalidDecl() &&
John McCalldeb5e722010-05-20 07:05:55 +00005713 !hasAnyErrorsInThisFunction())
Douglas Gregor9a28e842010-03-01 23:15:13 +00005714 DiagnoseInvalidJumps(Body);
Mike Stump11289f42009-09-09 15:08:12 +00005715
John McCalldeb646e2010-08-04 01:04:25 +00005716 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
5717 if (!Destructor->getParent()->isDependentType())
5718 CheckDestructor(Destructor);
5719
John McCalla6309952010-03-16 21:39:52 +00005720 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
5721 Destructor->getParent());
John McCalldeb646e2010-08-04 01:04:25 +00005722 }
Douglas Gregor9a28e842010-03-01 23:15:13 +00005723
5724 // If any errors have occurred, clear out any temporaries that may have
5725 // been leftover. This ensures that these temporaries won't be picked up for
5726 // deletion in some later function.
Douglas Gregor550b98b2011-03-04 23:08:02 +00005727 if (PP.getDiagnostics().hasErrorOccurred() ||
5728 PP.getDiagnostics().getSuppressAllDiagnostics())
Douglas Gregor9a28e842010-03-01 23:15:13 +00005729 ExprTemporaries.clear();
Ted Kremenek918fe842010-03-20 21:06:02 +00005730 else if (!isa<FunctionTemplateDecl>(dcl)) {
5731 // Since the body is valid, issue any analysis-based warnings that are
5732 // enabled.
Ted Kremenek1767a272011-02-23 01:51:48 +00005733 ActivePolicy = &WP;
Ted Kremenek918fe842010-03-20 21:06:02 +00005734 }
5735
Douglas Gregor9a28e842010-03-01 23:15:13 +00005736 assert(ExprTemporaries.empty() && "Leftover temporaries in function");
5737 }
5738
John McCalle99d5f32010-03-25 22:08:03 +00005739 if (!IsInstantiation)
5740 PopDeclContext();
5741
Ted Kremenek1767a272011-02-23 01:51:48 +00005742 PopFunctionOrBlockScope(ActivePolicy, dcl);
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00005743
Douglas Gregora7e3ea32009-11-15 07:07:58 +00005744 // If any errors have occurred, clear out any temporaries that may have
5745 // been leftover. This ensures that these temporaries won't be picked up for
5746 // deletion in some later function.
Chris Lattner30d0cfd2010-03-01 20:59:53 +00005747 if (getDiagnostics().hasErrorOccurred())
Douglas Gregora7e3ea32009-11-15 07:07:58 +00005748 ExprTemporaries.clear();
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00005749
John McCall48871652010-08-21 09:40:31 +00005750 return dcl;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +00005751}
5752
Chris Lattnerac18be92006-11-20 06:49:47 +00005753/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
5754/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump11289f42009-09-09 15:08:12 +00005755NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005756 IdentifierInfo &II, Scope *S) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00005757 // Before we produce a declaration for an implicitly defined
5758 // function, see whether there was a locally-scoped declaration of
5759 // this name as a function or variable. If so, use that
5760 // (non-visible) declaration, and complain about it.
5761 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
5762 = LocallyScopedExternalDecls.find(&II);
5763 if (Pos != LocallyScopedExternalDecls.end()) {
5764 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
5765 Diag(Pos->second->getLocation(), diag::note_previous_declaration);
5766 return Pos->second;
5767 }
5768
Chris Lattner00e26072008-05-05 21:18:06 +00005769 // Extension in C99. Legal in C90, but warn about it.
Daniel Dunbar07d07852009-10-18 21:17:35 +00005770 if (II.getName().startswith("__builtin_"))
Douglas Gregor56fbc372009-09-28 21:14:19 +00005771 Diag(Loc, diag::warn_builtin_unknown) << &II;
5772 else if (getLangOptions().C99)
Chris Lattner4bd8dd82008-11-19 08:23:25 +00005773 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner00e26072008-05-05 21:18:06 +00005774 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +00005775 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Mike Stump11289f42009-09-09 15:08:12 +00005776
Chris Lattnerac18be92006-11-20 06:49:47 +00005777 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +00005778 const char *Dummy;
Chris Lattnerac18be92006-11-20 06:49:47 +00005779 DeclSpec DS;
John McCall49bfce42009-08-03 20:12:06 +00005780 unsigned DiagID;
5781 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00005782 (void)Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +00005783 assert(!Error && "Error setting up implicit decl!");
Chris Lattnerac18be92006-11-20 06:49:47 +00005784 Declarator D(DS, Declarator::BlockContext);
John McCall53fa7142010-12-24 02:08:15 +00005785 D.AddTypeInfo(DeclaratorChunk::getFunction(ParsedAttributes(),
5786 false, false, SourceLocation(), 0,
Douglas Gregor54992352011-01-26 03:43:54 +00005787 0, 0, true, SourceLocation(),
Sebastian Redl802a4532011-03-05 22:42:13 +00005788 EST_None, SourceLocation(),
5789 0, 0, 0, 0, Loc, Loc, D),
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005790 SourceLocation());
Chris Lattnerac18be92006-11-20 06:49:47 +00005791 D.SetIdentifier(&II, Loc);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00005792
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00005793 // Insert this function into translation-unit scope.
5794
5795 DeclContext *PrevDC = CurContext;
5796 CurContext = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00005797
John McCall48871652010-08-21 09:40:31 +00005798 FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroff3913ea42008-04-04 14:32:09 +00005799 FD->setImplicit();
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00005800
5801 CurContext = PrevDC;
5802
Douglas Gregore711f702009-02-14 18:57:46 +00005803 AddKnownFunctionAttributes(FD);
5804
Steve Naroff3913ea42008-04-04 14:32:09 +00005805 return FD;
Chris Lattnerac18be92006-11-20 06:49:47 +00005806}
5807
Douglas Gregore711f702009-02-14 18:57:46 +00005808/// \brief Adds any function attributes that we know a priori based on
5809/// the declaration of this function.
5810///
5811/// These attributes can apply both to implicitly-declared builtins
5812/// (like __builtin___printf_chk) or to library-declared functions
5813/// like NSLog or printf.
5814void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
5815 if (FD->isInvalidDecl())
5816 return;
5817
5818 // If this is a built-in function, map its builtin attributes to
5819 // actual attributes.
Douglas Gregor15fc9562009-09-12 00:22:50 +00005820 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregore711f702009-02-14 18:57:46 +00005821 // Handle printf-formatting attributes.
5822 unsigned FormatIdx;
5823 bool HasVAListArg;
5824 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005825 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00005826 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
5827 "printf", FormatIdx+1,
Ted Kremenek7f4945a2010-02-11 05:28:37 +00005828 HasVAListArg ? 0 : FormatIdx+2));
Douglas Gregore711f702009-02-14 18:57:46 +00005829 }
Ted Kremenek5932c352010-07-16 02:11:15 +00005830 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
5831 HasVAListArg)) {
5832 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00005833 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
5834 "scanf", FormatIdx+1,
Ted Kremenek5932c352010-07-16 02:11:15 +00005835 HasVAListArg ? 0 : FormatIdx+2));
5836 }
Daniel Dunbar8eb018a2009-02-16 22:43:43 +00005837
5838 // Mark const if we don't care about errno and that is the only
5839 // thing preventing the function from being const. This allows
5840 // IRgen to use LLVM intrinsics for such functions.
5841 if (!getLangOptions().MathErrno &&
5842 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005843 if (!FD->getAttr<ConstAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00005844 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Daniel Dunbar8eb018a2009-02-16 22:43:43 +00005845 }
Mike Stumpca6c8752009-07-27 19:14:18 +00005846
Chris Lattner8977c432009-12-30 22:06:22 +00005847 if (Context.BuiltinInfo.isNoThrow(BuiltinID))
Alexis Huntdcfba7b2010-08-18 23:23:40 +00005848 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
Chris Lattner8977c432009-12-30 22:06:22 +00005849 if (Context.BuiltinInfo.isConst(BuiltinID))
Alexis Huntdcfba7b2010-08-18 23:23:40 +00005850 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Douglas Gregore711f702009-02-14 18:57:46 +00005851 }
5852
5853 IdentifierInfo *Name = FD->getIdentifier();
5854 if (!Name)
5855 return;
Mike Stump11289f42009-09-09 15:08:12 +00005856 if ((!getLangOptions().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +00005857 FD->getDeclContext()->isTranslationUnit()) ||
5858 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +00005859 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregore711f702009-02-14 18:57:46 +00005860 LinkageSpecDecl::lang_c)) {
5861 // Okay: this could be a libc/libm/Objective-C function we know
5862 // about.
5863 } else
5864 return;
5865
Douglas Gregorfedd4282009-04-22 20:56:09 +00005866 if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
Mike Stump82a9e442009-07-28 00:07:08 +00005867 // FIXME: NSLog and NSLogv should be target specific
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005868 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
Douglas Gregore711f702009-02-14 18:57:46 +00005869 // FIXME: We known better than our headers.
Ted Kremenek7f4945a2010-02-11 05:28:37 +00005870 const_cast<FormatAttr *>(Format)->setType(Context, "printf");
Mike Stump11289f42009-09-09 15:08:12 +00005871 } else
Alexis Huntdcfba7b2010-08-18 23:23:40 +00005872 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
5873 "printf", 1,
Eli Friedmanf4799842009-06-10 04:01:38 +00005874 Name->isStr("NSLogv") ? 0 : 2));
Douglas Gregorfedd4282009-04-22 20:56:09 +00005875 } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump82a9e442009-07-28 00:07:08 +00005876 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump11289f42009-09-09 15:08:12 +00005877 // target-specific builtins, perhaps?
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005878 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00005879 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
5880 "printf", 2,
Eli Friedmanf4799842009-06-10 04:01:38 +00005881 Name->isStr("vasprintf") ? 0 : 3));
Mike Stumpa4de80b2009-07-28 02:25:19 +00005882 }
Douglas Gregore711f702009-02-14 18:57:46 +00005883}
Chris Lattner302b4be2006-11-19 02:31:38 +00005884
John McCall703a3f82009-10-24 08:00:42 +00005885TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCallbcd03502009-12-07 02:54:59 +00005886 TypeSourceInfo *TInfo) {
Chris Lattner776fac82007-06-09 00:53:06 +00005887 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +00005888 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump11289f42009-09-09 15:08:12 +00005889
John McCallbcd03502009-12-07 02:54:59 +00005890 if (!TInfo) {
John McCall703a3f82009-10-24 08:00:42 +00005891 assert(D.isInvalidType() && "no declarator info for valid type");
John McCallbcd03502009-12-07 02:54:59 +00005892 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCall703a3f82009-10-24 08:00:42 +00005893 }
5894
Chris Lattner18b19622007-01-22 07:39:13 +00005895 // Scope manipulation handled by caller.
Chris Lattnerc5ffed42008-04-04 06:12:32 +00005896 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00005897 D.getSourceRange().getBegin(),
Chris Lattnerc5ffed42008-04-04 06:12:32 +00005898 D.getIdentifierLoc(),
Mike Stump11289f42009-09-09 15:08:12 +00005899 D.getIdentifier(),
John McCallbcd03502009-12-07 02:54:59 +00005900 TInfo);
Mike Stump11289f42009-09-09 15:08:12 +00005901
John McCall04fcd0d2011-02-01 08:20:08 +00005902 // Bail out immediately if we have an invalid declaration.
5903 if (D.isInvalidType()) {
5904 NewTD->setInvalidDecl();
5905 return NewTD;
Anders Carlsson02751152009-03-10 17:07:44 +00005906 }
5907
John McCall04fcd0d2011-02-01 08:20:08 +00005908 // C++ [dcl.typedef]p8:
5909 // If the typedef declaration defines an unnamed class (or
5910 // enum), the first typedef-name declared by the declaration
5911 // to be that class type (or enum type) is used to denote the
5912 // class type (or enum type) for linkage purposes only.
5913 // We need to check whether the type was declared in the declaration.
5914 switch (D.getDeclSpec().getTypeSpecType()) {
5915 case TST_enum:
5916 case TST_struct:
5917 case TST_union:
5918 case TST_class: {
5919 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
5920
5921 // Do nothing if the tag is not anonymous or already has an
5922 // associated typedef (from an earlier typedef in this decl group).
5923 if (tagFromDeclSpec->getIdentifier()) break;
5924 if (tagFromDeclSpec->getTypedefForAnonDecl()) break;
5925
5926 // A well-formed anonymous tag must always be a TUK_Definition.
5927 assert(tagFromDeclSpec->isThisDeclarationADefinition());
5928
5929 // The type must match the tag exactly; no qualifiers allowed.
5930 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
5931 break;
5932
5933 // Otherwise, set this is the anon-decl typedef for the tag.
5934 tagFromDeclSpec->setTypedefForAnonDecl(NewTD);
5935 break;
5936 }
5937
5938 default:
5939 break;
5940 }
5941
Steve Narofff93b6722007-08-28 20:14:24 +00005942 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +00005943}
5944
Douglas Gregord9034f02009-05-14 16:41:31 +00005945
5946/// \brief Determine whether a tag with a given kind is acceptable
5947/// as a redeclaration of the given tag declaration.
5948///
5949/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00005950bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Abramo Bagnara6150c882010-05-11 21:36:43 +00005951 TagTypeKind NewTag,
Douglas Gregord9034f02009-05-14 16:41:31 +00005952 SourceLocation NewTagLoc,
5953 const IdentifierInfo &Name) {
5954 // C++ [dcl.type.elab]p3:
5955 // The class-key or enum keyword present in the
5956 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara6150c882010-05-11 21:36:43 +00005957 // declaration to which the name in the elaborated-type-specifier
Douglas Gregord9034f02009-05-14 16:41:31 +00005958 // refers. This rule also applies to the form of
5959 // elaborated-type-specifier that declares a class-name or
5960 // friend class since it can be construed as referring to the
5961 // definition of the class. Thus, in any
5962 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara6150c882010-05-11 21:36:43 +00005963 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregord9034f02009-05-14 16:41:31 +00005964 // used to refer to a union (clause 9), and either the class or
5965 // struct class-key shall be used to refer to a class (clause 9)
5966 // declared using the class or struct class-key.
Abramo Bagnara6150c882010-05-11 21:36:43 +00005967 TagTypeKind OldTag = Previous->getTagKind();
Douglas Gregord9034f02009-05-14 16:41:31 +00005968 if (OldTag == NewTag)
5969 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005970
Abramo Bagnara6150c882010-05-11 21:36:43 +00005971 if ((OldTag == TTK_Struct || OldTag == TTK_Class) &&
5972 (NewTag == TTK_Struct || NewTag == TTK_Class)) {
Douglas Gregord9034f02009-05-14 16:41:31 +00005973 // Warn about the struct/class tag mismatch.
5974 bool isTemplate = false;
5975 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
5976 isTemplate = Record->getDescribedClassTemplate();
5977
5978 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Abramo Bagnara6150c882010-05-11 21:36:43 +00005979 << (NewTag == TTK_Class)
Douglas Gregord9034f02009-05-14 16:41:31 +00005980 << isTemplate << &Name
Douglas Gregora771f462010-03-31 17:46:05 +00005981 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
Abramo Bagnara6150c882010-05-11 21:36:43 +00005982 OldTag == TTK_Class? "class" : "struct");
Douglas Gregord9034f02009-05-14 16:41:31 +00005983 Diag(Previous->getLocation(), diag::note_previous_use);
5984 return true;
5985 }
5986 return false;
5987}
5988
Steve Naroff30d242c2007-09-15 18:49:24 +00005989/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +00005990/// former case, Name will be non-null. In the later case, Name will be null.
John McCall9bb74a52009-07-31 02:45:11 +00005991/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Chris Lattner1300fb92007-01-23 23:42:53 +00005992/// reference/declaration/definition of a tag.
John McCall48871652010-08-21 09:40:31 +00005993Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor009f6992010-09-16 23:58:57 +00005994 SourceLocation KWLoc, CXXScopeSpec &SS,
5995 IdentifierInfo *Name, SourceLocation NameLoc,
5996 AttributeList *Attr, AccessSpecifier AS,
5997 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00005998 bool &OwnedDecl, bool &IsDependent,
5999 bool ScopedEnum, bool ScopedEnumUsesClassTag,
Douglas Gregor0bf31402010-10-08 23:50:27 +00006000 TypeResult UnderlyingType) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006001 // If this is not a definition, it must have a name.
John McCall9bb74a52009-07-31 02:45:11 +00006002 assert((Name != 0 || TUK == TUK_Definition) &&
Chris Lattner7b9ace62007-01-23 20:11:08 +00006003 "Nameless record must be a definition!");
John McCallace48cd2010-10-19 01:40:49 +00006004 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregorded2d7b2009-02-04 19:02:06 +00006005
Douglas Gregord6ab8742009-05-28 23:31:59 +00006006 OwnedDecl = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +00006007 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00006008
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006009 // FIXME: Check explicit specializations more carefully.
6010 bool isExplicitSpecialization = false;
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006011 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006012 bool Invalid = false;
John McCallace48cd2010-10-19 01:40:49 +00006013
6014 // We only need to do this matching if we have template parameters
6015 // or a scope specifier, which also conveniently avoids this work
6016 // for non-C++ cases.
6017 if (NumMatchedTemplateParamLists ||
6018 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Douglas Gregore93e46c2009-07-22 23:48:44 +00006019 if (TemplateParameterList *TemplateParams
6020 = MatchTemplateParametersToScopeSpecifier(KWLoc, SS,
John McCallc9739e32010-10-16 07:23:36 +00006021 TemplateParameterLists.get(),
6022 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00006023 TUK == TUK_Friend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006024 isExplicitSpecialization,
6025 Invalid)) {
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006026 // All but one template parameter lists have been matching.
6027 --NumMatchedTemplateParamLists;
6028
Douglas Gregor3dad8422009-09-26 06:47:28 +00006029 if (TemplateParams->size() > 0) {
Douglas Gregore93e46c2009-07-22 23:48:44 +00006030 // This is a declaration or definition of a class template (which may
6031 // be a member of another template).
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006032 if (Invalid)
John McCall48871652010-08-21 09:40:31 +00006033 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00006034
Douglas Gregore93e46c2009-07-22 23:48:44 +00006035 OwnedDecl = false;
John McCall9bb74a52009-07-31 02:45:11 +00006036 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +00006037 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00006038 TemplateParams, AS,
6039 NumMatchedTemplateParamLists,
6040 (TemplateParameterList**) TemplateParameterLists.release());
Douglas Gregore93e46c2009-07-22 23:48:44 +00006041 return Result.get();
6042 } else {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006043 // The "template<>" header is extraneous.
6044 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara6150c882010-05-11 21:36:43 +00006045 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006046 isExplicitSpecialization = true;
Douglas Gregore93e46c2009-07-22 23:48:44 +00006047 }
Mike Stump11289f42009-09-09 15:08:12 +00006048 }
6049 }
6050
Douglas Gregor0bf31402010-10-08 23:50:27 +00006051 // Figure out the underlying type if this a enum declaration. We need to do
6052 // this early, because it's needed to detect if this is an incompatible
6053 // redeclaration.
6054 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
6055
6056 if (Kind == TTK_Enum) {
6057 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
6058 // No underlying type explicitly specified, or we failed to parse the
6059 // type, default to int.
6060 EnumUnderlying = Context.IntTy.getTypePtr();
6061 else if (UnderlyingType.get()) {
6062 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
6063 // integral type; any cv-qualification is ignored.
6064 TypeSourceInfo *TI = 0;
6065 QualType T = GetTypeFromParser(UnderlyingType.get(), &TI);
6066 EnumUnderlying = TI;
6067
6068 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
6069
6070 if (!T->isDependentType() && !T->isIntegralType(Context)) {
6071 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
6072 << T;
6073 // Recover by falling back to int.
6074 EnumUnderlying = Context.IntTy.getTypePtr();
6075 }
Douglas Gregor2b988fd2010-12-16 00:24:44 +00006076
6077 if (DiagnoseUnexpandedParameterPack(UnderlyingLoc, TI,
6078 UPPC_FixedUnderlyingType))
6079 EnumUnderlying = Context.IntTy.getTypePtr();
6080
Francois Picheta3108062010-10-18 15:01:13 +00006081 } else if (getLangOptions().Microsoft)
6082 // Microsoft enums are always of int type.
6083 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006084 }
6085
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00006086 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00006087 DeclContext *DC = CurContext;
Douglas Gregor87f54062009-09-15 22:30:29 +00006088 bool isStdBadAlloc = false;
Douglas Gregordee1be82009-01-17 00:42:38 +00006089
Chandler Carrutha419dbb2010-03-01 21:17:36 +00006090 RedeclarationKind Redecl = ForRedeclaration;
6091 if (TUK == TUK_Friend || TUK == TUK_Reference)
6092 Redecl = NotForRedeclaration;
John McCall1f82f242009-11-18 22:49:29 +00006093
6094 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
John McCall6538c932009-10-10 05:48:19 +00006095
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00006096 if (Name && SS.isNotEmpty()) {
6097 // We have a nested-name tag ('struct foo::bar').
6098
6099 // Check for invalid 'foo::'.
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00006100 if (SS.isInvalid()) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00006101 Name = 0;
6102 goto CreateNewDecl;
6103 }
6104
John McCall7f41d982009-09-11 04:59:25 +00006105 // If this is a friend or a reference to a class in a dependent
6106 // context, don't try to make a decl for it.
6107 if (TUK == TUK_Friend || TUK == TUK_Reference) {
6108 DC = computeDeclContext(SS, false);
6109 if (!DC) {
6110 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +00006111 return 0;
John McCall7f41d982009-09-11 04:59:25 +00006112 }
John McCall0b66eb32010-05-01 00:40:08 +00006113 } else {
6114 DC = computeDeclContext(SS, true);
6115 if (!DC) {
6116 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
6117 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00006118 return 0;
John McCall0b66eb32010-05-01 00:40:08 +00006119 }
John McCall7f41d982009-09-11 04:59:25 +00006120 }
6121
John McCall0b66eb32010-05-01 00:40:08 +00006122 if (RequireCompleteDeclContext(SS, DC))
John McCall48871652010-08-21 09:40:31 +00006123 return 0;
Douglas Gregor2ec748c2009-05-14 00:28:11 +00006124
Douglas Gregor8761da52009-02-03 00:34:39 +00006125 SearchDC = DC;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00006126 // Look-up name inside 'foo::'.
John McCall1f82f242009-11-18 22:49:29 +00006127 LookupQualifiedName(Previous, DC);
John McCall6538c932009-10-10 05:48:19 +00006128
John McCall1f82f242009-11-18 22:49:29 +00006129 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006130 return 0;
John McCall6538c932009-10-10 05:48:19 +00006131
John McCall1f82f242009-11-18 22:49:29 +00006132 if (Previous.empty()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00006133 // Name lookup did not find anything. However, if the
6134 // nested-name-specifier refers to the current instantiation,
6135 // and that current instantiation has any dependent base
6136 // classes, we might find something at instantiation time: treat
6137 // this as a dependent elaborated-type-specifier.
John McCallace48cd2010-10-19 01:40:49 +00006138 // But this only makes any sense for reference-like lookups.
6139 if (Previous.wasNotFoundInCurrentInstantiation() &&
6140 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00006141 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +00006142 return 0;
Douglas Gregord2e6a452010-01-14 17:47:39 +00006143 }
6144
6145 // A tag 'foo::bar' must already exist.
Douglas Gregorf5af3582010-03-31 23:17:41 +00006146 Diag(NameLoc, diag::err_not_tag_in_scope)
6147 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00006148 Name = 0;
Douglas Gregorb8006faf2009-05-27 17:30:49 +00006149 Invalid = true;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00006150 goto CreateNewDecl;
6151 }
Chris Lattnerd9773512009-01-21 02:38:50 +00006152 } else if (Name) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00006153 // If this is a named struct, check to see if there was a previous forward
6154 // declaration or definition.
Douglas Gregor889ceb72009-02-03 19:21:40 +00006155 // FIXME: We're looking into outer scopes here, even when we
6156 // shouldn't be. Doing so can result in ambiguities that we
6157 // shouldn't be diagnosing.
John McCall1f82f242009-11-18 22:49:29 +00006158 LookupName(Previous, S);
6159
6160 // Note: there used to be some attempt at recovery here.
6161 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006162 return 0;
Douglas Gregor82ac25e2009-01-08 20:45:30 +00006163
John McCall9bb74a52009-07-31 02:45:11 +00006164 if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor82ac25e2009-01-08 20:45:30 +00006165 // FIXME: This makes sure that we ignore the contexts associated
6166 // with C structs, unions, and enums when looking for a matching
6167 // tag declaration or definition. See the similar lookup tweak
Douglas Gregored8f2882009-01-30 01:04:22 +00006168 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00006169 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
6170 SearchDC = SearchDC->getParent();
Douglas Gregor82ac25e2009-01-08 20:45:30 +00006171 }
Douglas Gregor009f6992010-09-16 23:58:57 +00006172 } else if (S->isFunctionPrototypeScope()) {
6173 // If this is an enum declaration in function prototype scope, set its
6174 // initial context to the translation unit.
6175 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00006176 }
6177
John McCall1f82f242009-11-18 22:49:29 +00006178 if (Previous.isSingleResult() &&
6179 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00006180 // Maybe we will complain about the shadowed template parameter.
John McCall1f82f242009-11-18 22:49:29 +00006181 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor5101c242008-12-05 18:15:24 +00006182 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00006183 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00006184 }
6185
Douglas Gregor87f54062009-09-15 22:30:29 +00006186 if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006187 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor87f54062009-09-15 22:30:29 +00006188 // This is a declaration of or a reference to "std::bad_alloc".
6189 isStdBadAlloc = true;
6190
John McCall1f82f242009-11-18 22:49:29 +00006191 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor87f54062009-09-15 22:30:29 +00006192 // std::bad_alloc has been implicitly declared (but made invisible to
6193 // name lookup). Fill in this implicit declaration as the previous
6194 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006195 Previous.addDecl(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +00006196 }
6197 }
John McCall1f82f242009-11-18 22:49:29 +00006198
John McCalle9eaf8e2010-03-25 21:28:06 +00006199 // If we didn't find a previous declaration, and this is a reference
6200 // (or friend reference), move to the correct scope. In C++, we
6201 // also need to do a redeclaration lookup there, just in case
6202 // there's a shadow friend decl.
6203 if (Name && Previous.empty() &&
6204 (TUK == TUK_Reference || TUK == TUK_Friend)) {
6205 if (Invalid) goto CreateNewDecl;
6206 assert(SS.isEmpty());
6207
6208 if (TUK == TUK_Reference) {
6209 // C++ [basic.scope.pdecl]p5:
6210 // -- for an elaborated-type-specifier of the form
6211 //
6212 // class-key identifier
6213 //
6214 // if the elaborated-type-specifier is used in the
6215 // decl-specifier-seq or parameter-declaration-clause of a
6216 // function defined in namespace scope, the identifier is
6217 // declared as a class-name in the namespace that contains
6218 // the declaration; otherwise, except as a friend
6219 // declaration, the identifier is declared in the smallest
6220 // non-class, non-function-prototype scope that contains the
6221 // declaration.
6222 //
6223 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
6224 // C structs and unions.
6225 //
6226 // It is an error in C++ to declare (rather than define) an enum
6227 // type, including via an elaborated type specifier. We'll
6228 // diagnose that later; for now, declare the enum in the same
6229 // scope as we would have picked for any other tag type.
6230 //
6231 // GNU C also supports this behavior as part of its incomplete
6232 // enum types extension, while GNU C++ does not.
6233 //
6234 // Find the context where we'll be declaring the tag.
6235 // FIXME: We would like to maintain the current DeclContext as the
6236 // lexical context,
Rafael Espindola9e976dc2011-01-20 02:26:24 +00006237 while (SearchDC->isRecord() || SearchDC->isTransparentContext())
John McCalle9eaf8e2010-03-25 21:28:06 +00006238 SearchDC = SearchDC->getParent();
6239
6240 // Find the scope where we'll be declaring the tag.
6241 while (S->isClassScope() ||
6242 (getLangOptions().CPlusPlus &&
6243 S->isFunctionPrototypeScope()) ||
6244 ((S->getFlags() & Scope::DeclScope) == 0) ||
6245 (S->getEntity() &&
6246 ((DeclContext *)S->getEntity())->isTransparentContext()))
6247 S = S->getParent();
6248 } else {
6249 assert(TUK == TUK_Friend);
6250 // C++ [namespace.memdef]p3:
6251 // If a friend declaration in a non-local class first declares a
6252 // class or function, the friend class or function is a member of
6253 // the innermost enclosing namespace.
6254 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCalle9eaf8e2010-03-25 21:28:06 +00006255 }
6256
John McCalle87beb22010-04-23 18:46:30 +00006257 // In C++, we need to do a redeclaration lookup to properly
6258 // diagnose some problems.
John McCalle9eaf8e2010-03-25 21:28:06 +00006259 if (getLangOptions().CPlusPlus) {
6260 Previous.setRedeclarationKind(ForRedeclaration);
6261 LookupQualifiedName(Previous, SearchDC);
6262 }
6263 }
6264
John McCall1f82f242009-11-18 22:49:29 +00006265 if (!Previous.empty()) {
Douglas Gregorce40e2e2010-04-12 16:00:01 +00006266 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
John McCalle87beb22010-04-23 18:46:30 +00006267
6268 // It's okay to have a tag decl in the same scope as a typedef
6269 // which hides a tag decl in the same scope. Finding this
6270 // insanity with a redeclaration lookup can only actually happen
6271 // in C++.
6272 //
6273 // This is also okay for elaborated-type-specifiers, which is
6274 // technically forbidden by the current standard but which is
6275 // okay according to the likely resolution of an open issue;
6276 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
6277 if (getLangOptions().CPlusPlus) {
6278 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(PrevDecl)) {
6279 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
6280 TagDecl *Tag = TT->getDecl();
6281 if (Tag->getDeclName() == Name &&
Sebastian Redl50c68252010-08-31 00:36:30 +00006282 Tag->getDeclContext()->getRedeclContext()
6283 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCalle87beb22010-04-23 18:46:30 +00006284 PrevDecl = Tag;
6285 Previous.clear();
6286 Previous.addDecl(Tag);
Douglas Gregorfcee9462010-08-27 22:55:10 +00006287 Previous.resolveKind();
John McCalle87beb22010-04-23 18:46:30 +00006288 }
6289 }
6290 }
6291 }
6292
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006293 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +00006294 // If this is a use of a previous tag, or if the tag is already declared
6295 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006296 // rementions the tag), reuse the decl.
John McCall07e91c02009-08-06 02:15:43 +00006297 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Douglas Gregordb446112011-03-07 16:54:27 +00006298 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +00006299 // Make sure that this wasn't declared as an enum and now used as a
6300 // struct or something similar.
Douglas Gregord9034f02009-05-14 16:41:31 +00006301 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00006302 bool SafeToContinue
Abramo Bagnara6150c882010-05-11 21:36:43 +00006303 = (PrevTagDecl->getTagKind() != TTK_Enum &&
6304 Kind != TTK_Enum);
Douglas Gregor170512f2009-04-01 23:51:29 +00006305 if (SafeToContinue)
Mike Stump11289f42009-09-09 15:08:12 +00006306 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00006307 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00006308 << FixItHint::CreateReplacement(SourceRange(KWLoc),
6309 PrevTagDecl->getKindName());
Douglas Gregor170512f2009-04-01 23:51:29 +00006310 else
6311 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall1f82f242009-11-18 22:49:29 +00006312 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00006313
Mike Stump11289f42009-09-09 15:08:12 +00006314 if (SafeToContinue)
Douglas Gregor170512f2009-04-01 23:51:29 +00006315 Kind = PrevTagDecl->getTagKind();
6316 else {
6317 // Recover by making this an anonymous redefinition.
6318 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00006319 Previous.clear();
Douglas Gregor170512f2009-04-01 23:51:29 +00006320 Invalid = true;
6321 }
6322 }
6323
Douglas Gregor0bf31402010-10-08 23:50:27 +00006324 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
6325 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
6326
6327 // All conflicts with previous declarations are recovered by
6328 // returning the previous declaration.
6329 if (ScopedEnum != PrevEnum->isScoped()) {
6330 Diag(KWLoc, diag::err_enum_redeclare_scoped_mismatch)
6331 << PrevEnum->isScoped();
6332 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
6333 return PrevTagDecl;
6334 }
6335 else if (EnumUnderlying && PrevEnum->isFixed()) {
6336 QualType T;
6337 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
6338 T = TI->getType();
6339 else
6340 T = QualType(EnumUnderlying.get<const Type*>(), 0);
6341
6342 if (!Context.hasSameUnqualifiedType(T, PrevEnum->getIntegerType())) {
Douglas Gregor1a099ba2010-12-01 16:10:38 +00006343 Diag(NameLoc.isValid() ? NameLoc : KWLoc,
6344 diag::err_enum_redeclare_type_mismatch)
6345 << T
6346 << PrevEnum->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006347 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
6348 return PrevTagDecl;
6349 }
6350 }
6351 else if (!EnumUnderlying.isNull() != PrevEnum->isFixed()) {
6352 Diag(KWLoc, diag::err_enum_redeclare_fixed_mismatch)
6353 << PrevEnum->isFixed();
6354 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
6355 return PrevTagDecl;
6356 }
6357 }
6358
Douglas Gregor170512f2009-04-01 23:51:29 +00006359 if (!Invalid) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006360 // If this is a use, just return the declaration we found.
Chris Lattner9ff58d72008-07-03 03:30:58 +00006361
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006362 // FIXME: In the future, return a variant or some other clue
6363 // for the consumer of this Decl to know it doesn't own it.
6364 // For our current ASTs this shouldn't be a problem, but will
6365 // need to be changed with DeclGroups.
Douglas Gregor6f2e0952010-06-08 21:27:36 +00006366 if ((TUK == TUK_Reference && !PrevTagDecl->getFriendObjectKind()) ||
6367 TUK == TUK_Friend)
John McCall48871652010-08-21 09:40:31 +00006368 return PrevTagDecl;
Douglas Gregorded2d7b2009-02-04 19:02:06 +00006369
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006370 // Diagnose attempts to redefine a tag.
John McCall9bb74a52009-07-31 02:45:11 +00006371 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00006372 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00006373 // If we're defining a specialization and the previous definition
6374 // is from an implicit instantiation, don't emit an error
6375 // here; we'll catch this in the general case below.
6376 if (!isExplicitSpecialization ||
6377 !isa<CXXRecordDecl>(Def) ||
6378 cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
6379 == TSK_ExplicitSpecialization) {
6380 Diag(NameLoc, diag::err_redefinition) << Name;
6381 Diag(Def->getLocation(), diag::note_previous_definition);
6382 // If this is a redefinition, recover by making this
6383 // struct be anonymous, which will make any later
6384 // references get the previous definition.
6385 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00006386 Previous.clear();
Douglas Gregor06db9f52009-10-12 20:18:28 +00006387 Invalid = true;
6388 }
Douglas Gregordee1be82009-01-17 00:42:38 +00006389 } else {
6390 // If the type is currently being defined, complain
6391 // about a nested redefinition.
John McCall424cec92011-01-19 06:33:43 +00006392 const TagType *Tag
6393 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregordee1be82009-01-17 00:42:38 +00006394 if (Tag->isBeingDefined()) {
6395 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump11289f42009-09-09 15:08:12 +00006396 Diag(PrevTagDecl->getLocation(),
Douglas Gregordee1be82009-01-17 00:42:38 +00006397 diag::note_previous_definition);
6398 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00006399 Previous.clear();
Douglas Gregordee1be82009-01-17 00:42:38 +00006400 Invalid = true;
6401 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006402 }
Douglas Gregordee1be82009-01-17 00:42:38 +00006403
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006404 // Okay, this is definition of a previously declared or referenced
6405 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregordee1be82009-01-17 00:42:38 +00006406 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006407 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006408 // If we get here we have (another) forward declaration or we
John McCall07e91c02009-08-06 02:15:43 +00006409 // have a definition. Just create a new decl.
6410
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006411 } else {
6412 // If we get here, this is a definition of a new tag type in a nested
Mike Stump11289f42009-09-09 15:08:12 +00006413 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006414 // new decl/type. We set PrevDecl to NULL so that the entities
6415 // have distinct types.
John McCall1f82f242009-11-18 22:49:29 +00006416 Previous.clear();
Chris Lattner7b9ace62007-01-23 20:11:08 +00006417 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006418 // If we get here, we're going to create a new Decl. If PrevDecl
6419 // is non-NULL, it's a definition of the tag declared by
6420 // PrevDecl. If it's NULL, we have a new definition.
John McCalle87beb22010-04-23 18:46:30 +00006421
6422
6423 // Otherwise, PrevDecl is not a tag, but was found with tag
6424 // lookup. This is only actually possible in C++, where a few
6425 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006426 } else {
John McCalle87beb22010-04-23 18:46:30 +00006427 assert(getLangOptions().CPlusPlus);
6428
6429 // Use a better diagnostic if an elaborated-type-specifier
6430 // found the wrong kind of type on the first
6431 // (non-redeclaration) lookup.
6432 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
6433 !Previous.isForRedeclaration()) {
6434 unsigned Kind = 0;
6435 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
6436 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 2;
6437 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
6438 Diag(PrevDecl->getLocation(), diag::note_declared_at);
6439 Invalid = true;
6440
6441 // Otherwise, only diagnose if the declaration is in scope.
Douglas Gregordb446112011-03-07 16:54:27 +00006442 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
6443 isExplicitSpecialization)) {
John McCalle87beb22010-04-23 18:46:30 +00006444 // do nothing
6445
6446 // Diagnose implicit declarations introduced by elaborated types.
6447 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
6448 unsigned Kind = 0;
6449 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
6450 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 2;
6451 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
6452 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
6453 Invalid = true;
6454
6455 // Otherwise it's a declaration. Call out a particularly common
6456 // case here.
6457 } else if (isa<TypedefDecl>(PrevDecl)) {
6458 Diag(NameLoc, diag::err_tag_definition_of_typedef)
6459 << Name
6460 << cast<TypedefDecl>(PrevDecl)->getUnderlyingType();
6461 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
6462 Invalid = true;
6463
6464 // Otherwise, diagnose.
6465 } else {
6466 // The tag name clashes with something else in the target scope,
6467 // issue an error and recover by making this tag be anonymous.
Chris Lattner4bd8dd82008-11-19 08:23:25 +00006468 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner0369c572008-11-23 23:12:31 +00006469 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +00006470 Name = 0;
Douglas Gregordee1be82009-01-17 00:42:38 +00006471 Invalid = true;
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +00006472 }
John McCalle87beb22010-04-23 18:46:30 +00006473
6474 // The existing declaration isn't relevant to us; we're in a
6475 // new scope, so clear out the previous declaration.
6476 Previous.clear();
Chris Lattner8799cf22007-01-23 01:57:16 +00006477 }
Chris Lattner18b19622007-01-22 07:39:13 +00006478 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00006479
Chris Lattner438e5012008-12-17 07:13:27 +00006480CreateNewDecl:
Mike Stump11289f42009-09-09 15:08:12 +00006481
John McCall1f82f242009-11-18 22:49:29 +00006482 TagDecl *PrevDecl = 0;
6483 if (Previous.isSingleResult())
6484 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
6485
Chris Lattnerbf0b7982007-01-23 04:27:41 +00006486 // If there is an identifier, use the location of the identifier as the
6487 // location of the decl, otherwise use the location of the struct/union
6488 // keyword.
6489 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump11289f42009-09-09 15:08:12 +00006490
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006491 // Otherwise, create a new declaration. If there is a previous
6492 // declaration of the same entity, the two will be linked via
6493 // PrevDecl.
Chris Lattner7b9ace62007-01-23 20:11:08 +00006494 TagDecl *New;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00006495
Douglas Gregor0bf31402010-10-08 23:50:27 +00006496 bool IsForwardReference = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +00006497 if (Kind == TTK_Enum) {
Chris Lattner776fac82007-06-09 00:53:06 +00006498 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
6499 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006500 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor0bf31402010-10-08 23:50:27 +00006501 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00006502 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Chris Lattner5f521502007-01-25 06:27:24 +00006503 // If this is an undefined enum, warn.
Douglas Gregorc9ea2d52010-06-22 14:26:35 +00006504 if (TUK != TUK_Definition && !Invalid) {
6505 TagDecl *Def;
Douglas Gregor0bf31402010-10-08 23:50:27 +00006506 if (getLangOptions().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) {
6507 // C++0x: 7.2p2: opaque-enum-declaration.
6508 // Conflicts are diagnosed above. Do nothing.
6509 }
6510 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorc9ea2d52010-06-22 14:26:35 +00006511 Diag(Loc, diag::ext_forward_ref_enum_def)
6512 << New;
6513 Diag(Def->getLocation(), diag::note_previous_definition);
6514 } else {
Francois Pichet488b4a72010-09-12 05:06:55 +00006515 unsigned DiagID = diag::ext_forward_ref_enum;
6516 if (getLangOptions().Microsoft)
6517 DiagID = diag::ext_ms_forward_ref_enum;
6518 else if (getLangOptions().CPlusPlus)
6519 DiagID = diag::err_forward_ref_enum;
6520 Diag(Loc, DiagID);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006521
6522 // If this is a forward-declared reference to an enumeration, make a
6523 // note of it; we won't actually be introducing the declaration into
6524 // the declaration context.
6525 if (TUK == TUK_Reference)
6526 IsForwardReference = true;
Douglas Gregorc9ea2d52010-06-22 14:26:35 +00006527 }
Douglas Gregord45b93b2009-03-06 18:34:03 +00006528 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00006529
6530 if (EnumUnderlying) {
6531 EnumDecl *ED = cast<EnumDecl>(New);
6532 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
6533 ED->setIntegerTypeSourceInfo(TI);
6534 else
6535 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
6536 ED->setPromotionType(ED->getIntegerType());
6537 }
6538
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00006539 } else {
6540 // struct/union/class
6541
Chris Lattner776fac82007-06-09 00:53:06 +00006542 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
6543 // struct X { int A; } D; D should chain to X.
Douglas Gregor87f54062009-09-15 22:30:29 +00006544 if (getLangOptions().CPlusPlus) {
Ted Kremenek6ddf53e2008-09-05 17:39:33 +00006545 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006546 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006547 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006548
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006549 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor87f54062009-09-15 22:30:29 +00006550 StdBadAlloc = cast<CXXRecordDecl>(New);
6551 } else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006552 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006553 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006554 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006555
John McCall3e11ebe2010-03-15 10:12:16 +00006556 // Maybe add qualifier info.
6557 if (SS.isNotEmpty()) {
Fariborz Jahanian862fac92010-05-14 21:35:02 +00006558 if (SS.isSet()) {
Douglas Gregor14454802011-02-25 02:25:35 +00006559 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006560 if (NumMatchedTemplateParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00006561 New->setTemplateParameterListsInfo(Context,
6562 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00006563 (TemplateParameterList**) TemplateParameterLists.release());
6564 }
Fariborz Jahanian862fac92010-05-14 21:35:02 +00006565 }
6566 else
6567 Invalid = true;
John McCall3e11ebe2010-03-15 10:12:16 +00006568 }
6569
Daniel Dunbar8804f2e2010-05-27 01:53:40 +00006570 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
6571 // Add alignment attributes if necessary; these attributes are checked when
6572 // the ASTContext lays out the structure.
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006573 //
6574 // It is important for implementing the correct semantics that this
6575 // happen here (in act on tag decl). The #pragma pack stack is
6576 // maintained as a result of parser callbacks which can occur at
6577 // many points during the parsing of a struct declaration (because
6578 // the #pragma tokens are effectively skipped over during the
6579 // parsing of the struct).
Daniel Dunbar8804f2e2010-05-27 01:53:40 +00006580 AddAlignmentAttributesForRecord(RD);
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006581 }
6582
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006583 // If this is a specialization of a member class (of a class template),
6584 // check the specialization.
John McCall1f82f242009-11-18 22:49:29 +00006585 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006586 Invalid = true;
Daniel Dunbar8804f2e2010-05-27 01:53:40 +00006587
Douglas Gregordee1be82009-01-17 00:42:38 +00006588 if (Invalid)
6589 New->setInvalidDecl();
6590
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006591 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00006592 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006593
Douglas Gregordee1be82009-01-17 00:42:38 +00006594 // If we're declaring or defining a tag in function prototype scope
6595 // in C, note that this type can only be used within the function.
Douglas Gregor658b9552009-01-09 22:42:13 +00006596 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
6597 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
6598
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006599 // Set the lexical context. If the tag has a C++ scope specifier, the
6600 // lexical context will be different from the semantic context.
Douglas Gregor8761da52009-02-03 00:34:39 +00006601 New->setLexicalDeclContext(CurContext);
Douglas Gregordee1be82009-01-17 00:42:38 +00006602
John McCallaa74a0c2009-08-28 07:59:38 +00006603 // Mark this as a friend decl if applicable.
6604 if (TUK == TUK_Friend)
John McCall1f82f242009-11-18 22:49:29 +00006605 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty());
John McCallaa74a0c2009-08-28 07:59:38 +00006606
Anders Carlsson5558ca12009-03-26 01:19:02 +00006607 // Set the access specifier.
John McCalle9eaf8e2010-03-25 21:28:06 +00006608 if (!Invalid && SearchDC->isRecord())
Douglas Gregorb8006faf2009-05-27 17:30:49 +00006609 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor6c2adff2009-03-25 22:00:53 +00006610
John McCall9bb74a52009-07-31 02:45:11 +00006611 if (TUK == TUK_Definition)
Douglas Gregordee1be82009-01-17 00:42:38 +00006612 New->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00006613
Chris Lattner18b19622007-01-22 07:39:13 +00006614 // If this has an identifier, add it to the scope stack.
John McCall2dc078f2009-09-02 00:55:30 +00006615 if (TUK == TUK_Friend) {
John McCallf8bd8612009-09-02 19:32:14 +00006616 // We might be replacing an existing declaration in the lookup tables;
6617 // if so, borrow its access specifier.
6618 if (PrevDecl)
6619 New->setAccess(PrevDecl->getAccess());
6620
Sebastian Redl50c68252010-08-31 00:36:30 +00006621 DeclContext *DC = New->getDeclContext()->getRedeclContext();
John McCalle9eaf8e2010-03-25 21:28:06 +00006622 DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
6623 if (Name) // can be null along some error paths
John McCall2dc078f2009-09-02 00:55:30 +00006624 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
6625 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCall2dc078f2009-09-02 00:55:30 +00006626 } else if (Name) {
Douglas Gregor45a33ec2009-01-12 18:45:55 +00006627 S = getNonFieldDeclScope(S);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006628 PushOnScopeChains(New, S, !IsForwardReference);
6629 if (IsForwardReference)
6630 SearchDC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
6631
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00006632 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006633 CurContext->addDecl(New);
Chris Lattner18b19622007-01-22 07:39:13 +00006634 }
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00006635
Douglas Gregor27821ce2009-07-07 16:35:42 +00006636 // If this is the C FILE type, notify the AST context.
6637 if (IdentifierInfo *II = New->getIdentifier())
6638 if (!New->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00006639 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor27821ce2009-07-07 16:35:42 +00006640 II->isStr("FILE"))
6641 Context.setFILEDecl(New);
Mike Stump11289f42009-09-09 15:08:12 +00006642
Douglas Gregord6ab8742009-05-28 23:31:59 +00006643 OwnedDecl = true;
John McCall48871652010-08-21 09:40:31 +00006644 return New;
Chris Lattner18b19622007-01-22 07:39:13 +00006645}
Chris Lattner1300fb92007-01-23 23:42:53 +00006646
John McCall48871652010-08-21 09:40:31 +00006647void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00006648 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00006649 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregorba41d012010-04-24 16:38:41 +00006650
Douglas Gregor82ac25e2009-01-08 20:45:30 +00006651 // Enter the tag context.
6652 PushDeclContext(S, Tag);
John McCall1c7e6ec2009-12-20 07:58:13 +00006653}
Douglas Gregor82ac25e2009-01-08 20:45:30 +00006654
John McCall48871652010-08-21 09:40:31 +00006655void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlssonfc1eef42011-01-22 17:51:53 +00006656 ClassVirtSpecifiers &CVS,
John McCall1c7e6ec2009-12-20 07:58:13 +00006657 SourceLocation LBraceLoc) {
6658 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00006659 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00006660
John McCall1c7e6ec2009-12-20 07:58:13 +00006661 FieldCollector->StartClass();
6662
6663 if (!Record->getIdentifier())
6664 return;
6665
Anders Carlsson1eb95962011-01-24 16:26:15 +00006666 if (CVS.isFinalSpecified())
6667 Record->addAttr(new (Context) FinalAttr(CVS.getFinalLoc(), Context));
6668 if (CVS.isExplicitSpecified())
6669 Record->addAttr(new (Context) ExplicitAttr(CVS.getExplicitLoc(), Context));
Anders Carlssonfc1eef42011-01-22 17:51:53 +00006670
John McCall1c7e6ec2009-12-20 07:58:13 +00006671 // C++ [class]p2:
6672 // [...] The class-name is also inserted into the scope of the
6673 // class itself; this is known as the injected-class-name. For
6674 // purposes of access checking, the injected-class-name is treated
6675 // as if it were a public member name.
6676 CXXRecordDecl *InjectedClassName
Abramo Bagnara29c2d462011-03-09 14:09:51 +00006677 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
6678 Record->getLocStart(), Record->getLocation(),
John McCall1c7e6ec2009-12-20 07:58:13 +00006679 Record->getIdentifier(),
Argyrios Kyrtzidis470c4542010-10-14 20:14:21 +00006680 /*PrevDecl=*/0,
6681 /*DelayTypeCreation=*/true);
6682 Context.getTypeDeclType(InjectedClassName, Record);
John McCall1c7e6ec2009-12-20 07:58:13 +00006683 InjectedClassName->setImplicit();
6684 InjectedClassName->setAccess(AS_public);
6685 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
6686 InjectedClassName->setDescribedClassTemplate(Template);
6687 PushOnScopeChains(InjectedClassName, S);
6688 assert(InjectedClassName->isInjectedClassName() &&
6689 "Broken injected-class-name");
Douglas Gregor82ac25e2009-01-08 20:45:30 +00006690}
6691
John McCall48871652010-08-21 09:40:31 +00006692void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +00006693 SourceLocation RBraceLoc) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00006694 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00006695 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +00006696 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00006697
6698 if (isa<CXXRecordDecl>(Tag))
6699 FieldCollector->FinishClass();
6700
6701 // Exit this scope of this tag's definition.
6702 PopDeclContext();
Douglas Gregor859f0ae2010-01-06 17:00:51 +00006703
Douglas Gregor82ac25e2009-01-08 20:45:30 +00006704 // Notify the consumer that we've defined a tag.
6705 Consumer.HandleTagDeclDefinition(Tag);
6706}
Chris Lattner535b8302008-06-21 19:39:06 +00006707
John McCall48871652010-08-21 09:40:31 +00006708void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCall2ff380a2010-03-17 00:38:33 +00006709 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00006710 TagDecl *Tag = cast<TagDecl>(TagD);
John McCall2ff380a2010-03-17 00:38:33 +00006711 Tag->setInvalidDecl();
6712
John McCall71ba5f22010-03-17 19:25:57 +00006713 // We're undoing ActOnTagStartDefinition here, not
6714 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
6715 // the FieldCollector.
John McCall2ff380a2010-03-17 00:38:33 +00006716
6717 PopDeclContext();
6718}
6719
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00006720// Note that FieldName may be null for anonymous bitfields.
Mike Stump11289f42009-09-09 15:08:12 +00006721bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Eli Friedmanc96d4962009-08-15 21:55:26 +00006722 QualType FieldTy, const Expr *BitWidth,
6723 bool *ZeroWidth) {
6724 // Default to true; that shouldn't confuse checks for emptiness
6725 if (ZeroWidth)
6726 *ZeroWidth = true;
6727
Chris Lattner73bf7b42009-03-05 22:45:59 +00006728 // C99 6.7.2.1p4 - verify the field type.
Chris Lattnerd26760a2009-03-05 23:01:03 +00006729 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregorb90df602010-06-16 00:17:44 +00006730 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner73bf7b42009-03-05 22:45:59 +00006731 // Handle incomplete types with specific error.
Douglas Gregor81457422009-03-10 21:58:27 +00006732 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
6733 return true;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00006734 if (FieldName)
6735 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
6736 << FieldName << FieldTy << BitWidth->getSourceRange();
6737 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
6738 << FieldTy << BitWidth->getSourceRange();
Douglas Gregora02a72a2010-12-15 23:18:36 +00006739 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
6740 UPPC_BitFieldWidth))
6741 return true;
Douglas Gregor1efa4372009-03-11 18:59:21 +00006742
6743 // If the bit-width is type- or value-dependent, don't try to check
6744 // it now.
6745 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
6746 return false;
6747
Anders Carlsson5df391e2008-12-06 20:33:04 +00006748 llvm::APSInt Value;
6749 if (VerifyIntegerConstantExpression(BitWidth, &Value))
6750 return true;
6751
Eli Friedmanc96d4962009-08-15 21:55:26 +00006752 if (Value != 0 && ZeroWidth)
6753 *ZeroWidth = false;
6754
Chris Lattner81ed6802008-12-12 04:56:04 +00006755 // Zero-width bitfield is ok for anonymous field.
6756 if (Value == 0 && FieldName)
6757 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00006758
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00006759 if (Value.isSigned() && Value.isNegative()) {
6760 if (FieldName)
Mike Stump11289f42009-09-09 15:08:12 +00006761 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00006762 << FieldName << Value.toString(10);
6763 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
6764 << Value.toString(10);
6765 }
Anders Carlsson5df391e2008-12-06 20:33:04 +00006766
Douglas Gregor1efa4372009-03-11 18:59:21 +00006767 if (!FieldTy->isDependentType()) {
6768 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00006769 if (Value.getZExtValue() > TypeSize) {
Anders Carlssond5635fe2010-04-16 15:16:32 +00006770 if (!getLangOptions().CPlusPlus) {
6771 if (FieldName)
6772 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
6773 << FieldName << (unsigned)Value.getZExtValue()
6774 << (unsigned)TypeSize;
6775
6776 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
6777 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
6778 }
6779
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00006780 if (FieldName)
Anders Carlssond5635fe2010-04-16 15:16:32 +00006781 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
6782 << FieldName << (unsigned)Value.getZExtValue()
6783 << (unsigned)TypeSize;
6784 else
6785 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
6786 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00006787 }
Douglas Gregor1efa4372009-03-11 18:59:21 +00006788 }
Anders Carlsson5df391e2008-12-06 20:33:04 +00006789
6790 return false;
6791}
6792
Steve Naroff30d242c2007-09-15 18:49:24 +00006793/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +00006794/// to create a FieldDecl object for it.
John McCall48871652010-08-21 09:40:31 +00006795Decl *Sema::ActOnField(Scope *S, Decl *TagD,
Mike Stump11289f42009-09-09 15:08:12 +00006796 SourceLocation DeclStart,
Chris Lattner83f095c2009-03-28 19:18:32 +00006797 Declarator &D, ExprTy *BitfieldWidth) {
John McCall48871652010-08-21 09:40:31 +00006798 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattner83f095c2009-03-28 19:18:32 +00006799 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
6800 AS_public);
John McCall48871652010-08-21 09:40:31 +00006801 return Res;
Chris Lattner73bf7b42009-03-05 22:45:59 +00006802}
6803
6804/// HandleField - Analyze a field of a C struct or a C++ data member.
6805///
6806FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
6807 SourceLocation DeclStart,
Douglas Gregor4261e4c2009-03-11 20:50:30 +00006808 Declarator &D, Expr *BitWidth,
6809 AccessSpecifier AS) {
Chris Lattner1300fb92007-01-23 23:42:53 +00006810 IdentifierInfo *II = D.getIdentifier();
Chris Lattner1300fb92007-01-23 23:42:53 +00006811 SourceLocation Loc = DeclStart;
6812 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +00006813
John McCall8cb7bdf2010-06-04 23:28:52 +00006814 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6815 QualType T = TInfo->getType();
Douglas Gregora02a72a2010-12-15 23:18:36 +00006816 if (getLangOptions().CPlusPlus) {
Douglas Gregor1efa4372009-03-11 18:59:21 +00006817 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00006818
Douglas Gregora02a72a2010-12-15 23:18:36 +00006819 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6820 UPPC_DataMemberType)) {
6821 D.setInvalidType();
6822 T = Context.IntTy;
6823 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
6824 }
6825 }
6826
Eli Friedman574c7452009-04-07 19:37:57 +00006827 DiagnoseFunctionSpecifiers(D);
6828
Eli Friedmand5c0eed2009-04-19 20:27:55 +00006829 if (D.getDeclSpec().isThreadSpecified())
6830 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
Douglas Gregor2c7d9292010-08-30 14:32:14 +00006831
6832 // Check to see if this name was declared as a member previously
6833 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
6834 LookupName(Previous, S);
6835 assert((Previous.empty() || Previous.isOverloadedResult() ||
6836 Previous.isSingleResult())
6837 && "Lookup of member name should be either overloaded, single or null");
Eli Friedmand5c0eed2009-04-19 20:27:55 +00006838
Douglas Gregor2c7d9292010-08-30 14:32:14 +00006839 // If the name is overloaded then get any declaration else get the single result
6840 NamedDecl *PrevDecl = Previous.isOverloadedResult() ?
6841 Previous.getRepresentativeDecl() : Previous.getAsSingle<NamedDecl>();
Douglas Gregorf187420f2009-06-17 23:37:01 +00006842
6843 if (PrevDecl && PrevDecl->isTemplateParameter()) {
6844 // Maybe we will complain about the shadowed template parameter.
6845 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
6846 // Just pretend that we didn't see the previous declaration.
6847 PrevDecl = 0;
6848 }
6849
Douglas Gregor1efa4372009-03-11 18:59:21 +00006850 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
6851 PrevDecl = 0;
6852
Steve Naroff5ec6ff72009-07-14 14:58:18 +00006853 bool Mutable
6854 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
6855 SourceLocation TSSL = D.getSourceRange().getBegin();
6856 FieldDecl *NewFD
John McCallbcd03502009-12-07 02:54:59 +00006857 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, TSSL,
Steve Naroff5ec6ff72009-07-14 14:58:18 +00006858 AS, PrevDecl, &D);
Rafael Espindola568586f2010-03-21 22:56:43 +00006859
6860 if (NewFD->isInvalidDecl())
6861 Record->setInvalidDecl();
6862
Douglas Gregor1efa4372009-03-11 18:59:21 +00006863 if (NewFD->isInvalidDecl() && PrevDecl) {
6864 // Don't introduce NewFD into scope; there's already something
6865 // with the same name in the same scope.
6866 } else if (II) {
6867 PushOnScopeChains(NewFD, S);
6868 } else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006869 Record->addDecl(NewFD);
Douglas Gregor1efa4372009-03-11 18:59:21 +00006870
6871 return NewFD;
6872}
6873
6874/// \brief Build a new FieldDecl and check its well-formedness.
6875///
6876/// This routine builds a new FieldDecl given the fields name, type,
6877/// record, etc. \p PrevDecl should refer to any previous declaration
6878/// with the same name and in the same scope as the field to be
6879/// created.
6880///
6881/// \returns a new FieldDecl.
6882///
Mike Stump11289f42009-09-09 15:08:12 +00006883/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00006884FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCallbcd03502009-12-07 02:54:59 +00006885 TypeSourceInfo *TInfo,
Douglas Gregor1efa4372009-03-11 18:59:21 +00006886 RecordDecl *Record, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00006887 bool Mutable, Expr *BitWidth,
Steve Naroff5ec6ff72009-07-14 14:58:18 +00006888 SourceLocation TSSL,
Douglas Gregor4261e4c2009-03-11 20:50:30 +00006889 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor1efa4372009-03-11 18:59:21 +00006890 Declarator *D) {
6891 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Narofff93b6722007-08-28 20:14:24 +00006892 bool InvalidDecl = false;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006893 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006894
Douglas Gregor1efa4372009-03-11 18:59:21 +00006895 // If we receive a broken type, recover by assuming 'int' and
6896 // marking this declaration as invalid.
6897 if (T.isNull()) {
6898 InvalidDecl = true;
6899 T = Context.IntTy;
6900 }
6901
Eli Friedmand0e8de22009-12-07 00:22:08 +00006902 QualType EltTy = Context.getBaseElementType(T);
6903 if (!EltTy->isDependentType() &&
John McCall2677e102010-08-16 23:42:35 +00006904 RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
6905 // Fields of incomplete type force their record to be invalid.
6906 Record->setInvalidDecl();
Eli Friedmand0e8de22009-12-07 00:22:08 +00006907 InvalidDecl = true;
John McCall2677e102010-08-16 23:42:35 +00006908 }
Eli Friedmand0e8de22009-12-07 00:22:08 +00006909
Steve Naroff8eeeb132007-05-08 21:09:37 +00006910 // C99 6.7.2.1p8: A member of a structure or union may have any type other
6911 // than a variably modified type.
Eli Friedmand0e8de22009-12-07 00:22:08 +00006912 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00006913 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00006914 llvm::APSInt Oversized;
Eli Friedmana3b1d032009-02-21 00:44:51 +00006915 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00006916 SizeIsNegative,
6917 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00006918 if (!FixedTy.isNull()) {
6919 Diag(Loc, diag::warn_illegal_constant_array_size);
6920 T = FixedTy;
6921 } else {
6922 if (SizeIsNegative)
6923 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00006924 else if (Oversized.getBoolValue())
6925 Diag(Loc, diag::err_array_too_large)
6926 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00006927 else
6928 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00006929 InvalidDecl = true;
6930 }
Steve Naroff8eeeb132007-05-08 21:09:37 +00006931 }
Mike Stump11289f42009-09-09 15:08:12 +00006932
Anders Carlsson576cc6f2009-03-22 20:18:17 +00006933 // Fields can not have abstract class types
Eli Friedmand0e8de22009-12-07 00:22:08 +00006934 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
6935 diag::err_abstract_type_in_decl,
6936 AbstractFieldType))
Anders Carlsson576cc6f2009-03-22 20:18:17 +00006937 InvalidDecl = true;
Mike Stump11289f42009-09-09 15:08:12 +00006938
Eli Friedmanc96d4962009-08-15 21:55:26 +00006939 bool ZeroWidth = false;
Douglas Gregor1efa4372009-03-11 18:59:21 +00006940 // If this is declared as a bit-field, check the bit-field.
Eli Friedmand0e8de22009-12-07 00:22:08 +00006941 if (!InvalidDecl && BitWidth &&
6942 VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
Douglas Gregor1efa4372009-03-11 18:59:21 +00006943 InvalidDecl = true;
Douglas Gregor1efa4372009-03-11 18:59:21 +00006944 BitWidth = 0;
Eli Friedmanc96d4962009-08-15 21:55:26 +00006945 ZeroWidth = false;
Anders Carlsson5df391e2008-12-06 20:33:04 +00006946 }
Mike Stump11289f42009-09-09 15:08:12 +00006947
John McCallb1cd7da2010-06-04 08:34:12 +00006948 // Check that 'mutable' is consistent with the type of the declaration.
6949 if (!InvalidDecl && Mutable) {
6950 unsigned DiagID = 0;
6951 if (T->isReferenceType())
6952 DiagID = diag::err_mutable_reference;
6953 else if (T.isConstQualified())
6954 DiagID = diag::err_mutable_const;
6955
6956 if (DiagID) {
6957 SourceLocation ErrLoc = Loc;
6958 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
6959 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
6960 Diag(ErrLoc, DiagID);
6961 Mutable = false;
6962 InvalidDecl = true;
6963 }
6964 }
6965
Abramo Bagnaradff19302011-03-08 08:55:46 +00006966 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00006967 BitWidth, Mutable);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006968 if (InvalidDecl)
6969 NewFD->setInvalidDecl();
Douglas Gregor91f84212008-12-11 16:49:14 +00006970
Douglas Gregor1efa4372009-03-11 18:59:21 +00006971 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
6972 Diag(Loc, diag::err_duplicate_member) << II;
6973 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
6974 NewFD->setInvalidDecl();
Douglas Gregor82ac25e2009-01-08 20:45:30 +00006975 }
6976
John McCall67da35c2010-02-04 22:26:26 +00006977 if (!InvalidDecl && getLangOptions().CPlusPlus) {
Anders Carlsson2ceb3472010-11-07 19:13:55 +00006978 if (Record->isUnion()) {
6979 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
6980 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
6981 if (RDecl->getDefinition()) {
6982 // C++ [class.union]p1: An object of a class with a non-trivial
6983 // constructor, a non-trivial copy constructor, a non-trivial
6984 // destructor, or a non-trivial copy assignment operator
6985 // cannot be a member of a union, nor can an array of such
6986 // objects.
6987 // TODO: C++0x alters this restriction significantly.
6988 if (CheckNontrivialField(NewFD))
6989 NewFD->setInvalidDecl();
6990 }
6991 }
6992
6993 // C++ [class.union]p1: If a union contains a member of reference type,
6994 // the program is ill-formed.
6995 if (EltTy->isReferenceType()) {
6996 Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
6997 << NewFD->getDeclName() << EltTy;
6998 NewFD->setInvalidDecl();
Douglas Gregor8a273912009-07-22 18:25:24 +00006999 }
7000 }
7001 }
7002
Douglas Gregor1efa4372009-03-11 18:59:21 +00007003 // FIXME: We need to pass in the attributes given an AST
7004 // representation, not a parser representation.
7005 if (D)
Douglas Gregor758a8692009-06-17 21:51:59 +00007006 // FIXME: What to pass instead of TUScope?
7007 ProcessDeclAttributes(TUScope, NewFD, *D);
Douglas Gregor1efa4372009-03-11 18:59:21 +00007008
Fariborz Jahaniand29fecd2009-02-19 00:22:47 +00007009 if (T.isObjCGCWeak())
Fariborz Jahaniand35c7922009-02-18 18:14:41 +00007010 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlsson28e71082008-02-16 00:29:18 +00007011
Douglas Gregor4261e4c2009-03-11 20:50:30 +00007012 NewFD->setAccess(AS);
Steve Narofff93b6722007-08-28 20:14:24 +00007013 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +00007014}
7015
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00007016bool Sema::CheckNontrivialField(FieldDecl *FD) {
7017 assert(FD);
7018 assert(getLangOptions().CPlusPlus && "valid check only for C++");
7019
7020 if (FD->isInvalidDecl())
7021 return true;
7022
7023 QualType EltTy = Context.getBaseElementType(FD->getType());
7024 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
7025 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
7026 if (RDecl->getDefinition()) {
7027 // We check for copy constructors before constructors
7028 // because otherwise we'll never get complaints about
7029 // copy constructors.
7030
7031 CXXSpecialMember member = CXXInvalid;
7032 if (!RDecl->hasTrivialCopyConstructor())
7033 member = CXXCopyConstructor;
7034 else if (!RDecl->hasTrivialConstructor())
7035 member = CXXConstructor;
7036 else if (!RDecl->hasTrivialCopyAssignment())
7037 member = CXXCopyAssignment;
7038 else if (!RDecl->hasTrivialDestructor())
7039 member = CXXDestructor;
7040
7041 if (member != CXXInvalid) {
7042 Diag(FD->getLocation(), diag::err_illegal_union_or_anon_struct_member)
7043 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
7044 DiagnoseNontrivial(RT, member);
7045 return true;
7046 }
7047 }
7048 }
7049
7050 return false;
7051}
7052
Douglas Gregor8a273912009-07-22 18:25:24 +00007053/// DiagnoseNontrivial - Given that a class has a non-trivial
7054/// special member, figure out why.
7055void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
7056 QualType QT(T, 0U);
7057 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
7058
7059 // Check whether the member was user-declared.
7060 switch (member) {
Douglas Gregorfceea362010-04-22 14:36:26 +00007061 case CXXInvalid:
7062 break;
7063
Anders Carlsson05bf0092010-04-22 05:40:53 +00007064 case CXXConstructor:
Douglas Gregor8a273912009-07-22 18:25:24 +00007065 if (RD->hasUserDeclaredConstructor()) {
7066 typedef CXXRecordDecl::ctor_iterator ctor_iter;
Sebastian Redle24b1622009-10-25 22:31:45 +00007067 for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
7068 const FunctionDecl *body = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007069 ci->hasBody(body);
Anders Carlssonb7229932010-04-20 23:32:58 +00007070 if (!body || !cast<CXXConstructorDecl>(body)->isImplicitlyDefined()) {
Douglas Gregor8a273912009-07-22 18:25:24 +00007071 SourceLocation CtorLoc = ci->getLocation();
7072 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
7073 return;
7074 }
Sebastian Redle24b1622009-10-25 22:31:45 +00007075 }
Douglas Gregor8a273912009-07-22 18:25:24 +00007076
7077 assert(0 && "found no user-declared constructors");
7078 return;
7079 }
7080 break;
7081
7082 case CXXCopyConstructor:
7083 if (RD->hasUserDeclaredCopyConstructor()) {
7084 SourceLocation CtorLoc =
7085 RD->getCopyConstructor(Context, 0)->getLocation();
7086 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
7087 return;
7088 }
7089 break;
7090
7091 case CXXCopyAssignment:
7092 if (RD->hasUserDeclaredCopyAssignment()) {
7093 // FIXME: this should use the location of the copy
7094 // assignment, not the type.
7095 SourceLocation TyLoc = RD->getSourceRange().getBegin();
7096 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
7097 return;
7098 }
7099 break;
7100
7101 case CXXDestructor:
7102 if (RD->hasUserDeclaredDestructor()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00007103 SourceLocation DtorLoc = LookupDestructor(RD)->getLocation();
Douglas Gregor8a273912009-07-22 18:25:24 +00007104 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
7105 return;
7106 }
7107 break;
7108 }
7109
7110 typedef CXXRecordDecl::base_class_iterator base_iter;
7111
7112 // Virtual bases and members inhibit trivial copying/construction,
7113 // but not trivial destruction.
7114 if (member != CXXDestructor) {
7115 // Check for virtual bases. vbases includes indirect virtual bases,
7116 // so we just iterate through the direct bases.
7117 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
7118 if (bi->isVirtual()) {
7119 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
7120 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
7121 return;
7122 }
7123
7124 // Check for virtual methods.
7125 typedef CXXRecordDecl::method_iterator meth_iter;
7126 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
7127 ++mi) {
7128 if (mi->isVirtual()) {
7129 SourceLocation MLoc = mi->getSourceRange().getBegin();
7130 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
7131 return;
7132 }
7133 }
7134 }
Mike Stump11289f42009-09-09 15:08:12 +00007135
Douglas Gregor8a273912009-07-22 18:25:24 +00007136 bool (CXXRecordDecl::*hasTrivial)() const;
7137 switch (member) {
Anders Carlsson05bf0092010-04-22 05:40:53 +00007138 case CXXConstructor:
Douglas Gregor8a273912009-07-22 18:25:24 +00007139 hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break;
7140 case CXXCopyConstructor:
7141 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
7142 case CXXCopyAssignment:
7143 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
7144 case CXXDestructor:
7145 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
7146 default:
7147 assert(0 && "unexpected special member"); return;
7148 }
7149
7150 // Check for nontrivial bases (and recurse).
7151 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007152 const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
Sebastian Redl1054fae2009-10-25 17:03:50 +00007153 assert(BaseRT && "Don't know how to handle dependent bases");
Douglas Gregor8a273912009-07-22 18:25:24 +00007154 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
7155 if (!(BaseRecTy->*hasTrivial)()) {
7156 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
7157 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
7158 DiagnoseNontrivial(BaseRT, member);
7159 return;
7160 }
7161 }
Mike Stump11289f42009-09-09 15:08:12 +00007162
Douglas Gregor8a273912009-07-22 18:25:24 +00007163 // Check for nontrivial members (and recurse).
7164 typedef RecordDecl::field_iterator field_iter;
7165 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
7166 ++fi) {
Douglas Gregor79f83ed2009-07-23 23:49:00 +00007167 QualType EltTy = Context.getBaseElementType((*fi)->getType());
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007168 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
Douglas Gregor8a273912009-07-22 18:25:24 +00007169 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
7170
7171 if (!(EltRD->*hasTrivial)()) {
7172 SourceLocation FLoc = (*fi)->getLocation();
7173 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
7174 DiagnoseNontrivial(EltRT, member);
7175 return;
7176 }
7177 }
7178 }
7179
7180 assert(0 && "found no explanation for non-trivial member");
7181}
7182
Mike Stump11289f42009-09-09 15:08:12 +00007183/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00007184/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007185static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00007186TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +00007187 switch (ivarVisibility) {
Chris Lattner79ef8432008-10-12 00:28:42 +00007188 default: assert(0 && "Unknown visitibility kind");
7189 case tok::objc_private: return ObjCIvarDecl::Private;
7190 case tok::objc_public: return ObjCIvarDecl::Public;
7191 case tok::objc_protected: return ObjCIvarDecl::Protected;
7192 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroff2e688fd2007-09-14 23:09:53 +00007193 }
7194}
7195
Mike Stump11289f42009-09-09 15:08:12 +00007196/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian96376742008-04-11 16:55:42 +00007197/// in order to create an IvarDecl object for it.
John McCall48871652010-08-21 09:40:31 +00007198Decl *Sema::ActOnIvar(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00007199 SourceLocation DeclStart,
John McCall48871652010-08-21 09:40:31 +00007200 Decl *IntfDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00007201 Declarator &D, ExprTy *BitfieldWidth,
7202 tok::ObjCKeywordKind Visibility) {
Mike Stump11289f42009-09-09 15:08:12 +00007203
Fariborz Jahaniande615832008-04-10 23:32:45 +00007204 IdentifierInfo *II = D.getIdentifier();
7205 Expr *BitWidth = (Expr*)BitfieldWidth;
7206 SourceLocation Loc = DeclStart;
7207 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +00007208
Fariborz Jahaniande615832008-04-10 23:32:45 +00007209 // FIXME: Unnamed fields can be handled in various different ways, for
7210 // example, unnamed unions inject all members into the struct namespace!
Mike Stump11289f42009-09-09 15:08:12 +00007211
John McCall8cb7bdf2010-06-04 23:28:52 +00007212 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
7213 QualType T = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00007214
Fariborz Jahaniande615832008-04-10 23:32:45 +00007215 if (BitWidth) {
Steve Naroff17b2f5d2009-02-20 17:57:11 +00007216 // 6.7.2.1p3, 6.7.2.1p4
Chris Lattner73bf7b42009-03-05 22:45:59 +00007217 if (VerifyBitField(Loc, II, T, BitWidth)) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007218 D.setInvalidType();
Chris Lattner73bf7b42009-03-05 22:45:59 +00007219 BitWidth = 0;
7220 }
Fariborz Jahaniande615832008-04-10 23:32:45 +00007221 } else {
7222 // Not a bitfield.
Mike Stump11289f42009-09-09 15:08:12 +00007223
Fariborz Jahaniande615832008-04-10 23:32:45 +00007224 // validate II.
Mike Stump11289f42009-09-09 15:08:12 +00007225
Fariborz Jahaniande615832008-04-10 23:32:45 +00007226 }
Fariborz Jahanian0103d672010-04-26 22:07:03 +00007227 if (T->isReferenceType()) {
7228 Diag(Loc, diag::err_ivar_reference_type);
7229 D.setInvalidType();
7230 }
Fariborz Jahaniande615832008-04-10 23:32:45 +00007231 // C99 6.7.2.1p8: A member of a structure or union may have any type other
7232 // than a variably modified type.
Fariborz Jahanian0103d672010-04-26 22:07:03 +00007233 else if (T->isVariablyModifiedType()) {
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +00007234 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007235 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +00007236 }
Mike Stump11289f42009-09-09 15:08:12 +00007237
Ted Kremenek73295fa2008-07-23 18:04:17 +00007238 // Get the visibility (access control) for this ivar.
Mike Stump11289f42009-09-09 15:08:12 +00007239 ObjCIvarDecl::AccessControl ac =
Ted Kremenek73295fa2008-07-23 18:04:17 +00007240 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
7241 : ObjCIvarDecl::None;
Fariborz Jahanian68453832009-06-05 18:16:35 +00007242 // Must set ivar's DeclContext to its enclosing interface.
John McCall48871652010-08-21 09:40:31 +00007243 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(IntfDecl);
Daniel Dunbar229385c2010-04-02 18:29:09 +00007244 ObjCContainerDecl *EnclosingContext;
Mike Stump11289f42009-09-09 15:08:12 +00007245 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian68453832009-06-05 18:16:35 +00007246 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +00007247 if (!LangOpts.ObjCNonFragileABI2) {
Fariborz Jahanian68453832009-06-05 18:16:35 +00007248 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +00007249 EnclosingContext = IMPDecl->getClassInterface();
7250 assert(EnclosingContext && "Implementation has no class interface!");
7251 }
7252 else
7253 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00007254 } else {
7255 if (ObjCCategoryDecl *CDecl =
7256 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
7257 if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) {
7258 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCall48871652010-08-21 09:40:31 +00007259 return 0;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00007260 }
7261 }
Daniel Dunbar229385c2010-04-02 18:29:09 +00007262 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00007263 }
Mike Stump11289f42009-09-09 15:08:12 +00007264
Ted Kremenek73295fa2008-07-23 18:04:17 +00007265 // Construct the decl.
Abramo Bagnaradff19302011-03-08 08:55:46 +00007266 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
7267 DeclStart, Loc, II, T,
John McCallbcd03502009-12-07 02:54:59 +00007268 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump11289f42009-09-09 15:08:12 +00007269
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007270 if (II) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00007271 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall5cebab12009-11-18 07:57:50 +00007272 ForRedeclaration);
Fariborz Jahanian68453832009-06-05 18:16:35 +00007273 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007274 && !isa<TagDecl>(PrevDecl)) {
7275 Diag(Loc, diag::err_duplicate_member) << II;
7276 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
7277 NewID->setInvalidDecl();
7278 }
7279 }
7280
Ted Kremenek73295fa2008-07-23 18:04:17 +00007281 // Process attributes attached to the ivar.
Douglas Gregor758a8692009-06-17 21:51:59 +00007282 ProcessDeclAttributes(S, NewID, D);
Mike Stump11289f42009-09-09 15:08:12 +00007283
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007284 if (D.isInvalidType())
Fariborz Jahaniande615832008-04-10 23:32:45 +00007285 NewID->setInvalidDecl();
Ted Kremenek73295fa2008-07-23 18:04:17 +00007286
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007287 if (II) {
7288 // FIXME: When interfaces are DeclContexts, we'll need to add
7289 // these to the interface.
John McCall48871652010-08-21 09:40:31 +00007290 S->AddDecl(NewID);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007291 IdResolver.AddDecl(NewID);
7292 }
7293
John McCall48871652010-08-21 09:40:31 +00007294 return NewID;
Fariborz Jahaniande615832008-04-10 23:32:45 +00007295}
7296
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00007297/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
7298/// class and class extensions. For every class @interface and class
7299/// extension @interface, if the last ivar is a bitfield of any type,
7300/// then add an implicit `char :0` ivar to the end of that interface.
7301void Sema::ActOnLastBitfield(SourceLocation DeclLoc, Decl *EnclosingDecl,
7302 llvm::SmallVectorImpl<Decl *> &AllIvarDecls) {
7303 if (!LangOpts.ObjCNonFragileABI2 || AllIvarDecls.empty())
7304 return;
7305
7306 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
7307 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
7308
7309 if (!Ivar->isBitField())
7310 return;
7311 uint64_t BitFieldSize =
7312 Ivar->getBitWidth()->EvaluateAsInt(Context).getZExtValue();
7313 if (BitFieldSize == 0)
7314 return;
7315 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl);
7316 if (!ID) {
7317 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
7318 if (!CD->IsClassExtension())
7319 return;
7320 }
7321 // No need to add this to end of @implementation.
7322 else
7323 return;
7324 }
7325 // All conditions are met. Add a new bitfield to the tail end of ivars.
7326 llvm::APInt Zero(Context.getTypeSize(Context.CharTy), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007327 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.CharTy, DeclLoc);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00007328
7329 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(EnclosingDecl),
Abramo Bagnaradff19302011-03-08 08:55:46 +00007330 DeclLoc, DeclLoc, 0,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00007331 Context.CharTy,
7332 Context.CreateTypeSourceInfo(Context.CharTy),
7333 ObjCIvarDecl::Private, BW,
7334 true);
7335 AllIvarDecls.push_back(Ivar);
7336}
7337
Fariborz Jahanian343f7092007-09-29 00:54:24 +00007338void Sema::ActOnFields(Scope* S,
John McCall48871652010-08-21 09:40:31 +00007339 SourceLocation RecLoc, Decl *EnclosingDecl,
7340 Decl **Fields, unsigned NumFields,
Daniel Dunbar15619c72008-10-03 02:03:53 +00007341 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar325601a2008-10-03 17:33:35 +00007342 AttributeList *Attr) {
Steve Naroffdb47ee22007-09-14 22:20:54 +00007343 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump11289f42009-09-09 15:08:12 +00007344
Chris Lattnerd13b8b52009-02-23 22:00:08 +00007345 // If the decl this is being inserted into is invalid, then it may be a
7346 // redeclaration or some other bogus case. Don't try to add fields to it.
7347 if (EnclosingDecl->isInvalidDecl()) {
7348 // FIXME: Deallocate fields?
7349 return;
7350 }
7351
Mike Stump11289f42009-09-09 15:08:12 +00007352
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00007353 // Verify that all the fields are okay.
Chris Lattner82625602007-01-24 02:26:21 +00007354 unsigned NumNamedMembers = 0;
Chris Lattner23b7eb62007-06-15 23:05:46 +00007355 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorf4d33272009-01-07 19:46:03 +00007356
Chris Lattnerd13b8b52009-02-23 22:00:08 +00007357 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00007358 for (unsigned i = 0; i != NumFields; ++i) {
John McCall48871652010-08-21 09:40:31 +00007359 FieldDecl *FD = cast<FieldDecl>(Fields[i]);
Mike Stump11289f42009-09-09 15:08:12 +00007360
Chris Lattner720a0542007-01-25 00:44:24 +00007361 // Get the type for the field.
John McCall424cec92011-01-19 06:33:43 +00007362 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorf4d33272009-01-07 19:46:03 +00007363
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007364 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00007365 // Remember all fields written by the user.
7366 RecFields.push_back(FD);
7367 }
Mike Stump11289f42009-09-09 15:08:12 +00007368
Chris Lattner73bf7b42009-03-05 22:45:59 +00007369 // If the field is already invalid for some reason, don't emit more
7370 // diagnostics about it.
Eli Friedmand0e8de22009-12-07 00:22:08 +00007371 if (FD->isInvalidDecl()) {
7372 EnclosingDecl->setInvalidDecl();
Chris Lattner73bf7b42009-03-05 22:45:59 +00007373 continue;
Eli Friedmand0e8de22009-12-07 00:22:08 +00007374 }
Mike Stump11289f42009-09-09 15:08:12 +00007375
Douglas Gregorac1fb652009-03-24 19:52:54 +00007376 // C99 6.7.2.1p2:
7377 // A structure or union shall not contain a member with
7378 // incomplete or function type (hence, a structure shall not
7379 // contain an instance of itself, but may contain a pointer to
7380 // an instance of itself), except that the last member of a
7381 // structure with more than one named member may have incomplete
7382 // array type; such a structure (and any union containing,
7383 // possibly recursively, a member that is such a structure)
7384 // shall not be a member of a structure or an element of an
7385 // array.
Chris Lattner0fd893e2007-07-31 21:33:24 +00007386 if (FDTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00007387 // Field declared as a function.
Chris Lattner651d42d2008-11-20 06:38:18 +00007388 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007389 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +00007390 FD->setInvalidDecl();
7391 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00007392 continue;
Francois Pichetf657b632010-09-15 00:14:08 +00007393 } else if (FDTy->isIncompleteArrayType() && Record &&
7394 ((i == NumFields - 1 && !Record->isUnion()) ||
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00007395 ((getLangOptions().Microsoft || getLangOptions().CPlusPlus) &&
Francois Pichetf657b632010-09-15 00:14:08 +00007396 (i == NumFields - 1 || Record->isUnion())))) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00007397 // Flexible array member.
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00007398 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichetf657b632010-09-15 00:14:08 +00007399 // It will accept flexible array in union and also
Anders Carlsson0ea10472010-10-17 23:36:12 +00007400 // as the sole element of a struct/class.
Francois Pichetf657b632010-09-15 00:14:08 +00007401 if (getLangOptions().Microsoft) {
7402 if (Record->isUnion())
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00007403 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
Francois Pichetf657b632010-09-15 00:14:08 +00007404 << FD->getDeclName();
7405 else if (NumFields == 1)
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00007406 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
Francois Pichetf657b632010-09-15 00:14:08 +00007407 << FD->getDeclName() << Record->getTagKind();
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00007408 } else if (getLangOptions().CPlusPlus) {
7409 if (Record->isUnion())
7410 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
7411 << FD->getDeclName();
7412 else if (NumFields == 1)
7413 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
7414 << FD->getDeclName() << Record->getTagKind();
7415 } else if (NumNamedMembers < 1) {
Chris Lattner651d42d2008-11-20 06:38:18 +00007416 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00007417 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +00007418 FD->setInvalidDecl();
7419 EnclosingDecl->setInvalidDecl();
Chris Lattner82625602007-01-24 02:26:21 +00007420 continue;
7421 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00007422 if (!FD->getType()->isDependentType() &&
7423 !Context.getBaseElementType(FD->getType())->isPODType()) {
7424 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
Fariborz Jahanianb0e28472010-05-26 20:46:24 +00007425 << FD->getDeclName() << FD->getType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00007426 FD->setInvalidDecl();
7427 EnclosingDecl->setInvalidDecl();
7428 continue;
7429 }
Chris Lattner720a0542007-01-25 00:44:24 +00007430 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00007431 if (Record)
7432 Record->setHasFlexibleArrayMember(true);
Douglas Gregorac1fb652009-03-24 19:52:54 +00007433 } else if (!FDTy->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00007434 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregorac1fb652009-03-24 19:52:54 +00007435 diag::err_field_incomplete)) {
7436 // Incomplete type
7437 FD->setInvalidDecl();
7438 EnclosingDecl->setInvalidDecl();
7439 continue;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007440 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Chris Lattner720a0542007-01-25 00:44:24 +00007441 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
7442 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00007443 if (Record && Record->isUnion()) {
Chris Lattner41943152007-01-25 04:52:46 +00007444 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00007445 } else {
7446 // If this is a struct/class and this is not the last element, reject
7447 // it. Note that GCC supports variable sized arrays in the middle of
7448 // structures.
Douglas Gregor3e06dbf2009-03-06 23:41:27 +00007449 if (i != NumFields-1)
7450 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattnerb28fe9e2009-04-25 18:52:45 +00007451 << FD->getDeclName() << FD->getType();
Douglas Gregor3e06dbf2009-03-06 23:41:27 +00007452 else {
7453 // We support flexible arrays at the end of structs in
7454 // other structs as an extension.
7455 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
7456 << FD->getDeclName();
7457 if (Record)
7458 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00007459 }
Chris Lattner720a0542007-01-25 00:44:24 +00007460 }
7461 }
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00007462 if (Record && FDTTy->getDecl()->hasObjectMember())
7463 Record->setHasObjectMember(true);
John McCall8b07ec22010-05-15 11:32:37 +00007464 } else if (FDTy->isObjCObjectType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00007465 /// A field cannot be an Objective-c object
Steve Naroff32606412009-02-20 22:59:16 +00007466 Diag(FD->getLocation(), diag::err_statically_allocated_object);
Fariborz Jahanianecfe4f12007-10-12 22:10:42 +00007467 FD->setInvalidDecl();
7468 EnclosingDecl->setInvalidDecl();
7469 continue;
Mike Stump12b8ce12009-08-04 21:02:39 +00007470 } else if (getLangOptions().ObjC1 &&
7471 getLangOptions().getGCMode() != LangOptions::NonGC &&
7472 Record &&
7473 (FD->getType()->isObjCObjectPointerType() ||
7474 FD->getType().isObjCGCStrong()))
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00007475 Record->setHasObjectMember(true);
Fariborz Jahanian021510e2010-06-15 22:44:06 +00007476 else if (Context.getAsArrayType(FD->getType())) {
7477 QualType BaseType = Context.getBaseElementType(FD->getType());
7478 if (Record && BaseType->isRecordType() &&
7479 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
7480 Record->setHasObjectMember(true);
7481 }
Chris Lattner82625602007-01-24 02:26:21 +00007482 // Keep track of the number of named members.
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007483 if (FD->getIdentifier())
Chris Lattner82625602007-01-24 02:26:21 +00007484 ++NumNamedMembers;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00007485 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00007486
Chris Lattner82625602007-01-24 02:26:21 +00007487 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +00007488 if (Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00007489 bool Completed = false;
7490 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
7491 if (!CXXRecord->isInvalidDecl()) {
7492 // Set access bits correctly on the directly-declared conversions.
7493 UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions();
7494 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end();
7495 I != E; ++I)
7496 Convs->setAccess(I, (*I)->getAccess());
7497
7498 if (!CXXRecord->isDependentType()) {
7499 // Add any implicitly-declared members to this class.
7500 AddImplicitlyDeclaredMembersToClass(CXXRecord);
7501
7502 // If we have virtual base classes, we may end up finding multiple
7503 // final overriders for a given virtual function. Check for this
7504 // problem now.
7505 if (CXXRecord->getNumVBases()) {
7506 CXXFinalOverriderMap FinalOverriders;
7507 CXXRecord->getFinalOverriders(FinalOverriders);
7508
7509 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
7510 MEnd = FinalOverriders.end();
7511 M != MEnd; ++M) {
7512 for (OverridingMethods::iterator SO = M->second.begin(),
7513 SOEnd = M->second.end();
7514 SO != SOEnd; ++SO) {
7515 assert(SO->second.size() > 0 &&
7516 "Virtual function without overridding functions?");
7517 if (SO->second.size() == 1)
7518 continue;
7519
7520 // C++ [class.virtual]p2:
7521 // In a derived class, if a virtual member function of a base
7522 // class subobject has more than one final overrider the
7523 // program is ill-formed.
7524 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
7525 << (NamedDecl *)M->first << Record;
7526 Diag(M->first->getLocation(),
7527 diag::note_overridden_virtual_function);
7528 for (OverridingMethods::overriding_iterator
7529 OM = SO->second.begin(),
7530 OMEnd = SO->second.end();
7531 OM != OMEnd; ++OM)
7532 Diag(OM->Method->getLocation(), diag::note_final_overrider)
7533 << (NamedDecl *)M->first << OM->Method->getParent();
7534
7535 Record->setInvalidDecl();
7536 }
7537 }
7538 CXXRecord->completeDefinition(&FinalOverriders);
7539 Completed = true;
7540 }
7541 }
7542 }
7543 }
7544
7545 if (!Completed)
7546 Record->completeDefinition();
Chris Lattner622c1932008-02-06 00:51:33 +00007547 } else {
Jay Foad7d0479f2009-05-21 09:52:38 +00007548 ObjCIvarDecl **ClsFields =
7549 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian02225532008-12-13 20:28:25 +00007550 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattner22298722009-02-20 21:35:13 +00007551 ID->setLocEnd(RBrac);
Fariborz Jahanian68453832009-06-05 18:16:35 +00007552 // Add ivar's to class's DeclContext.
7553 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
7554 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007555 ID->addDecl(ClsFields[i]);
Fariborz Jahanian68453832009-06-05 18:16:35 +00007556 }
Fariborz Jahaniana599c132008-12-16 01:08:35 +00007557 // Must enforce the rule that ivars in the base classes may not be
7558 // duplicates.
Fariborz Jahanian545643c2010-02-23 23:41:11 +00007559 if (ID->getSuperClass())
7560 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump11289f42009-09-09 15:08:12 +00007561 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattnerd13b8b52009-02-23 22:00:08 +00007562 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007563 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian68453832009-06-05 18:16:35 +00007564 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
7565 // Ivar declared in @implementation never belongs to the implementation.
7566 // Only it is in implementation's lexical context.
Douglas Gregor5f662052009-04-23 03:23:08 +00007567 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian95b60762007-10-31 18:48:14 +00007568 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +00007569 } else if (ObjCCategoryDecl *CDecl =
7570 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00007571 // case of ivars in class extension; all other cases have been
7572 // reported as errors elsewhere.
7573 // FIXME. Class extension does not have a LocEnd field.
7574 // CDecl->setLocEnd(RBrac);
7575 // Add ivar's to class extension's DeclContext.
7576 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
7577 ClsFields[i]->setLexicalDeclContext(CDecl);
7578 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +00007579 }
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +00007580 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +00007581 }
Daniel Dunbar325601a2008-10-03 17:33:35 +00007582
7583 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00007584 ProcessDeclAttributeList(S, Record, Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00007585
7586 // If there's a #pragma GCC visibility in scope, and this isn't a subclass,
7587 // set the visibility of this record.
7588 if (Record && !Record->getDeclContext()->isRecord())
7589 AddPushedVisibilityAttribute(Record);
Chris Lattner1300fb92007-01-23 23:42:53 +00007590}
7591
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007592/// \brief Determine whether the given integral value is representable within
7593/// the given type T.
7594static bool isRepresentableIntegerValue(ASTContext &Context,
7595 llvm::APSInt &Value,
7596 QualType T) {
Douglas Gregor6972a622010-06-16 00:35:25 +00007597 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregorc1cf8142010-04-15 15:53:31 +00007598 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007599
Douglas Gregor0bf31402010-10-08 23:50:27 +00007600 if (Value.isUnsigned() || Value.isNonNegative()) {
7601 if (T->isSignedIntegerType())
7602 --BitWidth;
7603 return Value.getActiveBits() <= BitWidth;
7604 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007605 return Value.getMinSignedBits() <= BitWidth;
7606}
7607
7608// \brief Given an integral type, return the next larger integral type
7609// (or a NULL type of no such type exists).
7610static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
7611 // FIXME: Int128/UInt128 support, which also needs to be introduced into
7612 // enum checking below.
Douglas Gregor6972a622010-06-16 00:35:25 +00007613 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007614 const unsigned NumTypes = 4;
7615 QualType SignedIntegralTypes[NumTypes] = {
7616 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
7617 };
7618 QualType UnsignedIntegralTypes[NumTypes] = {
7619 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
7620 Context.UnsignedLongLongTy
7621 };
7622
7623 unsigned BitWidth = Context.getTypeSize(T);
7624 QualType *Types = T->isSignedIntegerType()? SignedIntegralTypes
7625 : UnsignedIntegralTypes;
7626 for (unsigned I = 0; I != NumTypes; ++I)
7627 if (Context.getTypeSize(Types[I]) > BitWidth)
7628 return Types[I];
7629
7630 return QualType();
7631}
7632
Douglas Gregor954f6b272009-03-17 19:05:46 +00007633EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
7634 EnumConstantDecl *LastEnumConst,
7635 SourceLocation IdLoc,
7636 IdentifierInfo *Id,
John McCallb268a282010-08-23 23:25:46 +00007637 Expr *Val) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007638 unsigned IntWidth = Context.Target.getIntWidth();
7639 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor954f6b272009-03-17 19:05:46 +00007640 QualType EltTy;
Douglas Gregor2b988fd2010-12-16 00:24:44 +00007641
7642 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
7643 Val = 0;
7644
Douglas Gregorb2186fe2009-11-06 00:03:12 +00007645 if (Val) {
Douglas Gregordc70c3a2010-03-02 17:53:14 +00007646 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregorb2186fe2009-11-06 00:03:12 +00007647 EltTy = Context.DependentTy;
7648 else {
Douglas Gregorb2186fe2009-11-06 00:03:12 +00007649 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
7650 SourceLocation ExpLoc;
Douglas Gregordc70c3a2010-03-02 17:53:14 +00007651 if (!Val->isValueDependent() &&
7652 VerifyIntegerConstantExpression(Val, &EnumVal)) {
Douglas Gregorb2186fe2009-11-06 00:03:12 +00007653 Val = 0;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007654 } else {
7655 if (!getLangOptions().CPlusPlus) {
7656 // C99 6.7.2.2p2:
7657 // The expression that defines the value of an enumeration constant
7658 // shall be an integer constant expression that has a value
7659 // representable as an int.
7660
7661 // Complain if the value is not representable in an int.
7662 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
7663 Diag(IdLoc, diag::ext_enum_value_not_int)
7664 << EnumVal.toString(10) << Val->getSourceRange()
Douglas Gregorc0b8c812010-02-17 22:40:11 +00007665 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007666 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
7667 // Force the type of the expression to 'int'.
John McCalle3027922010-08-25 11:45:40 +00007668 ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast);
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007669 }
7670 }
7671
Douglas Gregor0bf31402010-10-08 23:50:27 +00007672 if (Enum->isFixed()) {
7673 EltTy = Enum->getIntegerType();
7674
7675 // C++0x [dcl.enum]p5:
7676 // ... if the initializing value of an enumerator cannot be
7677 // represented by the underlying type, the program is ill-formed.
Francois Picheta3108062010-10-18 15:01:13 +00007678 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
7679 if (getLangOptions().Microsoft) {
7680 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
7681 ImpCastExprToType(Val, EltTy, CK_IntegralCast);
7682 } else
7683 Diag(IdLoc, diag::err_enumerator_too_large)
7684 << EltTy;
7685 } else
Douglas Gregor0bf31402010-10-08 23:50:27 +00007686 ImpCastExprToType(Val, EltTy, CK_IntegralCast);
7687 }
7688 else {
7689 // C++0x [dcl.enum]p5:
7690 // If the underlying type is not fixed, the type of each enumerator
7691 // is the type of its initializing value:
7692 // - If an initializer is specified for an enumerator, the
7693 // initializing value has the same type as the expression.
7694 EltTy = Val->getType();
7695 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +00007696 }
Douglas Gregor954f6b272009-03-17 19:05:46 +00007697 }
7698 }
Mike Stump11289f42009-09-09 15:08:12 +00007699
Douglas Gregor954f6b272009-03-17 19:05:46 +00007700 if (!Val) {
Eli Friedmand0e60972009-12-11 01:34:50 +00007701 if (Enum->isDependentType())
7702 EltTy = Context.DependentTy;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007703 else if (!LastEnumConst) {
7704 // C++0x [dcl.enum]p5:
7705 // If the underlying type is not fixed, the type of each enumerator
7706 // is the type of its initializing value:
7707 // - If no initializer is specified for the first enumerator, the
7708 // initializing value has an unspecified integral type.
7709 //
7710 // GCC uses 'int' for its unspecified integral type, as does
7711 // C99 6.7.2.2p3.
Douglas Gregor0bf31402010-10-08 23:50:27 +00007712 if (Enum->isFixed()) {
7713 EltTy = Enum->getIntegerType();
7714 }
7715 else {
7716 EltTy = Context.IntTy;
7717 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007718 } else {
Douglas Gregor954f6b272009-03-17 19:05:46 +00007719 // Assign the last value + 1.
7720 EnumVal = LastEnumConst->getInitVal();
7721 ++EnumVal;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007722 EltTy = LastEnumConst->getType();
Douglas Gregor954f6b272009-03-17 19:05:46 +00007723
7724 // Check for overflow on increment.
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007725 if (EnumVal < LastEnumConst->getInitVal()) {
7726 // C++0x [dcl.enum]p5:
7727 // If the underlying type is not fixed, the type of each enumerator
7728 // is the type of its initializing value:
7729 //
7730 // - Otherwise the type of the initializing value is the same as
7731 // the type of the initializing value of the preceding enumerator
7732 // unless the incremented value is not representable in that type,
7733 // in which case the type is an unspecified integral type
7734 // sufficient to contain the incremented value. If no such type
7735 // exists, the program is ill-formed.
7736 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor0bf31402010-10-08 23:50:27 +00007737 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007738 // There is no integral type larger enough to represent this
7739 // value. Complain, then allow the value to wrap around.
7740 EnumVal = LastEnumConst->getInitVal();
Jay Foad6d4db0c2010-12-07 08:25:34 +00007741 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor0bf31402010-10-08 23:50:27 +00007742 ++EnumVal;
7743 if (Enum->isFixed())
7744 // When the underlying type is fixed, this is ill-formed.
7745 Diag(IdLoc, diag::err_enumerator_wrapped)
7746 << EnumVal.toString(10)
7747 << EltTy;
7748 else
7749 Diag(IdLoc, diag::warn_enumerator_too_large)
7750 << EnumVal.toString(10);
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007751 } else {
7752 EltTy = T;
7753 }
7754
7755 // Retrieve the last enumerator's value, extent that type to the
7756 // type that is supposed to be large enough to represent the incremented
7757 // value, then increment.
7758 EnumVal = LastEnumConst->getInitVal();
7759 EnumVal.setIsSigned(EltTy->isSignedIntegerType());
Jay Foad6d4db0c2010-12-07 08:25:34 +00007760 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007761 ++EnumVal;
7762
7763 // If we're not in C++, diagnose the overflow of enumerator values,
7764 // which in C99 means that the enumerator value is not representable in
7765 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
7766 // permits enumerator values that are representable in some larger
7767 // integral type.
7768 if (!getLangOptions().CPlusPlus && !T.isNull())
7769 Diag(IdLoc, diag::warn_enum_value_overflow);
7770 } else if (!getLangOptions().CPlusPlus &&
7771 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
7772 // Enforce C99 6.7.2.2p2 even when we compute the next value.
7773 Diag(IdLoc, diag::ext_enum_value_not_int)
7774 << EnumVal.toString(10) << 1;
7775 }
Douglas Gregor954f6b272009-03-17 19:05:46 +00007776 }
7777 }
Mike Stump11289f42009-09-09 15:08:12 +00007778
Douglas Gregordc70c3a2010-03-02 17:53:14 +00007779 if (!EltTy->isDependentType()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007780 // Make the enumerator value match the signedness and size of the
7781 // enumerator's type.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007782 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6791a0d2010-02-01 23:36:03 +00007783 EnumVal.setIsSigned(EltTy->isSignedIntegerType());
7784 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +00007785
Douglas Gregor954f6b272009-03-17 19:05:46 +00007786 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump11289f42009-09-09 15:08:12 +00007787 Val, EnumVal);
Douglas Gregor954f6b272009-03-17 19:05:46 +00007788}
7789
7790
John McCall811a0f52010-10-22 23:36:17 +00007791Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
7792 SourceLocation IdLoc, IdentifierInfo *Id,
7793 AttributeList *Attr,
7794 SourceLocation EqualLoc, ExprTy *val) {
John McCall48871652010-08-21 09:40:31 +00007795 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Chris Lattner4ef40012007-06-11 01:28:17 +00007796 EnumConstantDecl *LastEnumConst =
John McCall48871652010-08-21 09:40:31 +00007797 cast_or_null<EnumConstantDecl>(lastEnumConst);
Chris Lattner4ef40012007-06-11 01:28:17 +00007798 Expr *Val = static_cast<Expr*>(val);
Chris Lattner8116d1b2007-01-25 22:38:29 +00007799
Chris Lattner1a76a3c2007-08-26 06:24:45 +00007800 // The scope passed in may not be a decl scope. Zip up the scope tree until
7801 // we find one that is.
Douglas Gregor45a33ec2009-01-12 18:45:55 +00007802 S = getNonFieldDeclScope(S);
Mike Stump11289f42009-09-09 15:08:12 +00007803
Chris Lattner8116d1b2007-01-25 22:38:29 +00007804 // Verify that there isn't already something declared with this name in this
7805 // scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00007806 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregor5204248f2010-01-19 06:06:57 +00007807 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +00007808 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00007809 // Maybe we will complain about the shadowed template parameter.
7810 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
7811 // Just pretend that we didn't see the previous declaration.
7812 PrevDecl = 0;
7813 }
7814
7815 if (PrevDecl) {
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +00007816 // When in C++, we may get a TagDecl with the same name; in this case the
7817 // enum constant will 'hide' the tag.
7818 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
7819 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis5b144d52008-09-09 21:18:04 +00007820 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +00007821 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner4bd8dd82008-11-19 08:23:25 +00007822 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner8116d1b2007-01-25 22:38:29 +00007823 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +00007824 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner0369c572008-11-23 23:12:31 +00007825 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00007826 return 0;
Chris Lattner8116d1b2007-01-25 22:38:29 +00007827 }
7828 }
Chris Lattner4ef40012007-06-11 01:28:17 +00007829
Douglas Gregor36c22a22010-10-15 13:21:21 +00007830 // C++ [class.mem]p13:
7831 // If T is the name of a class, then each of the following shall have a
7832 // name different from T:
7833 // - every enumerator of every member of class T that is an enumerated
7834 // type
7835 if (CXXRecordDecl *Record
7836 = dyn_cast<CXXRecordDecl>(
7837 TheEnumDecl->getDeclContext()->getRedeclContext()))
7838 if (Record->getIdentifier() && Record->getIdentifier() == Id)
7839 Diag(IdLoc, diag::err_member_name_of_class) << Id;
7840
John McCall811a0f52010-10-22 23:36:17 +00007841 EnumConstantDecl *New =
7842 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner0515e4b2007-08-27 21:16:18 +00007843
John McCall553c0792010-01-23 00:46:32 +00007844 if (New) {
John McCall811a0f52010-10-22 23:36:17 +00007845 // Process attributes.
7846 if (Attr) ProcessDeclAttributeList(S, New, Attr);
7847
7848 // Register this decl in the current scope stack.
John McCall553c0792010-01-23 00:46:32 +00007849 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor954f6b272009-03-17 19:05:46 +00007850 PushOnScopeChains(New, S);
John McCall553c0792010-01-23 00:46:32 +00007851 }
Douglas Gregor2f521192008-12-17 02:04:30 +00007852
John McCall48871652010-08-21 09:40:31 +00007853 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +00007854}
7855
Mike Stump6814d1c2009-05-16 07:06:02 +00007856void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCall48871652010-08-21 09:40:31 +00007857 SourceLocation RBraceLoc, Decl *EnumDeclX,
7858 Decl **Elements, unsigned NumElements,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00007859 Scope *S, AttributeList *Attr) {
John McCall48871652010-08-21 09:40:31 +00007860 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor07665a62009-01-05 19:45:36 +00007861 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00007862
7863 if (Attr)
7864 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump11289f42009-09-09 15:08:12 +00007865
Eli Friedmand0e60972009-12-11 01:34:50 +00007866 if (Enum->isDependentType()) {
7867 for (unsigned i = 0; i != NumElements; ++i) {
7868 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +00007869 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmand0e60972009-12-11 01:34:50 +00007870 if (!ECD) continue;
7871
7872 ECD->setType(EnumType);
7873 }
7874
John McCall9aa35be2010-05-06 08:49:23 +00007875 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmand0e60972009-12-11 01:34:50 +00007876 return;
7877 }
7878
Chris Lattner67933c02007-08-28 05:10:31 +00007879 // TODO: If the result value doesn't fit in an int, it must be a long or long
7880 // long value. ISO C does not support this, but GCC does as an extension,
7881 // emit a warning.
Chris Lattner37e05872008-03-05 18:54:05 +00007882 unsigned IntWidth = Context.Target.getIntWidth();
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00007883 unsigned CharWidth = Context.Target.getCharWidth();
7884 unsigned ShortWidth = Context.Target.getShortWidth();
Mike Stump11289f42009-09-09 15:08:12 +00007885
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007886 // Verify that all the values are okay, compute the size of the values, and
7887 // reverse the list.
7888 unsigned NumNegativeBits = 0;
7889 unsigned NumPositiveBits = 0;
Mike Stump11289f42009-09-09 15:08:12 +00007890
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007891 // Keep track of whether all elements have type int.
7892 bool AllElementsInt = true;
Mike Stump11289f42009-09-09 15:08:12 +00007893
Chris Lattnerc1915e22007-01-25 07:29:02 +00007894 for (unsigned i = 0; i != NumElements; ++i) {
7895 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +00007896 cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerc1915e22007-01-25 07:29:02 +00007897 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump11289f42009-09-09 15:08:12 +00007898
Chris Lattnerbf478cb2007-08-28 05:27:00 +00007899 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump11289f42009-09-09 15:08:12 +00007900
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007901 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +00007902 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +00007903 NumPositiveBits = std::max(NumPositiveBits,
7904 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007905 else
Chris Lattner49f980c2008-01-14 21:47:29 +00007906 NumNegativeBits = std::max(NumNegativeBits,
7907 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +00007908
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007909 // Keep track of whether every enum element has type int (very commmon).
7910 if (AllElementsInt)
Mike Stump11289f42009-09-09 15:08:12 +00007911 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattnerc1915e22007-01-25 07:29:02 +00007912 }
Mike Stump11289f42009-09-09 15:08:12 +00007913
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007914 // Figure out the type that should be used for this enum.
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007915 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +00007916 unsigned BestWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00007917
John McCall56774992009-12-09 09:09:27 +00007918 // C++0x N3000 [conv.prom]p3:
7919 // An rvalue of an unscoped enumeration type whose underlying
7920 // type is not fixed can be converted to an rvalue of the first
7921 // of the following types that can represent all the values of
7922 // the enumeration: int, unsigned int, long int, unsigned long
7923 // int, long long int, or unsigned long long int.
7924 // C99 6.4.4.3p2:
7925 // An identifier declared as an enumeration constant has type int.
7926 // The C99 rule is modified by a gcc extension
7927 QualType BestPromotionType;
7928
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00007929 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
Argyrios Kyrtzidis74825bc2010-10-08 00:25:19 +00007930 // -fshort-enums is the equivalent to specifying the packed attribute on all
7931 // enum definitions.
7932 if (LangOpts.ShortEnums)
7933 Packed = true;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00007934
Douglas Gregor0bf31402010-10-08 23:50:27 +00007935 if (Enum->isFixed()) {
7936 BestType = BestPromotionType = Enum->getIntegerType();
Duncan Sands38b918c2010-10-12 14:07:59 +00007937 // We don't need to set BestWidth, because BestType is going to be the type
7938 // of the enumerators, but we do anyway because otherwise some compilers
7939 // warn that it might be used uninitialized.
7940 BestWidth = CharWidth;
Douglas Gregor0bf31402010-10-08 23:50:27 +00007941 }
7942 else if (NumNegativeBits) {
Mike Stump11289f42009-09-09 15:08:12 +00007943 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007944 // int/long/longlong) that fits.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00007945 // If it's packed, check also if it fits a char or a short.
7946 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall56774992009-12-09 09:09:27 +00007947 BestType = Context.SignedCharTy;
7948 BestWidth = CharWidth;
Mike Stump11289f42009-09-09 15:08:12 +00007949 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00007950 NumPositiveBits < ShortWidth) {
John McCall56774992009-12-09 09:09:27 +00007951 BestType = Context.ShortTy;
7952 BestWidth = ShortWidth;
7953 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007954 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00007955 BestWidth = IntWidth;
7956 } else {
Chris Lattner37e05872008-03-05 18:54:05 +00007957 BestWidth = Context.Target.getLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +00007958
John McCall56774992009-12-09 09:09:27 +00007959 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007960 BestType = Context.LongTy;
John McCall56774992009-12-09 09:09:27 +00007961 } else {
Chris Lattner37e05872008-03-05 18:54:05 +00007962 BestWidth = Context.Target.getLongLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +00007963
Chris Lattner3a370bf2007-08-29 17:31:48 +00007964 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007965 Diag(Enum->getLocation(), diag::warn_enum_too_large);
7966 BestType = Context.LongLongTy;
7967 }
7968 }
John McCall56774992009-12-09 09:09:27 +00007969 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007970 } else {
Douglas Gregora71cc152010-02-02 20:10:50 +00007971 // If there is no negative value, figure out the smallest type that fits
7972 // all of the enumerator values.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00007973 // If it's packed, check also if it fits a char or a short.
7974 if (Packed && NumPositiveBits <= CharWidth) {
John McCall56774992009-12-09 09:09:27 +00007975 BestType = Context.UnsignedCharTy;
7976 BestPromotionType = Context.IntTy;
7977 BestWidth = CharWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00007978 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall56774992009-12-09 09:09:27 +00007979 BestType = Context.UnsignedShortTy;
7980 BestPromotionType = Context.IntTy;
7981 BestWidth = ShortWidth;
7982 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007983 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00007984 BestWidth = IntWidth;
Douglas Gregora71cc152010-02-02 20:10:50 +00007985 BestPromotionType
7986 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
7987 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00007988 } else if (NumPositiveBits <=
Chris Lattner37e05872008-03-05 18:54:05 +00007989 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007990 BestType = Context.UnsignedLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +00007991 BestPromotionType
7992 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
7993 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner37e05872008-03-05 18:54:05 +00007994 } else {
7995 BestWidth = Context.Target.getLongLongWidth();
Chris Lattner3a370bf2007-08-29 17:31:48 +00007996 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +00007997 "How could an initializer get larger than ULL?");
7998 BestType = Context.UnsignedLongLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +00007999 BestPromotionType
8000 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
8001 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008002 }
8003 }
Mike Stump11289f42009-09-09 15:08:12 +00008004
Chris Lattner3a370bf2007-08-29 17:31:48 +00008005 // Loop over all of the enumerator constants, changing their types to match
8006 // the type of the enum if needed.
8007 for (unsigned i = 0; i != NumElements; ++i) {
John McCall48871652010-08-21 09:40:31 +00008008 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattner3a370bf2007-08-29 17:31:48 +00008009 if (!ECD) continue; // Already issued a diagnostic.
8010
8011 // Standard C says the enumerators have int type, but we allow, as an
8012 // extension, the enumerators to be larger than int size. If each
8013 // enumerator value fits in an int, type it as an int, otherwise type it the
8014 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
8015 // that X has type 'int', not 'unsigned'.
Chris Lattner3a370bf2007-08-29 17:31:48 +00008016
8017 // Determine whether the value fits into an int.
8018 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattner3a370bf2007-08-29 17:31:48 +00008019
8020 // If it fits into an integer type, force it. Otherwise force it to match
8021 // the enum decl type.
8022 QualType NewTy;
8023 unsigned NewWidth;
8024 bool NewSign;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008025 if (!getLangOptions().CPlusPlus &&
8026 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattner3a370bf2007-08-29 17:31:48 +00008027 NewTy = Context.IntTy;
8028 NewWidth = IntWidth;
8029 NewSign = true;
8030 } else if (ECD->getType() == BestType) {
8031 // Already the right type!
Douglas Gregor1d248c52008-12-12 02:00:36 +00008032 if (getLangOptions().CPlusPlus)
8033 // C++ [dcl.enum]p4: Following the closing brace of an
8034 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +00008035 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +00008036 ECD->setType(EnumType);
Chris Lattner3a370bf2007-08-29 17:31:48 +00008037 continue;
8038 } else {
8039 NewTy = BestType;
8040 NewWidth = BestWidth;
8041 NewSign = BestType->isSignedIntegerType();
8042 }
8043
8044 // Adjust the APSInt value.
Jay Foad6d4db0c2010-12-07 08:25:34 +00008045 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattner3a370bf2007-08-29 17:31:48 +00008046 InitVal.setIsSigned(NewSign);
8047 ECD->setInitVal(InitVal);
Mike Stump11289f42009-09-09 15:08:12 +00008048
Chris Lattner3a370bf2007-08-29 17:31:48 +00008049 // Adjust the Expr initializer and type.
Abramo Bagnara77815432010-12-17 15:49:53 +00008050 if (ECD->getInitExpr() &&
8051 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallcf142162010-08-07 06:22:56 +00008052 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCalle3027922010-08-25 11:45:40 +00008053 CK_IntegralCast,
John McCallcf142162010-08-07 06:22:56 +00008054 ECD->getInitExpr(),
8055 /*base paths*/ 0,
John McCall2536c6d2010-08-25 10:28:54 +00008056 VK_RValue));
Douglas Gregor1d248c52008-12-12 02:00:36 +00008057 if (getLangOptions().CPlusPlus)
8058 // C++ [dcl.enum]p4: Following the closing brace of an
8059 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +00008060 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +00008061 ECD->setType(EnumType);
8062 else
8063 ECD->setType(NewTy);
Chris Lattner3a370bf2007-08-29 17:31:48 +00008064 }
Mike Stump11289f42009-09-09 15:08:12 +00008065
John McCall9aa35be2010-05-06 08:49:23 +00008066 Enum->completeDefinition(BestType, BestPromotionType,
8067 NumPositiveBits, NumNegativeBits);
Chris Lattnerc1915e22007-01-25 07:29:02 +00008068}
Chris Lattner1300fb92007-01-23 23:42:53 +00008069
Abramo Bagnara348823a2011-03-03 14:20:18 +00008070Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
8071 SourceLocation StartLoc,
8072 SourceLocation EndLoc) {
John McCallb268a282010-08-23 23:25:46 +00008073 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redlc675bab2008-12-13 16:23:55 +00008074
Douglas Gregor278f52e2009-05-30 00:08:05 +00008075 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara348823a2011-03-03 14:20:18 +00008076 AsmString, StartLoc,
8077 EndLoc);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008078 CurContext->addDecl(New);
John McCall48871652010-08-21 09:40:31 +00008079 return New;
Anders Carlsson5c6c0592008-02-08 00:33:21 +00008080}
Eli Friedman5ed51982009-06-05 02:44:36 +00008081
8082void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
8083 SourceLocation PragmaLoc,
8084 SourceLocation NameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00008085 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedman5ed51982009-06-05 02:44:36 +00008086
Eli Friedman5ed51982009-06-05 02:44:36 +00008087 if (PrevDecl) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00008088 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
Ryan Flynn7d470f32009-07-30 03:15:39 +00008089 } else {
8090 (void)WeakUndeclaredIdentifiers.insert(
8091 std::pair<IdentifierInfo*,WeakInfo>
8092 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedman5ed51982009-06-05 02:44:36 +00008093 }
Eli Friedman5ed51982009-06-05 02:44:36 +00008094}
8095
8096void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
8097 IdentifierInfo* AliasName,
8098 SourceLocation PragmaLoc,
8099 SourceLocation NameLoc,
8100 SourceLocation AliasNameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00008101 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
8102 LookupOrdinaryName);
Ryan Flynn7d470f32009-07-30 03:15:39 +00008103 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedman5ed51982009-06-05 02:44:36 +00008104
Eli Friedman5ed51982009-06-05 02:44:36 +00008105 if (PrevDecl) {
Ryan Flynn7d470f32009-07-30 03:15:39 +00008106 if (!PrevDecl->hasAttr<AliasAttr>())
8107 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynnd963a492009-07-31 02:52:19 +00008108 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynn7d470f32009-07-30 03:15:39 +00008109 } else {
8110 (void)WeakUndeclaredIdentifiers.insert(
8111 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedman5ed51982009-06-05 02:44:36 +00008112 }
Eli Friedman5ed51982009-06-05 02:44:36 +00008113}