blob: f650724535be32e7c9a88797ebbeb37ea69acfdb [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"
Chandler Carruth33bf3e72011-03-27 09:46:56 +000028#include "clang/AST/EvaluatedExprVisitor.h"
Chris Lattner2c6fcf52008-06-26 18:38:35 +000029#include "clang/AST/ExprCXX.h"
Sebastian Redla7b98a72009-04-26 20:35:05 +000030#include "clang/AST/StmtCXX.h"
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +000031#include "clang/AST/CharUnits.h"
John McCall8b0666c2010-08-20 18:27:03 +000032#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/ParsedTemplate.h"
Douglas Gregor15e56022009-10-13 23:27:22 +000034#include "clang/Parse/ParseDiagnostic.h"
Anders Carlssond624e162009-08-26 23:45:07 +000035#include "clang/Basic/PartialDiagnostic.h"
Steve Naroffe101f952008-01-30 23:46:05 +000036#include "clang/Basic/SourceManager.h"
Anders Carlssond624e162009-08-26 23:45:07 +000037#include "clang/Basic/TargetInfo.h"
Steve Naroffe101f952008-01-30 23:46:05 +000038// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattner622c1932008-02-06 00:51:33 +000039#include "clang/Lex/Preprocessor.h"
Mike Stump11289f42009-09-09 15:08:12 +000040#include "clang/Lex/HeaderSearch.h"
John McCall0e21fcc2009-12-24 09:58:38 +000041#include "llvm/ADT/Triple.h"
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000042#include <algorithm>
Douglas Gregor56fbc372009-09-28 21:14:19 +000043#include <cstring>
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000044#include <functional>
Chris Lattner697e5d62006-11-09 06:32:27 +000045using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000046using namespace sema;
Chris Lattner697e5d62006-11-09 06:32:27 +000047
Richard Smithcd1c0552011-07-01 19:46:12 +000048Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
49 if (OwnedType) {
50 Decl *Group[2] = { OwnedType, Ptr };
51 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
52 }
53
John McCall48871652010-08-21 09:40:31 +000054 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
Chris Lattner5bbb3c82009-03-29 16:50:03 +000055}
56
Douglas Gregorec6e1892009-02-04 19:16:12 +000057/// \brief If the identifier refers to a type name within this scope,
58/// return the declaration of that type.
59///
60/// This routine performs ordinary name lookup of the identifier II
61/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor9817f4a2009-02-09 15:09:02 +000062/// determine whether the name refers to a type. If so, returns an
63/// opaque pointer (actually a QualType) corresponding to that
64/// type. Otherwise, returns NULL.
Douglas Gregorec6e1892009-02-04 19:16:12 +000065///
66/// If name lookup results in an ambiguity, this routine will complain
67/// and then return NULL.
John McCallba7bf592010-08-24 05:47:05 +000068ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
69 Scope *S, CXXScopeSpec *SS,
Fariborz Jahanian87967422011-02-08 18:05:59 +000070 bool isClassName, bool HasTrailingDot,
Douglas Gregor844cb502011-03-01 18:12:44 +000071 ParsedType ObjectTypePtr,
72 bool WantNontrivialTypeSourceInfo) {
Douglas Gregora25d65d2009-11-20 22:03:38 +000073 // Determine where we will perform name lookup.
74 DeclContext *LookupCtx = 0;
75 if (ObjectTypePtr) {
John McCallba7bf592010-08-24 05:47:05 +000076 QualType ObjectType = ObjectTypePtr.get();
Douglas Gregora25d65d2009-11-20 22:03:38 +000077 if (ObjectType->isRecordType())
78 LookupCtx = computeDeclContext(ObjectType);
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +000079 } else if (SS && SS->isNotEmpty()) {
Douglas Gregora25d65d2009-11-20 22:03:38 +000080 LookupCtx = computeDeclContext(*SS, false);
81
82 if (!LookupCtx) {
83 if (isDependentScopeSpecifier(*SS)) {
84 // C++ [temp.res]p3:
85 // A qualified-id that refers to a type and in which the
86 // nested-name-specifier depends on a template-parameter (14.6.2)
87 // shall be prefixed by the keyword typename to indicate that the
88 // qualified-id denotes a type, forming an
89 // elaborated-type-specifier (7.1.5.3).
90 //
91 // We therefore do not perform any name lookup if the result would
92 // refer to a member of an unknown specialization.
93 if (!isClassName)
John McCallba7bf592010-08-24 05:47:05 +000094 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +000095
John McCallc392f372010-06-11 00:33:02 +000096 // We know from the grammar that this name refers to a type,
97 // so build a dependent node to describe the type.
Douglas Gregor844cb502011-03-01 18:12:44 +000098 if (WantNontrivialTypeSourceInfo)
99 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
100
101 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
John McCallba7bf592010-08-24 05:47:05 +0000102 QualType T =
Douglas Gregor844cb502011-03-01 18:12:44 +0000103 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000104 II, NameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +0000105
106 return ParsedType::make(T);
Douglas Gregora25d65d2009-11-20 22:03:38 +0000107 }
108
John McCallba7bf592010-08-24 05:47:05 +0000109 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000110 }
111
John McCall0b66eb32010-05-01 00:40:08 +0000112 if (!LookupCtx->isDependentContext() &&
113 RequireCompleteDeclContext(*SS, LookupCtx))
John McCallba7bf592010-08-24 05:47:05 +0000114 return ParsedType();
Douglas Gregor5e0962f2009-08-26 18:27:52 +0000115 }
Eli Friedman9025ec22009-12-21 01:42:38 +0000116
117 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
118 // lookup for class-names.
119 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
120 LookupOrdinaryName;
121 LookupResult Result(*this, &II, NameLoc, Kind);
Douglas Gregora25d65d2009-11-20 22:03:38 +0000122 if (LookupCtx) {
123 // Perform "qualified" name lookup into the declaration context we
124 // computed, which is either the type of the base of a member access
125 // expression or the declaration context associated with a prior
126 // nested-name-specifier.
127 LookupQualifiedName(Result, LookupCtx);
Douglas Gregorc9f9b862009-05-11 19:58:34 +0000128
Douglas Gregora25d65d2009-11-20 22:03:38 +0000129 if (ObjectTypePtr && Result.empty()) {
130 // C++ [basic.lookup.classref]p3:
131 // If the unqualified-id is ~type-name, the type-name is looked up
132 // in the context of the entire postfix-expression. If the type T of
133 // the object expression is of a class type C, the type-name is also
134 // looked up in the scope of class C. At least one of the lookups shall
135 // find a name that refers to (possibly cv-qualified) T.
136 LookupName(Result, S);
137 }
138 } else {
139 // Perform unqualified name lookup.
140 LookupName(Result, S);
141 }
142
Chris Lattnera3778332009-02-16 22:07:16 +0000143 NamedDecl *IIDecl = 0;
John McCall27b18f82009-11-17 02:14:36 +0000144 switch (Result.getResultKind()) {
Chris Lattnera3778332009-02-16 22:07:16 +0000145 case LookupResult::NotFound:
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000146 case LookupResult::NotFoundInCurrentInstantiation:
Chris Lattnera3778332009-02-16 22:07:16 +0000147 case LookupResult::FoundOverloaded:
John McCalle61f2ba2009-11-18 02:36:19 +0000148 case LookupResult::FoundUnresolvedValue:
John McCall58cc69d2010-01-27 01:50:18 +0000149 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000150 return ParsedType();
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000151
Chris Lattnere40853a2009-10-25 22:09:09 +0000152 case LookupResult::Ambiguous:
John McCall6538c932009-10-10 05:48:19 +0000153 // Recover from type-hiding ambiguities by hiding the type. We'll
154 // do the lookup again when looking for an object, and we can
155 // diagnose the error then. If we don't do this, then the error
156 // about hiding the type will be immediately followed by an error
157 // that only makes sense if the identifier was treated like a type.
John McCall27b18f82009-11-17 02:14:36 +0000158 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
159 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000160 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000161 }
John McCall6538c932009-10-10 05:48:19 +0000162
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000163 // Look to see if we have a type anywhere in the list of results.
164 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
165 Res != ResEnd; ++Res) {
166 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
Mike Stump11289f42009-09-09 15:08:12 +0000167 if (!IIDecl ||
168 (*Res)->getLocation().getRawEncoding() <
Douglas Gregor712a3512009-04-13 15:14:38 +0000169 IIDecl->getLocation().getRawEncoding())
170 IIDecl = *Res;
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000171 }
172 }
173
174 if (!IIDecl) {
175 // None of the entities we found is a type, so there is no way
176 // to even assume that the result is a type. In this case, don't
177 // complain about the ambiguity. The parser will either try to
178 // perform this lookup again (e.g., as an object name), which
179 // will produce the ambiguity, or will complain that it expected
180 // a type name.
John McCall27b18f82009-11-17 02:14:36 +0000181 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000182 return ParsedType();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000183 }
184
185 // We found a type within the ambiguous lookup; diagnose the
186 // ambiguity and then return that type. This might be the right
187 // answer, or it might not be, but it suppresses any attempt to
188 // perform the name lookup again.
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000189 break;
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000190
Chris Lattnera3778332009-02-16 22:07:16 +0000191 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +0000192 IIDecl = Result.getFoundDecl();
Chris Lattnera3778332009-02-16 22:07:16 +0000193 break;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000194 }
195
Chris Lattner17e15f12009-10-25 17:16:46 +0000196 assert(IIDecl && "Didn't find decl");
John McCall28a6aea2009-11-04 02:18:39 +0000197
Chris Lattner17e15f12009-10-25 17:16:46 +0000198 QualType T;
199 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
John McCall28a6aea2009-11-04 02:18:39 +0000200 DiagnoseUseOfDecl(IIDecl, NameLoc);
John McCall27b18f82009-11-17 02:14:36 +0000201
Chris Lattner17e15f12009-10-25 17:16:46 +0000202 if (T.isNull())
203 T = Context.getTypeDeclType(TD);
204
Douglas Gregor844cb502011-03-01 18:12:44 +0000205 if (SS && SS->isNotEmpty()) {
206 if (WantNontrivialTypeSourceInfo) {
207 // Construct a type with type-source information.
208 TypeLocBuilder Builder;
209 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
210
211 T = getElaboratedType(ETK_None, *SS, T);
212 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
213 ElabTL.setKeywordLoc(SourceLocation());
214 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
215 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
216 } else {
217 T = getElaboratedType(ETK_None, *SS, T);
218 }
219 }
Chris Lattner17e15f12009-10-25 17:16:46 +0000220 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
Fariborz Jahanian08891f52011-03-08 19:12:46 +0000221 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
Fariborz Jahanian87967422011-02-08 18:05:59 +0000222 if (!HasTrailingDot)
223 T = Context.getObjCInterfaceType(IDecl);
224 }
225
226 if (T.isNull()) {
John McCall27b18f82009-11-17 02:14:36 +0000227 // If it's not plausibly a type, suppress diagnostics.
228 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000229 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000230 }
John McCallba7bf592010-08-24 05:47:05 +0000231 return ParsedType::make(T);
Chris Lattnere168f762006-11-10 05:29:30 +0000232}
233
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000234/// isTagName() - This method is called *for error recovery purposes only*
235/// to determine if the specified name is a valid tag name ("struct foo"). If
236/// so, this returns the TST for the tag corresponding to it (TST_enum,
237/// TST_union, TST_struct, TST_class). This is used to diagnose cases in C
238/// where the user forgot to specify the tag.
239DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
240 // Do a tag name lookup in this scope.
John McCall27b18f82009-11-17 02:14:36 +0000241 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
242 LookupName(R, S, false);
243 R.suppressDiagnostics();
244 if (R.getResultKind() == LookupResult::Found)
John McCall67c00872009-12-02 08:25:40 +0000245 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000246 switch (TD->getTagKind()) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000247 default: return DeclSpec::TST_unspecified;
248 case TTK_Struct: return DeclSpec::TST_struct;
249 case TTK_Union: return DeclSpec::TST_union;
250 case TTK_Class: return DeclSpec::TST_class;
251 case TTK_Enum: return DeclSpec::TST_enum;
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000252 }
253 }
Mike Stump11289f42009-09-09 15:08:12 +0000254
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000255 return DeclSpec::TST_unspecified;
256}
257
Francois Pichet48c946e2011-04-13 02:38:49 +0000258/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
259/// if a CXXScopeSpec's type is equal to the type of one of the base classes
260/// then downgrade the missing typename error to a warning.
261/// This is needed for MSVC compatibility; Example:
262/// @code
263/// template<class T> class A {
264/// public:
265/// typedef int TYPE;
266/// };
267/// template<class T> class B : public A<T> {
268/// public:
269/// A<T>::TYPE a; // no typename required because A<T> is a base class.
270/// };
271/// @endcode
272bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS) {
273 if (CurContext->isRecord()) {
Francois Pichetefc283c2011-04-13 02:44:57 +0000274 const Type *Ty = SS->getScopeRep()->getAsType();
Francois Pichet48c946e2011-04-13 02:38:49 +0000275
276 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
277 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
278 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
279 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
280 return true;
281 }
282 return false;
283}
284
Douglas Gregor15e56022009-10-13 23:27:22 +0000285bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
286 SourceLocation IILoc,
287 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000288 CXXScopeSpec *SS,
John McCallba7bf592010-08-24 05:47:05 +0000289 ParsedType &SuggestedType) {
Douglas Gregor15e56022009-10-13 23:27:22 +0000290 // We don't have anything to suggest (yet).
John McCallba7bf592010-08-24 05:47:05 +0000291 SuggestedType = ParsedType();
Douglas Gregor15e56022009-10-13 23:27:22 +0000292
Douglas Gregor2d435302009-12-30 17:04:44 +0000293 // There may have been a typo in the name of the type. Look up typo
294 // results, in case we have something that we can suggest.
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000295 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(&II, IILoc),
296 LookupOrdinaryName, S, SS, NULL,
297 false, CTC_Type)) {
298 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
299 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
Douglas Gregor2d435302009-12-30 17:04:44 +0000300
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000301 if (Corrected.isKeyword()) {
302 // We corrected to a keyword.
303 // FIXME: Actually recover with the keyword we suggest, and emit a fix-it.
304 Diag(IILoc, diag::err_unknown_typename_suggest)
305 << &II << CorrectedQuotedStr;
306 return true;
307 } else {
308 NamedDecl *Result = Corrected.getCorrectionDecl();
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000309 if ((isa<TypeDecl>(Result) || isa<ObjCInterfaceDecl>(Result)) &&
310 !Result->isInvalidDecl()) {
311 // We found a similarly-named type or interface; suggest that.
312 if (!SS || !SS->isSet())
313 Diag(IILoc, diag::err_unknown_typename_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000314 << &II << CorrectedQuotedStr
315 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000316 else if (DeclContext *DC = computeDeclContext(*SS, false))
317 Diag(IILoc, diag::err_unknown_nested_typename_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000318 << &II << DC << CorrectedQuotedStr << SS->getRange()
319 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000320 else
321 llvm_unreachable("could not have corrected a typo here");
Douglas Gregor2d435302009-12-30 17:04:44 +0000322
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000323 Diag(Result->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000324 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000325
Douglas Gregor844cb502011-03-01 18:12:44 +0000326 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS,
327 false, false, ParsedType(),
328 /*NonTrivialTypeSourceInfo=*/true);
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000329 return true;
330 }
Douglas Gregor2d435302009-12-30 17:04:44 +0000331 }
332 }
333
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000334 if (getLangOptions().CPlusPlus) {
335 // See if II is a class template that the user forgot to pass arguments to.
336 UnqualifiedId Name;
337 Name.setIdentifier(&II, IILoc);
338 CXXScopeSpec EmptySS;
339 TemplateTy TemplateResult;
Douglas Gregor786123d2010-05-21 23:18:07 +0000340 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000341 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
John McCallba7bf592010-08-24 05:47:05 +0000342 Name, ParsedType(), true, TemplateResult,
Douglas Gregor786123d2010-05-21 23:18:07 +0000343 MemberOfUnknownSpecialization) == TNK_Type_template) {
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000344 TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
345 Diag(IILoc, diag::err_template_missing_args) << TplName;
346 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
347 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
348 << TplDecl->getTemplateParameters()->getSourceRange();
349 }
350 return true;
351 }
352 }
353
Douglas Gregor15e56022009-10-13 23:27:22 +0000354 // FIXME: Should we move the logic that tries to recover from a missing tag
355 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
356
Douglas Gregor2d435302009-12-30 17:04:44 +0000357 if (!SS || (!SS->isSet() && !SS->isInvalid()))
Douglas Gregor15e56022009-10-13 23:27:22 +0000358 Diag(IILoc, diag::err_unknown_typename) << &II;
359 else if (DeclContext *DC = computeDeclContext(*SS, false))
360 Diag(IILoc, diag::err_typename_nested_not_found)
361 << &II << DC << SS->getRange();
362 else if (isDependentScopeSpecifier(*SS)) {
Francois Pichet48c946e2011-04-13 02:38:49 +0000363 unsigned DiagID = diag::err_typename_missing;
364 if (getLangOptions().Microsoft && isMicrosoftMissingTypename(SS))
Francois Pichet93921652011-04-22 08:25:24 +0000365 DiagID = diag::warn_typename_missing;
Francois Pichet48c946e2011-04-13 02:38:49 +0000366
367 Diag(SS->getRange().getBegin(), DiagID)
Daniel Dunbar07d07852009-10-18 21:17:35 +0000368 << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
Douglas Gregor15e56022009-10-13 23:27:22 +0000369 << SourceRange(SS->getRange().getBegin(), IILoc)
Douglas Gregora771f462010-03-31 17:46:05 +0000370 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
Douglas Gregorf7d77712010-06-16 22:31:08 +0000371 SuggestedType = ActOnTypenameType(S, SourceLocation(), *SS, II, IILoc).get();
Douglas Gregor15e56022009-10-13 23:27:22 +0000372 } else {
373 assert(SS && SS->isInvalid() &&
374 "Invalid scope specifier has already been diagnosed");
375 }
376
377 return true;
378}
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000379
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000380/// \brief Determine whether the given result set contains either a type name
381/// or
382static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
383 bool CheckTemplate = R.getSema().getLangOptions().CPlusPlus &&
384 NextToken.is(tok::less);
385
386 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
387 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
388 return true;
389
390 if (CheckTemplate && isa<TemplateDecl>(*I))
391 return true;
392 }
393
394 return false;
395}
396
397Sema::NameClassification Sema::ClassifyName(Scope *S,
398 CXXScopeSpec &SS,
399 IdentifierInfo *&Name,
400 SourceLocation NameLoc,
401 const Token &NextToken) {
402 DeclarationNameInfo NameInfo(Name, NameLoc);
403 ObjCMethodDecl *CurMethod = getCurMethodDecl();
404
405 if (NextToken.is(tok::coloncolon)) {
406 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
407 QualType(), false, SS, 0, false);
408
409 }
410
411 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
412 LookupParsedName(Result, S, &SS, !CurMethod);
413
414 // Perform lookup for Objective-C instance variables (including automatically
415 // synthesized instance variables), if we're in an Objective-C method.
416 // FIXME: This lookup really, really needs to be folded in to the normal
417 // unqualified lookup mechanism.
418 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
419 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
Douglas Gregorb90f5182011-04-25 15:05:41 +0000420 if (E.get() || E.isInvalid())
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000421 return E;
422
423 // Synthesize ivars lazily.
424 if (getLangOptions().ObjCDefaultSynthProperties &&
425 getLangOptions().ObjCNonFragileABI2) {
426 if (SynthesizeProvisionalIvar(Result, Name, NameLoc)) {
427 if (const ObjCPropertyDecl *Property =
428 canSynthesizeProvisionalIvar(Name)) {
429 Diag(NameLoc, diag::warn_synthesized_ivar_access) << Name;
430 Diag(Property->getLocation(), diag::note_property_declare);
431 }
432
433 // FIXME: This is strange. Shouldn't we just take the ivar returned
434 // from SynthesizeProvisionalIvar and continue with that?
Douglas Gregorb90f5182011-04-25 15:05:41 +0000435 E = LookupInObjCMethod(Result, S, Name, true);
436 if (E.get() || E.isInvalid())
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000437 return E;
438 }
439 }
440 }
441
442 bool SecondTry = false;
443 bool IsFilteredTemplateName = false;
444
445Corrected:
446 switch (Result.getResultKind()) {
447 case LookupResult::NotFound:
448 // If an unqualified-id is followed by a '(', then we have a function
449 // call.
450 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
451 // In C++, this is an ADL-only call.
452 // FIXME: Reference?
453 if (getLangOptions().CPlusPlus)
454 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
455
456 // C90 6.3.2.2:
457 // If the expression that precedes the parenthesized argument list in a
458 // function call consists solely of an identifier, and if no
459 // declaration is visible for this identifier, the identifier is
460 // implicitly declared exactly as if, in the innermost block containing
461 // the function call, the declaration
462 //
463 // extern int identifier ();
464 //
465 // appeared.
466 //
467 // We also allow this in C99 as an extension.
468 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
469 Result.addDecl(D);
470 Result.resolveKind();
471 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
472 }
473 }
474
475 // In C, we first see whether there is a tag type by the same name, in
476 // which case it's likely that the user just forget to write "enum",
477 // "struct", or "union".
478 if (!getLangOptions().CPlusPlus && !SecondTry) {
479 Result.clear(LookupTagName);
480 LookupParsedName(Result, S, &SS);
481 if (TagDecl *Tag = Result.getAsSingle<TagDecl>()) {
482 const char *TagName = 0;
483 const char *FixItTagName = 0;
484 switch (Tag->getTagKind()) {
485 case TTK_Class:
486 TagName = "class";
487 FixItTagName = "class ";
488 break;
489
490 case TTK_Enum:
491 TagName = "enum";
492 FixItTagName = "enum ";
493 break;
494
495 case TTK_Struct:
496 TagName = "struct";
497 FixItTagName = "struct ";
498 break;
499
500 case TTK_Union:
501 TagName = "union";
502 FixItTagName = "union ";
503 break;
504 }
505
506 Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
507 << Name << TagName << getLangOptions().CPlusPlus
508 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
509 break;
510 }
511
512 Result.clear(LookupOrdinaryName);
513 }
514
515 // Perform typo correction to determine if there is another name that is
516 // close to this name.
517 if (!SecondTry) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000518 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
519 Result.getLookupKind(), S, &SS)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000520 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
521 unsigned QualifiedDiag = diag::err_no_member_suggest;
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000522 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
523 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
Douglas Gregor5e16c162011-04-27 03:47:06 +0000524
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000525 NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000526 NamedDecl *UnderlyingFirstDecl
527 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
Douglas Gregor5e16c162011-04-27 03:47:06 +0000528 if (getLangOptions().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000529 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000530 UnqualifiedDiag = diag::err_no_template_suggest;
531 QualifiedDiag = diag::err_no_member_template_suggest;
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000532 } else if (UnderlyingFirstDecl &&
533 (isa<TypeDecl>(UnderlyingFirstDecl) ||
534 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
535 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000536 UnqualifiedDiag = diag::err_unknown_typename_suggest;
537 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
538 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000539
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000540 if (SS.isEmpty())
Douglas Gregor5e16c162011-04-27 03:47:06 +0000541 Diag(NameLoc, UnqualifiedDiag)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000542 << Name << CorrectedQuotedStr
543 << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000544 else
Douglas Gregor5e16c162011-04-27 03:47:06 +0000545 Diag(NameLoc, QualifiedDiag)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000546 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000547 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000548 << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000549
550 // Update the name, so that the caller has the new name.
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000551 Name = Corrected.getCorrectionAsIdentifierInfo();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000552
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000553 // Also update the LookupResult...
554 // FIXME: This should probably go away at some point
555 Result.clear();
556 Result.setLookupName(Corrected.getCorrection());
557 if (FirstDecl) Result.addDecl(FirstDecl);
558
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000559 // Typo correction corrected to a keyword.
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000560 if (Corrected.isKeyword())
561 return Corrected.getCorrectionAsIdentifierInfo();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000562
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000563 Diag(FirstDecl->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000564 << CorrectedQuotedStr;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000565
566 // If we found an Objective-C instance variable, let
567 // LookupInObjCMethod build the appropriate expression to
568 // reference the ivar.
569 // FIXME: This is a gross hack.
570 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
571 Result.clear();
572 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
573 return move(E);
574 }
575
576 goto Corrected;
577 }
578 }
579
580 // We failed to correct; just fall through and let the parser deal with it.
581 Result.suppressDiagnostics();
582 return NameClassification::Unknown();
583
584 case LookupResult::NotFoundInCurrentInstantiation:
585 // We performed name lookup into the current instantiation, and there were
586 // dependent bases, so we treat this result the same way as any other
587 // dependent nested-name-specifier.
588
589 // C++ [temp.res]p2:
590 // A name used in a template declaration or definition and that is
591 // dependent on a template-parameter is assumed not to name a type
592 // unless the applicable name lookup finds a type name or the name is
593 // qualified by the keyword typename.
594 //
595 // FIXME: If the next token is '<', we might want to ask the parser to
596 // perform some heroics to see if we actually have a
597 // template-argument-list, which would indicate a missing 'template'
598 // keyword here.
599 return BuildDependentDeclRefExpr(SS, NameInfo, /*TemplateArgs=*/0);
600
601 case LookupResult::Found:
602 case LookupResult::FoundOverloaded:
603 case LookupResult::FoundUnresolvedValue:
604 break;
605
606 case LookupResult::Ambiguous:
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000607 if (getLangOptions().CPlusPlus && NextToken.is(tok::less) &&
608 hasAnyAcceptableTemplateNames(Result)) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000609 // C++ [temp.local]p3:
610 // A lookup that finds an injected-class-name (10.2) can result in an
611 // ambiguity in certain cases (for example, if it is found in more than
612 // one base class). If all of the injected-class-names that are found
613 // refer to specializations of the same class template, and if the name
614 // is followed by a template-argument-list, the reference refers to the
615 // class template itself and not a specialization thereof, and is not
616 // ambiguous.
617 //
618 // This filtering can make an ambiguous result into an unambiguous one,
619 // so try again after filtering out template names.
620 FilterAcceptableTemplateNames(Result);
621 if (!Result.isAmbiguous()) {
622 IsFilteredTemplateName = true;
623 break;
624 }
625 }
626
627 // Diagnose the ambiguity and return an error.
628 return NameClassification::Error();
629 }
630
631 if (getLangOptions().CPlusPlus && NextToken.is(tok::less) &&
632 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
633 // C++ [temp.names]p3:
634 // After name lookup (3.4) finds that a name is a template-name or that
635 // an operator-function-id or a literal- operator-id refers to a set of
636 // overloaded functions any member of which is a function template if
637 // this is followed by a <, the < is always taken as the delimiter of a
638 // template-argument-list and never as the less-than operator.
639 if (!IsFilteredTemplateName)
640 FilterAcceptableTemplateNames(Result);
641
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000642 if (!Result.empty()) {
643 bool IsFunctionTemplate;
644 TemplateName Template;
645 if (Result.end() - Result.begin() > 1) {
646 IsFunctionTemplate = true;
647 Template = Context.getOverloadedTemplateName(Result.begin(),
648 Result.end());
649 } else {
650 TemplateDecl *TD
651 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
652 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
653
654 if (SS.isSet() && !SS.isInvalid())
655 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000656 /*TemplateKeyword=*/false,
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000657 TD);
658 else
659 Template = TemplateName(TD);
660 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000661
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000662 if (IsFunctionTemplate) {
663 // Function templates always go through overload resolution, at which
664 // point we'll perform the various checks (e.g., accessibility) we need
665 // to based on which function we selected.
666 Result.suppressDiagnostics();
667
668 return NameClassification::FunctionTemplate(Template);
669 }
670
671 return NameClassification::TypeTemplate(Template);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000672 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000673 }
674
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000675 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000676 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
677 DiagnoseUseOfDecl(Type, NameLoc);
678 QualType T = Context.getTypeDeclType(Type);
679 return ParsedType::make(T);
680 }
681
682 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
683 if (!Class) {
684 // FIXME: It's unfortunate that we don't have a Type node for handling this.
685 if (ObjCCompatibleAliasDecl *Alias
686 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
687 Class = Alias->getClassInterface();
688 }
689
690 if (Class) {
691 DiagnoseUseOfDecl(Class, NameLoc);
692
693 if (NextToken.is(tok::period)) {
694 // Interface. <something> is parsed as a property reference expression.
695 // Just return "unknown" as a fall-through for now.
696 Result.suppressDiagnostics();
697 return NameClassification::Unknown();
698 }
699
700 QualType T = Context.getObjCInterfaceType(Class);
701 return ParsedType::make(T);
702 }
703
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000704 if (!Result.empty() && (*Result.begin())->isCXXClassMember())
705 return BuildPossibleImplicitMemberExpr(SS, Result, 0);
706
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000707 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
708 return BuildDeclarationNameExpr(SS, Result, ADL);
709}
710
John McCall5ed6e8f2009-08-18 00:00:49 +0000711// Determines the context to return to after temporarily entering a
712// context. This depends in an unnecessarily complicated way on the
713// exact ordering of callbacks from the parser.
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000714DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000715
John McCall5ed6e8f2009-08-18 00:00:49 +0000716 // Functions defined inline within classes aren't parsed until we've
717 // finished parsing the top-level class, so the top-level class is
718 // the context we'll need to return to.
719 if (isa<FunctionDecl>(DC)) {
720 DC = DC->getLexicalParent();
721
722 // A function not defined within a class will always return to its
723 // lexical context.
724 if (!isa<CXXRecordDecl>(DC))
725 return DC;
726
727 // A C++ inline method/friend is parsed *after* the topmost class
728 // it was declared in is fully parsed ("complete"); the topmost
729 // class is the context we need to return to.
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000730 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000731 DC = RD;
732
733 // Return the declaration context of the topmost class the inline method is
734 // declared in.
735 return DC;
736 }
737
John McCalldc9796e2010-08-06 00:46:05 +0000738 // ObjCMethodDecls are parsed (for some reason) outside the context
739 // of the class.
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +0000740 if (isa<ObjCMethodDecl>(DC))
John McCalldc9796e2010-08-06 00:46:05 +0000741 return DC->getLexicalParent()->getLexicalParent();
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +0000742
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000743 return DC->getLexicalParent();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000744}
745
Douglas Gregor91f84212008-12-11 16:49:14 +0000746void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000747 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu17a37eb2008-12-08 07:14:51 +0000748 "The next DeclContext should be lexically contained in the current one.");
Chris Lattnerbec41342008-04-22 18:39:57 +0000749 CurContext = DC;
Douglas Gregor91f84212008-12-11 16:49:14 +0000750 S->setEntity(DC);
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000751}
752
Chris Lattner0a5ff0d2008-04-06 04:47:34 +0000753void Sema::PopDeclContext() {
754 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor91f84212008-12-11 16:49:14 +0000755
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000756 CurContext = getContainingDC(CurContext);
John McCalldd762d12010-07-23 22:45:07 +0000757 assert(CurContext && "Popped translation unit!");
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000758}
759
Argyrios Kyrtzidis9941a4d2009-06-17 23:19:02 +0000760/// EnterDeclaratorContext - Used when we must lookup names in the context
761/// of a declarator's nested name specifier.
John McCall6df5fef2009-12-19 10:49:29 +0000762///
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000763void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall6df5fef2009-12-19 10:49:29 +0000764 // C++0x [basic.lookup.unqual]p13:
765 // A name used in the definition of a static data member of class
766 // X (after the qualified-id of the static member) is looked up as
767 // if the name was used in a member function of X.
768 // C++0x [basic.lookup.unqual]p14:
769 // If a variable member of a namespace is defined outside of the
770 // scope of its namespace then any name used in the definition of
771 // the variable member (after the declarator-id) is looked up as
772 // if the definition of the variable member occurred in its
773 // namespace.
774 // Both of these imply that we should push a scope whose context
775 // is the semantic context of the declaration. We can't use
776 // PushDeclContext here because that context is not necessarily
777 // lexically contained in the current context. Fortunately,
778 // the containing scope should have the appropriate information.
779
780 assert(!S->getEntity() && "scope already has entity");
781
782#ifndef NDEBUG
783 Scope *Ancestor = S->getParent();
784 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
785 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
786#endif
787
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000788 CurContext = DC;
John McCall6df5fef2009-12-19 10:49:29 +0000789 S->setEntity(DC);
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000790}
791
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000792void Sema::ExitDeclaratorContext(Scope *S) {
John McCall6df5fef2009-12-19 10:49:29 +0000793 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000794
John McCall6df5fef2009-12-19 10:49:29 +0000795 // Switch back to the lexical context. The safety of this is
796 // enforced by an assert in EnterDeclaratorContext.
797 Scope *Ancestor = S->getParent();
798 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
799 CurContext = (DeclContext*) Ancestor->getEntity();
800
801 // We don't need to do anything with the scope, which is going to
802 // disappear.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000803}
804
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000805/// \brief Determine whether we allow overloading of the function
806/// PrevDecl with another declaration.
807///
808/// This routine determines whether overloading is possible, not
809/// whether some new function is actually an overload. It will return
810/// true in C++ (where we can always provide overloads) or, as an
811/// extension, in C when the previous function is already an
812/// overloaded function declaration or has the "overloadable"
813/// attribute.
John McCall1f82f242009-11-18 22:49:29 +0000814static bool AllowOverloadingOfFunction(LookupResult &Previous,
815 ASTContext &Context) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000816 if (Context.getLangOptions().CPlusPlus)
817 return true;
818
John McCall1f82f242009-11-18 22:49:29 +0000819 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000820 return true;
821
John McCall1f82f242009-11-18 22:49:29 +0000822 return (Previous.getResultKind() == LookupResult::Found
823 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000824}
825
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +0000826/// Add this decl to the scope shadowed decl chains.
John McCall759e32b2009-08-31 22:39:49 +0000827void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor07665a62009-01-05 19:45:36 +0000828 // Move up the scope chain until we find the nearest enclosing
829 // non-transparent context. The declaration will be introduced into this
830 // scope.
Mike Stump11289f42009-09-09 15:08:12 +0000831 while (S->getEntity() &&
Douglas Gregor07665a62009-01-05 19:45:36 +0000832 ((DeclContext *)S->getEntity())->isTransparentContext())
833 S = S->getParent();
834
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000835 // Add scoped declarations into their context, so that they can be
836 // found later. Declarations without a context won't be inserted
837 // into any context.
John McCall759e32b2009-08-31 22:39:49 +0000838 if (AddToContext)
839 CurContext->addDecl(D);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000840
Chandler Carruthf50ef6e2010-02-21 07:08:09 +0000841 // Out-of-line definitions shouldn't be pushed into scope in C++.
842 // Out-of-line variable and function definitions shouldn't even in C.
843 if ((getLangOptions().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
844 D->isOutOfLine())
845 return;
846
847 // Template instantiations should also not be pushed into scope.
848 if (isa<FunctionDecl>(D) &&
849 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregor5ad7c542009-09-28 18:41:37 +0000850 return;
851
John McCall9f3059a2009-10-09 21:13:30 +0000852 // If this replaces anything in the current scope,
853 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
854 IEnd = IdResolver.end();
855 for (; I != IEnd; ++I) {
John McCall48871652010-08-21 09:40:31 +0000856 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
857 S->RemoveDecl(*I);
John McCall9f3059a2009-10-09 21:13:30 +0000858 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000859
John McCall9f3059a2009-10-09 21:13:30 +0000860 // Should only need to replace one decl.
861 break;
Douglas Gregor38feed82009-04-24 02:57:34 +0000862 }
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000863 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000864
John McCall48871652010-08-21 09:40:31 +0000865 S->AddDecl(D);
Douglas Gregor88764cf2011-03-14 21:19:51 +0000866
867 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
868 // Implicitly-generated labels may end up getting generated in an order that
869 // isn't strictly lexical, which breaks name lookup. Be careful to insert
870 // the label at the appropriate place in the identifier chain.
871 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
Douglas Gregord7d7e0d2011-03-24 14:35:16 +0000872 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
Douglas Gregor46c04e72011-03-16 16:39:03 +0000873 if (IDC == CurContext) {
874 if (!S->isDeclScope(*I))
875 continue;
876 } else if (IDC->Encloses(CurContext))
Douglas Gregor88764cf2011-03-14 21:19:51 +0000877 break;
878 }
879
Douglas Gregor46c04e72011-03-16 16:39:03 +0000880 IdResolver.InsertDeclAfter(I, D);
Douglas Gregor88764cf2011-03-14 21:19:51 +0000881 } else {
882 IdResolver.AddDecl(D);
883 }
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +0000884}
885
Douglas Gregordb446112011-03-07 16:54:27 +0000886bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S,
887 bool ExplicitInstantiationOrSpecialization) {
888 return IdResolver.isDeclInScope(D, Ctx, Context, S,
889 ExplicitInstantiationOrSpecialization);
Douglas Gregor505ad492009-09-28 00:47:05 +0000890}
891
John McCallcc14d1f2010-08-24 08:50:51 +0000892Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
893 DeclContext *TargetDC = DC->getPrimaryContext();
894 do {
895 if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
896 if (ScopeDC->getPrimaryContext() == TargetDC)
897 return S;
898 } while ((S = S->getParent()));
899
900 return 0;
901}
902
John McCall1f82f242009-11-18 22:49:29 +0000903static bool isOutOfScopePreviousDeclaration(NamedDecl *,
904 DeclContext*,
905 ASTContext&);
906
907/// Filters out lookup results that don't fall within the given scope
908/// as determined by isDeclInScope.
Richard Smith3f1b5d02011-05-05 21:57:07 +0000909void Sema::FilterLookupForScope(LookupResult &R,
910 DeclContext *Ctx, Scope *S,
911 bool ConsiderLinkage,
912 bool ExplicitInstantiationOrSpecialization) {
John McCall1f82f242009-11-18 22:49:29 +0000913 LookupResult::Filter F = R.makeFilter();
914 while (F.hasNext()) {
915 NamedDecl *D = F.next();
916
Richard Smith3f1b5d02011-05-05 21:57:07 +0000917 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
John McCall1f82f242009-11-18 22:49:29 +0000918 continue;
919
920 if (ConsiderLinkage &&
Richard Smith3f1b5d02011-05-05 21:57:07 +0000921 isOutOfScopePreviousDeclaration(D, Ctx, Context))
John McCall1f82f242009-11-18 22:49:29 +0000922 continue;
923
924 F.erase();
925 }
926
927 F.done();
928}
929
930static bool isUsingDecl(NamedDecl *D) {
931 return isa<UsingShadowDecl>(D) ||
932 isa<UnresolvedUsingTypenameDecl>(D) ||
933 isa<UnresolvedUsingValueDecl>(D);
934}
935
936/// Removes using shadow declarations from the lookup results.
937static void RemoveUsingDecls(LookupResult &R) {
938 LookupResult::Filter F = R.makeFilter();
939 while (F.hasNext())
940 if (isUsingDecl(F.next()))
941 F.erase();
942
943 F.done();
944}
945
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000946/// \brief Check for this common pattern:
947/// @code
948/// class S {
949/// S(const S&); // DO NOT IMPLEMENT
950/// void operator=(const S&); // DO NOT IMPLEMENT
951/// };
952/// @endcode
953static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
954 // FIXME: Should check for private access too but access is set after we get
955 // the decl here.
Alexis Hunt4a8ea102011-05-06 20:44:56 +0000956 if (D->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000957 return false;
958
959 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
960 return CD->isCopyConstructor();
Douglas Gregora1ce1f82010-09-27 22:06:20 +0000961 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
962 return Method->isCopyAssignmentOperator();
963 return false;
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000964}
965
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000966bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
967 assert(D);
Argyrios Kyrtzidis540bc012010-08-13 18:42:29 +0000968
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000969 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
970 return false;
971
972 // Ignore class templates.
Chandler Carruth8e666512011-01-03 19:27:19 +0000973 if (D->getDeclContext()->isDependentContext() ||
974 D->getLexicalDeclContext()->isDependentContext())
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000975 return false;
976
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000977 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000978 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
979 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000980
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000981 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
982 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
983 return false;
984 } else {
985 // 'static inline' functions are used in headers; don't warn.
John McCall8e7d6562010-08-26 03:08:43 +0000986 if (FD->getStorageClass() == SC_Static &&
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000987 FD->isInlineSpecified())
988 return false;
989 }
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000990
Alexis Hunt4a8ea102011-05-06 20:44:56 +0000991 if (FD->doesThisDeclarationHaveABody() &&
John McCalld37d35b2010-10-27 01:41:35 +0000992 Context.DeclMustBeEmitted(FD))
993 return false;
John McCalld37d35b2010-10-27 01:41:35 +0000994 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
995 if (!VD->isFileVarDecl() ||
996 VD->getType().isConstant(Context) ||
997 Context.DeclMustBeEmitted(VD))
998 return false;
999
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001000 if (VD->isStaticDataMember() &&
1001 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1002 return false;
1003
John McCalld37d35b2010-10-27 01:41:35 +00001004 } else {
1005 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001006 }
1007
John McCalld37d35b2010-10-27 01:41:35 +00001008 // Only warn for unused decls internal to the translation unit.
1009 if (D->getLinkage() == ExternalLinkage)
1010 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001011
John McCalld37d35b2010-10-27 01:41:35 +00001012 return true;
1013}
1014
1015void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001016 if (!D)
1017 return;
1018
1019 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1020 const FunctionDecl *First = FD->getFirstDeclaration();
1021 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1022 return; // First should already be in the vector.
1023 }
1024
1025 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1026 const VarDecl *First = VD->getFirstDeclaration();
1027 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1028 return; // First should already be in the vector.
1029 }
1030
1031 if (ShouldWarnIfUnusedFileScopedDecl(D))
1032 UnusedFileScopedDecls.push_back(D);
1033 }
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00001034
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001035static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall67da35c2010-02-04 22:26:26 +00001036 if (D->isInvalidDecl())
1037 return false;
1038
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001039 if (D->isUsed() || D->hasAttr<UnusedAttr>())
1040 return false;
John McCall67da35c2010-02-04 22:26:26 +00001041
Chris Lattnercab02a62011-02-17 20:34:02 +00001042 if (isa<LabelDecl>(D))
1043 return true;
1044
John McCall67da35c2010-02-04 22:26:26 +00001045 // White-list anything that isn't a local variable.
1046 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1047 !D->getDeclContext()->isFunctionOrMethod())
1048 return false;
1049
1050 // Types of valid local variables should be complete, so this should succeed.
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001051 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
John McCallcef15822010-03-31 02:47:45 +00001052
1053 // White-list anything with an __attribute__((unused)) type.
1054 QualType Ty = VD->getType();
1055
1056 // Only look at the outermost level of typedef.
1057 if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) {
1058 if (TT->getDecl()->hasAttr<UnusedAttr>())
1059 return false;
1060 }
1061
Douglas Gregor14f232e2010-05-08 23:05:03 +00001062 // If we failed to complete the type for some reason, or if the type is
1063 // dependent, don't diagnose the variable.
1064 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregor19defcd2010-04-27 16:20:13 +00001065 return false;
1066
John McCallcef15822010-03-31 02:47:45 +00001067 if (const TagType *TT = Ty->getAs<TagType>()) {
1068 const TagDecl *Tag = TT->getDecl();
1069 if (Tag->hasAttr<UnusedAttr>())
1070 return false;
1071
1072 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Douglas Gregor14f232e2010-05-08 23:05:03 +00001073 // FIXME: Checking for the presence of a user-declared constructor
1074 // isn't completely accurate; we'd prefer to check that the initializer
1075 // has no side effects.
1076 if (RD->hasUserDeclaredConstructor() || !RD->hasTrivialDestructor())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001077 return false;
1078 }
1079 }
John McCallcef15822010-03-31 02:47:45 +00001080
1081 // TODO: __attribute__((unused)) templates?
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001082 }
1083
John McCall67da35c2010-02-04 22:26:26 +00001084 return true;
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001085}
1086
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001087/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1088/// unless they are marked attr(unused).
Douglas Gregor14f232e2010-05-08 23:05:03 +00001089void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1090 if (!ShouldDiagnoseUnusedDecl(D))
1091 return;
1092
Chris Lattnercab02a62011-02-17 20:34:02 +00001093 unsigned DiagID;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001094 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
Chris Lattnercab02a62011-02-17 20:34:02 +00001095 DiagID = diag::warn_unused_exception_param;
1096 else if (isa<LabelDecl>(D))
1097 DiagID = diag::warn_unused_label;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001098 else
Chris Lattnercab02a62011-02-17 20:34:02 +00001099 DiagID = diag::warn_unused_variable;
1100
1101 Diag(D->getLocation(), DiagID) << D->getDeclName();
Douglas Gregor14f232e2010-05-08 23:05:03 +00001102}
1103
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001104static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1105 // Verify that we have no forward references left. If so, there was a goto
1106 // or address of a label taken, but no definition of it. Label fwd
1107 // definitions are indicated with a null substmt.
1108 if (L->getStmt() == 0)
1109 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1110}
1111
Steve Naroffc62adb62007-10-09 22:01:59 +00001112void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001113 if (S->decl_empty()) return;
Douglas Gregor5101c242008-12-05 18:15:24 +00001114 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump11289f42009-09-09 15:08:12 +00001115 "Scope shouldn't contain decls!");
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001116
Chris Lattner302b4be2006-11-19 02:31:38 +00001117 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1118 I != E; ++I) {
John McCall48871652010-08-21 09:40:31 +00001119 Decl *TmpD = (*I);
Steve Naroff9324db12007-09-13 18:10:37 +00001120 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001121
Douglas Gregor91f84212008-12-11 16:49:14 +00001122 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1123 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001124
Douglas Gregor91f84212008-12-11 16:49:14 +00001125 if (!D->getDeclName()) continue;
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001126
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00001127 // Diagnose unused variables in this scope.
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00001128 if (!S->hasErrorOccurred())
Douglas Gregor14f232e2010-05-08 23:05:03 +00001129 DiagnoseUnusedDecl(D);
1130
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001131 // If this was a forward reference to a label, verify it was defined.
1132 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1133 CheckPoppedLabel(LD, *this);
1134
Douglas Gregor91f84212008-12-11 16:49:14 +00001135 // Remove this name from our lexical scope.
1136 IdResolver.RemoveDecl(D);
Chris Lattner302b4be2006-11-19 02:31:38 +00001137 }
1138}
1139
Douglas Gregor1c283312010-08-11 12:19:30 +00001140/// \brief Look for an Objective-C class in the translation unit.
1141///
1142/// \param Id The name of the Objective-C class we're looking for. If
1143/// typo-correction fixes this name, the Id will be updated
1144/// to the fixed name.
1145///
1146/// \param IdLoc The location of the name in the translation unit.
1147///
1148/// \param TypoCorrection If true, this routine will attempt typo correction
1149/// if there is no class with the given name.
1150///
1151/// \returns The declaration of the named Objective-C class, or NULL if the
1152/// class could not be found.
1153ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1154 SourceLocation IdLoc,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001155 bool DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001156 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1157 // creation from this context.
1158 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1159
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001160 if (!IDecl && DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001161 // Perform typo correction at the given location, but only if we
1162 // find an Objective-C class name.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001163 TypoCorrection C;
1164 if ((C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1165 TUScope, NULL, NULL, false, CTC_NoKeywords)) &&
1166 (IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>())) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001167 Diag(IdLoc, diag::err_undef_interface_suggest)
1168 << Id << IDecl->getDeclName()
1169 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
1170 Diag(IDecl->getLocation(), diag::note_previous_decl)
1171 << IDecl->getDeclName();
1172
1173 Id = IDecl->getIdentifier();
1174 }
1175 }
1176
1177 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1178}
1179
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001180/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1181/// from S, where a non-field would be declared. This routine copes
1182/// with the difference between C and C++ scoping rules in structs and
1183/// unions. For example, the following code is well-formed in C but
1184/// ill-formed in C++:
1185/// @code
1186/// struct S6 {
1187/// enum { BAR } e;
1188/// };
Mike Stump11289f42009-09-09 15:08:12 +00001189///
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001190/// void test_S6() {
1191/// struct S6 a;
1192/// a.e = BAR;
1193/// }
1194/// @endcode
1195/// For the declaration of BAR, this routine will return a different
1196/// scope. The scope S will be the scope of the unnamed enumeration
1197/// within S6. In C++, this routine will return the scope associated
1198/// with S6, because the enumeration's scope is a transparent
1199/// context but structures can contain non-field names. In C, this
1200/// routine will return the translation unit scope, since the
1201/// enumeration's scope is a transparent context and structures cannot
1202/// contain non-field names.
1203Scope *Sema::getNonFieldDeclScope(Scope *S) {
1204 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Mike Stump11289f42009-09-09 15:08:12 +00001205 (S->getEntity() &&
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001206 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
1207 (S->isClassScope() && !getLangOptions().CPlusPlus))
1208 S = S->getParent();
1209 return S;
1210}
1211
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001212/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1213/// file scope. lazily create a decl for it. ForRedeclaration is true
1214/// if we're creating this built-in in anticipation of redeclaring the
1215/// built-in.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001216NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001217 Scope *S, bool ForRedeclaration,
1218 SourceLocation Loc) {
Chris Lattner9561a0b2007-01-28 08:20:04 +00001219 Builtin::ID BID = (Builtin::ID)bid;
1220
Chris Lattnerecd79c62009-06-14 00:45:47 +00001221 ASTContext::GetBuiltinTypeError Error;
Mike Stump11289f42009-09-09 15:08:12 +00001222 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor538c3d82009-02-14 01:52:53 +00001223 switch (Error) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00001224 case ASTContext::GE_None:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001225 // Okay
1226 break;
1227
Mike Stump93246cc2009-07-28 23:57:15 +00001228 case ASTContext::GE_Missing_stdio:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001229 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001230 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
Douglas Gregor538c3d82009-02-14 01:52:53 +00001231 << Context.BuiltinInfo.GetName(BID);
1232 return 0;
Mike Stumpa4de80b2009-07-28 02:25:19 +00001233
Mike Stump93246cc2009-07-28 23:57:15 +00001234 case ASTContext::GE_Missing_setjmp:
Mike Stumpa4de80b2009-07-28 02:25:19 +00001235 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001236 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
Mike Stumpa4de80b2009-07-28 02:25:19 +00001237 << Context.BuiltinInfo.GetName(BID);
1238 return 0;
Douglas Gregor538c3d82009-02-14 01:52:53 +00001239 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001240
1241 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1242 Diag(Loc, diag::ext_implicit_lib_function_decl)
1243 << Context.BuiltinInfo.GetName(BID)
1244 << R;
Douglas Gregor9eebd972009-02-16 21:58:21 +00001245 if (Context.BuiltinInfo.getHeaderName(BID) &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001246 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
Chris Lattneraf73cf62009-04-16 03:59:32 +00001247 != Diagnostic::Ignored)
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001248 Diag(Loc, diag::note_please_include_header)
1249 << Context.BuiltinInfo.getHeaderName(BID)
1250 << Context.BuiltinInfo.GetName(BID);
1251 }
1252
Argyrios Kyrtzidis6d053032008-04-17 14:47:13 +00001253 FunctionDecl *New = FunctionDecl::Create(Context,
1254 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001255 Loc, Loc, II, R, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00001256 SC_Extern,
1257 SC_None, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00001258 /*hasPrototype=*/true);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001259 New->setImplicit();
1260
Chris Lattner4dd27102008-05-05 22:18:14 +00001261 // Create Decl objects for each parameter, adding them to the
1262 // FunctionDecl.
John McCall424cec92011-01-19 06:33:43 +00001263 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner4dd27102008-05-05 22:18:14 +00001264 llvm::SmallVector<ParmVarDecl*, 16> Params;
John McCall8fb0d9d2011-05-01 22:35:37 +00001265 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1266 ParmVarDecl *parm =
1267 ParmVarDecl::Create(Context, New, SourceLocation(),
1268 SourceLocation(), 0,
1269 FT->getArgType(i), /*TInfo=*/0,
1270 SC_None, SC_None, 0);
1271 parm->setScopeInfo(0, i);
1272 Params.push_back(parm);
1273 }
Douglas Gregord5058122010-02-11 01:19:42 +00001274 New->setParams(Params.data(), Params.size());
Chris Lattner4dd27102008-05-05 22:18:14 +00001275 }
Mike Stump11289f42009-09-09 15:08:12 +00001276
1277 AddKnownFunctionAttributes(New);
1278
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001279 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregorc72e6452009-01-09 18:51:29 +00001280 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1281 // relate Scopes to DeclContexts, and probably eliminate CurContext
1282 // entirely, but we're not there yet.
1283 DeclContext *SavedContext = CurContext;
1284 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001285 PushOnScopeChains(New, TUScope);
Douglas Gregorc72e6452009-01-09 18:51:29 +00001286 CurContext = SavedContext;
Chris Lattner9561a0b2007-01-28 08:20:04 +00001287 return New;
1288}
1289
Richard Smithdda56e42011-04-15 14:24:37 +00001290/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001291/// same name and scope as a previous declaration 'Old'. Figure out
1292/// how to resolve this situation, merging decls or emitting
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001293/// diagnostics as appropriate. If there was an error, set New to be invalid.
Chris Lattner01564d92007-01-27 19:27:06 +00001294///
Richard Smithdda56e42011-04-15 14:24:37 +00001295void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
John McCall1f82f242009-11-18 22:49:29 +00001296 // If the new decl is known invalid already, don't bother doing any
1297 // merging checks.
1298 if (New->isInvalidDecl()) return;
Mike Stump11289f42009-09-09 15:08:12 +00001299
Steve Naroff44cfcb62008-09-09 14:32:20 +00001300 // Allow multiple definitions for ObjC built-in typedefs.
1301 // FIXME: Verify the underlying types are equivalent!
1302 if (getLangOptions().ObjC1) {
Chris Lattner66e32812008-11-20 05:41:43 +00001303 const IdentifierInfo *TypeID = New->getIdentifier();
1304 switch (TypeID->getLength()) {
1305 default: break;
Mike Stump11289f42009-09-09 15:08:12 +00001306 case 2:
Chris Lattner66e32812008-11-20 05:41:43 +00001307 if (!TypeID->isStr("id"))
1308 break;
David Chisnall9f57c292009-08-17 16:35:33 +00001309 Context.ObjCIdRedefinitionType = New->getUnderlyingType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001310 // Install the built-in type for 'id', ignoring the current definition.
1311 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1312 return;
Chris Lattner66e32812008-11-20 05:41:43 +00001313 case 5:
1314 if (!TypeID->isStr("Class"))
1315 break;
David Chisnall9f57c292009-08-17 16:35:33 +00001316 Context.ObjCClassRedefinitionType = New->getUnderlyingType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001317 // Install the built-in type for 'Class', ignoring the current definition.
1318 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001319 return;
Chris Lattner66e32812008-11-20 05:41:43 +00001320 case 3:
1321 if (!TypeID->isStr("SEL"))
1322 break;
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00001323 Context.ObjCSelRedefinitionType = New->getUnderlyingType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001324 // Install the built-in type for 'SEL', ignoring the current definition.
1325 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001326 return;
Chris Lattner66e32812008-11-20 05:41:43 +00001327 case 8:
1328 if (!TypeID->isStr("Protocol"))
1329 break;
Steve Naroff44cfcb62008-09-09 14:32:20 +00001330 Context.setObjCProtoType(New->getUnderlyingType());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001331 return;
Steve Naroff44cfcb62008-09-09 14:32:20 +00001332 }
1333 // Fall through - the typedef name was not a builtin type.
1334 }
John McCall1f82f242009-11-18 22:49:29 +00001335
Douglas Gregorfb034662009-01-28 17:15:10 +00001336 // Verify the old decl was also a type.
John McCall91f1a022009-12-30 00:31:22 +00001337 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1338 if (!Old) {
Mike Stump11289f42009-09-09 15:08:12 +00001339 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001340 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00001341
1342 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001343 if (OldD->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +00001344 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall1f82f242009-11-18 22:49:29 +00001345
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001346 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00001347 }
Douglas Gregorfb034662009-01-28 17:15:10 +00001348
John McCall1f82f242009-11-18 22:49:29 +00001349 // If the old declaration is invalid, just give up here.
1350 if (Old->isInvalidDecl())
1351 return New->setInvalidDecl();
1352
Mike Stump11289f42009-09-09 15:08:12 +00001353 // Determine the "old" type we'll use for checking and diagnostics.
Douglas Gregorfb034662009-01-28 17:15:10 +00001354 QualType OldType;
Richard Smithdda56e42011-04-15 14:24:37 +00001355 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
Douglas Gregorfb034662009-01-28 17:15:10 +00001356 OldType = OldTypedef->getUnderlyingType();
1357 else
1358 OldType = Context.getTypeDeclType(Old);
1359
Chris Lattnerf9c49e52008-07-25 18:44:27 +00001360 // If the typedef types are not identical, reject them in all languages and
1361 // with any extensions enabled.
Douglas Gregorfb034662009-01-28 17:15:10 +00001362
Mike Stump11289f42009-09-09 15:08:12 +00001363 if (OldType != New->getUnderlyingType() &&
1364 Context.getCanonicalType(OldType) !=
Chris Lattnerf9c49e52008-07-25 18:44:27 +00001365 Context.getCanonicalType(New->getUnderlyingType())) {
Richard Smithdda56e42011-04-15 14:24:37 +00001366 int Kind = 0;
1367 if (isa<TypeAliasDecl>(Old))
1368 Kind = 1;
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00001369 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Richard Smithdda56e42011-04-15 14:24:37 +00001370 << Kind << New->getUnderlyingType() << OldType;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001371 if (Old->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +00001372 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001373 return New->setInvalidDecl();
Chris Lattnerf9c49e52008-07-25 18:44:27 +00001374 }
Mike Stump11289f42009-09-09 15:08:12 +00001375
John McCall91f1a022009-12-30 00:31:22 +00001376 // The types match. Link up the redeclaration chain if the old
1377 // declaration was a typedef.
Nick Lewycky0bdf13e2011-07-02 02:05:12 +00001378 // FIXME: this is a potential source of weirdness if the type
John McCall91f1a022009-12-30 00:31:22 +00001379 // spellings don't match exactly.
Richard Smithdda56e42011-04-15 14:24:37 +00001380 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old))
1381 New->setPreviousDeclaration(Typedef);
John McCall91f1a022009-12-30 00:31:22 +00001382
Steve Naroff7cae42b2009-07-10 23:34:53 +00001383 if (getLangOptions().Microsoft)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001384 return;
Eli Friedman61b529f2008-06-11 06:20:39 +00001385
Chris Lattner2581fc32009-04-17 22:04:20 +00001386 if (getLangOptions().CPlusPlus) {
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001387 // C++ [dcl.typedef]p2:
1388 // In a given non-class scope, a typedef specifier can be used to
1389 // redefine the name of any type declared in that scope to refer
1390 // to the type to which it already refers.
Chris Lattner2581fc32009-04-17 22:04:20 +00001391 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001392 return;
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001393
1394 // C++0x [dcl.typedef]p4:
1395 // In a given class scope, a typedef specifier can be used to redefine
1396 // any class-name declared in that scope that is not also a typedef-name
1397 // to refer to the type to which it already refers.
1398 //
1399 // This wording came in via DR424, which was a correction to the
1400 // wording in DR56, which accidentally banned code like:
1401 //
1402 // struct S {
1403 // typedef struct A { } A;
1404 // };
1405 //
1406 // in the C++03 standard. We implement the C++0x semantics, which
1407 // allow the above but disallow
1408 //
1409 // struct S {
1410 // typedef int I;
1411 // typedef int I;
1412 // };
1413 //
1414 // since that was the intent of DR56.
Richard Smithdda56e42011-04-15 14:24:37 +00001415 if (!isa<TypedefNameDecl>(Old))
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001416 return;
1417
Chris Lattner2581fc32009-04-17 22:04:20 +00001418 Diag(New->getLocation(), diag::err_redefinition)
1419 << New->getDeclName();
1420 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001421 return New->setInvalidDecl();
Daniel Dunbar84b70f72008-09-12 18:10:20 +00001422 }
Eli Friedman61b529f2008-06-11 06:20:39 +00001423
Chris Lattner2581fc32009-04-17 22:04:20 +00001424 // If we have a redefinition of a typedef in C, emit a warning. This warning
1425 // is normally mapped to an error, but can be controlled with
Eli Friedman319ce952009-06-04 23:03:07 +00001426 // -Wtypedef-redefinition. If either the original or the redefinition is
1427 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner30d0cfd2010-03-01 20:59:53 +00001428 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman319ce952009-06-04 23:03:07 +00001429 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1430 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattner9a845892009-04-27 01:46:12 +00001431 return;
Mike Stump11289f42009-09-09 15:08:12 +00001432
Chris Lattner2581fc32009-04-17 22:04:20 +00001433 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1434 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001435 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001436 return;
Chris Lattner01564d92007-01-27 19:27:06 +00001437}
1438
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001439/// DeclhasAttr - returns true if decl Declaration already has the target
1440/// attribute.
Mike Stump11289f42009-09-09 15:08:12 +00001441static bool
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001442DeclHasAttr(const Decl *D, const Attr *A) {
1443 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1444 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1445 if ((*i)->getKind() == A->getKind()) {
1446 // FIXME: Don't hardcode this check
1447 if (OA && isa<OwnershipAttr>(*i))
1448 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
Chris Lattner84966392008-03-03 03:28:21 +00001449 return true;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001450 }
Chris Lattner84966392008-03-03 03:28:21 +00001451
1452 return false;
1453}
1454
John McCallf79e87d2011-03-02 04:00:57 +00001455/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
1456static void mergeDeclAttributes(Decl *newDecl, const Decl *oldDecl,
1457 ASTContext &C) {
1458 if (!oldDecl->hasAttrs())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001459 return;
John McCallf79e87d2011-03-02 04:00:57 +00001460
1461 bool foundAny = newDecl->hasAttrs();
1462
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001463 // Ensure that any moving of objects within the allocated map is done before
1464 // we process them.
John McCallf79e87d2011-03-02 04:00:57 +00001465 if (!foundAny) newDecl->setAttrs(AttrVec());
1466
Peter Collingbourneab8bc062011-01-21 02:08:36 +00001467 for (specific_attr_iterator<InheritableAttr>
John McCallf79e87d2011-03-02 04:00:57 +00001468 i = oldDecl->specific_attr_begin<InheritableAttr>(),
1469 e = oldDecl->specific_attr_end<InheritableAttr>(); i != e; ++i) {
1470 if (!DeclHasAttr(newDecl, *i)) {
1471 InheritableAttr *newAttr = cast<InheritableAttr>((*i)->clone(C));
1472 newAttr->setInherited(true);
1473 newDecl->addAttr(newAttr);
1474 foundAny = true;
Chris Lattner84966392008-03-03 03:28:21 +00001475 }
1476 }
John McCallf79e87d2011-03-02 04:00:57 +00001477
1478 if (!foundAny) newDecl->dropAttrs();
1479}
1480
1481/// mergeParamDeclAttributes - Copy attributes from the old parameter
1482/// to the new one.
1483static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
1484 const ParmVarDecl *oldDecl,
1485 ASTContext &C) {
1486 if (!oldDecl->hasAttrs())
1487 return;
1488
1489 bool foundAny = newDecl->hasAttrs();
1490
1491 // Ensure that any moving of objects within the allocated map is
1492 // done before we process them.
1493 if (!foundAny) newDecl->setAttrs(AttrVec());
1494
1495 for (specific_attr_iterator<InheritableParamAttr>
1496 i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
1497 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
1498 if (!DeclHasAttr(newDecl, *i)) {
1499 InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C));
1500 newAttr->setInherited(true);
1501 newDecl->addAttr(newAttr);
1502 foundAny = true;
1503 }
1504 }
1505
1506 if (!foundAny) newDecl->dropAttrs();
Chris Lattner84966392008-03-03 03:28:21 +00001507}
1508
Dan Gohman28ade552010-07-26 21:25:24 +00001509namespace {
1510
Douglas Gregora74a2972009-03-06 22:43:54 +00001511/// Used in MergeFunctionDecl to keep track of function parameters in
1512/// C.
1513struct GNUCompatibleParamWarning {
1514 ParmVarDecl *OldParm;
1515 ParmVarDecl *NewParm;
1516 QualType PromotedType;
1517};
1518
Dan Gohman28ade552010-07-26 21:25:24 +00001519}
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001520
1521/// getSpecialMember - get the special member enum for a method.
Anders Carlsson05bf0092010-04-22 05:40:53 +00001522Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001523 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001524 if (Ctor->isDefaultConstructor())
1525 return Sema::CXXDefaultConstructor;
Alexis Huntd051b872011-05-26 01:26:05 +00001526
1527 if (Ctor->isCopyConstructor())
1528 return Sema::CXXCopyConstructor;
1529
1530 if (Ctor->isMoveConstructor())
1531 return Sema::CXXMoveConstructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00001532 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001533 return Sema::CXXDestructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00001534 } else if (MD->isCopyAssignmentOperator()) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001535 return Sema::CXXCopyAssignment;
Alexis Hunt119c10e2011-05-25 23:16:36 +00001536 }
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001537
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001538 return Sema::CXXInvalid;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001539}
1540
Sebastian Redl243d9052010-06-09 21:17:41 +00001541/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisfea48452010-02-18 02:00:42 +00001542/// only extern inline functions can be redefined, and even then only in
1543/// GNU89 mode.
1544static bool canRedefineFunction(const FunctionDecl *FD,
1545 const LangOptions& LangOpts) {
Eli Friedman51dd0182011-06-13 23:56:42 +00001546 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
1547 !LangOpts.CPlusPlus &&
Charles Davisfea48452010-02-18 02:00:42 +00001548 FD->isInlineSpecified() &&
John McCall8e7d6562010-08-26 03:08:43 +00001549 FD->getStorageClass() == SC_Extern);
Charles Davisfea48452010-02-18 02:00:42 +00001550}
1551
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001552/// MergeFunctionDecl - We just parsed a function 'New' from
1553/// declarator D which has the same name and scope as a previous
1554/// declaration 'Old'. Figure out how to resolve this situation,
1555/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001556///
1557/// In C++, New and Old must be declarations that are not
1558/// overloaded. Use IsOverload to determine whether New and Old are
1559/// overloaded, and to select the Old declaration that New should be
1560/// merged with.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001561///
1562/// Returns true if there was an error, false otherwise.
1563bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +00001564 // Verify the old decl was also a function.
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001565 FunctionDecl *Old = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001566 if (FunctionTemplateDecl *OldFunctionTemplate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001567 = dyn_cast<FunctionTemplateDecl>(OldD))
1568 Old = OldFunctionTemplate->getTemplatedDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001569 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001570 Old = dyn_cast<FunctionDecl>(OldD);
Chris Lattnerc511efb2007-01-27 19:32:14 +00001571 if (!Old) {
John McCalle29c5cd2009-12-10 19:51:03 +00001572 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
1573 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
1574 Diag(Shadow->getTargetDecl()->getLocation(),
1575 diag::note_using_decl_target);
1576 Diag(Shadow->getUsingDecl()->getLocation(),
1577 diag::note_using_decl) << 0;
1578 return true;
1579 }
1580
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00001581 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001582 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001583 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001584 return true;
Chris Lattnerc511efb2007-01-27 19:32:14 +00001585 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001586
1587 // Determine whether the previous declaration was a definition,
1588 // implicit declaration, or a declaration.
1589 diag::kind PrevDiag;
1590 if (Old->isThisDeclarationADefinition())
Chris Lattner0369c572008-11-23 23:12:31 +00001591 PrevDiag = diag::note_previous_definition;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001592 else if (Old->isImplicit())
1593 PrevDiag = diag::note_previous_implicit_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00001594 else
Chris Lattner0369c572008-11-23 23:12:31 +00001595 PrevDiag = diag::note_previous_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00001596
Chris Lattnerfc4379f2008-04-06 23:10:54 +00001597 QualType OldQType = Context.getCanonicalType(Old->getType());
1598 QualType NewQType = Context.getCanonicalType(New->getType());
Mike Stump11289f42009-09-09 15:08:12 +00001599
Charles Davisfea48452010-02-18 02:00:42 +00001600 // Don't complain about this if we're in GNU89 mode and the old function
1601 // is an extern inline function.
Douglas Gregore62c0a42009-02-24 01:23:02 +00001602 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCall8e7d6562010-08-26 03:08:43 +00001603 New->getStorageClass() == SC_Static &&
1604 Old->getStorageClass() != SC_Static &&
Charles Davisfea48452010-02-18 02:00:42 +00001605 !canRedefineFunction(Old, getLangOptions())) {
Francois Pichet6841a122011-04-22 19:50:06 +00001606 if (getLangOptions().Microsoft) {
1607 Diag(New->getLocation(), diag::warn_static_non_static) << New;
1608 Diag(Old->getLocation(), PrevDiag);
1609 } else {
1610 Diag(New->getLocation(), diag::err_static_non_static) << New;
1611 Diag(Old->getLocation(), PrevDiag);
1612 return true;
1613 }
Douglas Gregore62c0a42009-02-24 01:23:02 +00001614 }
1615
John McCallcddbad02010-02-04 05:44:44 +00001616 // If a function is first declared with a calling convention, but is
1617 // later declared or defined without one, the second decl assumes the
1618 // calling convention of the first.
1619 //
1620 // For the new decl, we have to look at the NON-canonical type to tell the
1621 // difference between a function that really doesn't have a calling
1622 // convention and one that is declared cdecl. That's because in
1623 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
1624 // because it is the default calling convention.
1625 //
1626 // Note also that we DO NOT return at this point, because we still have
1627 // other tests to run.
John McCall4f5019e2010-12-19 02:44:49 +00001628 const FunctionType *OldType = cast<FunctionType>(OldQType);
John McCallcddbad02010-02-04 05:44:44 +00001629 const FunctionType *NewType = New->getType()->getAs<FunctionType>();
John McCall4f5019e2010-12-19 02:44:49 +00001630 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
1631 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
1632 bool RequiresAdjustment = false;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001633 if (OldTypeInfo.getCC() != CC_Default &&
1634 NewTypeInfo.getCC() == CC_Default) {
John McCall4f5019e2010-12-19 02:44:49 +00001635 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
1636 RequiresAdjustment = true;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001637 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
1638 NewTypeInfo.getCC())) {
John McCallcddbad02010-02-04 05:44:44 +00001639 // Calling conventions really aren't compatible, so complain.
John McCallab26cfa2010-02-05 21:31:56 +00001640 Diag(New->getLocation(), diag::err_cconv_change)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001641 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
1642 << (OldTypeInfo.getCC() == CC_Default)
1643 << (OldTypeInfo.getCC() == CC_Default ? "" :
1644 FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
John McCallab26cfa2010-02-05 21:31:56 +00001645 Diag(Old->getLocation(), diag::note_previous_declaration);
John McCallcddbad02010-02-04 05:44:44 +00001646 return true;
1647 }
1648
John McCallab26cfa2010-02-05 21:31:56 +00001649 // FIXME: diagnose the other way around?
John McCall4f5019e2010-12-19 02:44:49 +00001650 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
1651 NewTypeInfo = NewTypeInfo.withNoReturn(true);
1652 RequiresAdjustment = true;
John McCallab26cfa2010-02-05 21:31:56 +00001653 }
1654
Douglas Gregor77e274f2010-06-18 21:30:25 +00001655 // Merge regparm attribute.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00001656 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
1657 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
1658 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregor77e274f2010-06-18 21:30:25 +00001659 Diag(New->getLocation(), diag::err_regparm_mismatch)
1660 << NewType->getRegParmType()
1661 << OldType->getRegParmType();
1662 Diag(Old->getLocation(), diag::note_previous_declaration);
1663 return true;
1664 }
John McCall4f5019e2010-12-19 02:44:49 +00001665
1666 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
1667 RequiresAdjustment = true;
1668 }
1669
1670 if (RequiresAdjustment) {
1671 NewType = Context.adjustFunctionType(NewType, NewTypeInfo);
1672 New->setType(QualType(NewType, 0));
1673 NewQType = Context.getCanonicalType(New->getType());
Douglas Gregor77e274f2010-06-18 21:30:25 +00001674 }
1675
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001676 if (getLangOptions().CPlusPlus) {
1677 // (C++98 13.1p2):
1678 // Certain function declarations cannot be overloaded:
Mike Stump11289f42009-09-09 15:08:12 +00001679 // -- Function declarations that differ only in the return type
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001680 // cannot be overloaded.
John McCall4f5019e2010-12-19 02:44:49 +00001681 QualType OldReturnType = OldType->getResultType();
1682 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00001683 QualType ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001684 if (OldReturnType != NewReturnType) {
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00001685 if (NewReturnType->isObjCObjectPointerType()
1686 && OldReturnType->isObjCObjectPointerType())
1687 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
1688 if (ResQT.isNull()) {
Argyrios Kyrtzidis3d320862011-02-05 05:54:49 +00001689 if (New->isCXXClassMember() && New->isOutOfLine())
1690 Diag(New->getLocation(),
1691 diag::err_member_def_does_not_match_ret_type) << New;
1692 else
1693 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00001694 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1695 return true;
1696 }
1697 else
1698 NewQType = ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001699 }
1700
1701 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
John McCall43314ab2010-04-13 07:45:41 +00001702 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001703 if (OldMethod && NewMethod) {
John McCall43314ab2010-04-13 07:45:41 +00001704 // Preserve triviality.
1705 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichetc2fac712011-05-14 19:17:07 +00001706
John McCall43314ab2010-04-13 07:45:41 +00001707 bool isFriend = NewMethod->getFriendObjectKind();
1708
Francois Pichetc2fac712011-05-14 19:17:07 +00001709 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord()) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001710 // -- Member function declarations with the same name and the
1711 // same parameter types cannot be overloaded if any of them
1712 // is a static member function declaration.
1713 if (OldMethod->isStatic() || NewMethod->isStatic()) {
1714 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
1715 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1716 return true;
1717 }
1718
1719 // C++ [class.mem]p1:
1720 // [...] A member shall not be declared twice in the
1721 // member-specification, except that a nested class or member
1722 // class template can be declared and then later defined.
1723 unsigned NewDiag;
1724 if (isa<CXXConstructorDecl>(OldMethod))
1725 NewDiag = diag::err_constructor_redeclared;
1726 else if (isa<CXXDestructorDecl>(NewMethod))
1727 NewDiag = diag::err_destructor_redeclared;
1728 else if (isa<CXXConversionDecl>(NewMethod))
1729 NewDiag = diag::err_conv_function_redeclared;
1730 else
1731 NewDiag = diag::err_member_redeclared;
1732
1733 Diag(New->getLocation(), NewDiag);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001734 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
John McCall43314ab2010-04-13 07:45:41 +00001735
1736 // Complain if this is an explicit declaration of a special
1737 // member that was initially declared implicitly.
1738 //
1739 // As an exception, it's okay to befriend such methods in order
1740 // to permit the implicit constructor/destructor/operator calls.
1741 } else if (OldMethod->isImplicit()) {
1742 if (isFriend) {
1743 NewMethod->setImplicit();
1744 } else {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001745 Diag(NewMethod->getLocation(),
1746 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson05bf0092010-04-22 05:40:53 +00001747 << New << getSpecialMember(OldMethod);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001748 return true;
1749 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00001750 } else if (OldMethod->isExplicitlyDefaulted()) {
1751 Diag(NewMethod->getLocation(),
1752 diag::err_definition_of_explicitly_defaulted_member)
1753 << getSpecialMember(OldMethod);
1754 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001755 }
1756 }
1757
1758 // (C++98 8.3.5p3):
1759 // All declarations for a function shall agree exactly in both the
1760 // return type and the parameter-type-list.
John McCall4f5019e2010-12-19 02:44:49 +00001761 // We also want to respect all the extended bits except noreturn.
1762
1763 // noreturn should now match unless the old type info didn't have it.
1764 QualType OldQTypeForComparison = OldQType;
1765 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
1766 assert(OldQType == QualType(OldType, 0));
1767 const FunctionType *OldTypeForComparison
1768 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
1769 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
1770 assert(OldQTypeForComparison.isCanonical());
1771 }
1772
1773 if (OldQTypeForComparison == NewQType)
Douglas Gregore62c0a42009-02-24 01:23:02 +00001774 return MergeCompatibleFunctionDecls(New, Old);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001775
1776 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor89f238c2008-04-21 02:02:58 +00001777 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001778
1779 // C: Function types need to be compatible, not identical. This handles
Steve Naroff012484d2008-01-14 20:51:29 +00001780 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001781 if (!getLangOptions().CPlusPlus &&
Eli Friedman47f77112008-08-22 00:56:42 +00001782 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall9dd450b2009-09-21 23:43:11 +00001783 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
1784 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001785 const FunctionProtoType *OldProto = 0;
1786 if (isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregora74a2972009-03-06 22:43:54 +00001787 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregorbcbf8632009-02-16 18:20:44 +00001788 // The old declaration provided a function prototype, but the
1789 // new declaration does not. Merge in the prototype.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001790 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Douglas Gregorbcbf8632009-02-16 18:20:44 +00001791 llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
1792 OldProto->arg_type_end());
1793 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
Jay Foad7d0479f2009-05-21 09:52:38 +00001794 ParamTypes.data(), ParamTypes.size(),
John McCalldb40c7f2010-12-14 08:05:40 +00001795 OldProto->getExtProtoInfo());
Douglas Gregorbcbf8632009-02-16 18:20:44 +00001796 New->setType(NewQType);
Anders Carlssone0dd1d52009-05-14 21:46:00 +00001797 New->setHasInheritedPrototype();
Douglas Gregorbfdd6072009-02-16 20:58:07 +00001798
1799 // Synthesize a parameter for each argument type.
1800 llvm::SmallVector<ParmVarDecl*, 16> Params;
Mike Stump11289f42009-09-09 15:08:12 +00001801 for (FunctionProtoType::arg_type_iterator
1802 ParamType = OldProto->arg_type_begin(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00001803 ParamEnd = OldProto->arg_type_end();
1804 ParamType != ParamEnd; ++ParamType) {
1805 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001806 SourceLocation(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00001807 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00001808 *ParamType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00001809 SC_None, SC_None,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001810 0);
John McCall8fb0d9d2011-05-01 22:35:37 +00001811 Param->setScopeInfo(0, Params.size());
Douglas Gregorbfdd6072009-02-16 20:58:07 +00001812 Param->setImplicit();
1813 Params.push_back(Param);
1814 }
1815
Douglas Gregord5058122010-02-11 01:19:42 +00001816 New->setParams(Params.data(), Params.size());
Mike Stump11289f42009-09-09 15:08:12 +00001817 }
Douglas Gregorbcbf8632009-02-16 18:20:44 +00001818
Douglas Gregore62c0a42009-02-24 01:23:02 +00001819 return MergeCompatibleFunctionDecls(New, Old);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001820 }
Chris Lattner45d561a2007-11-06 06:07:26 +00001821
Douglas Gregora74a2972009-03-06 22:43:54 +00001822 // GNU C permits a K&R definition to follow a prototype declaration
1823 // if the declared types of the parameters in the K&R definition
1824 // match the types in the prototype declaration, even when the
1825 // promoted types of the parameters from the K&R definition differ
1826 // from the types in the prototype. GCC then keeps the types from
1827 // the prototype.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001828 //
1829 // If a variadic prototype is followed by a non-variadic K&R definition,
1830 // the K&R definition becomes variadic. This is sort of an edge case, but
1831 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
1832 // C99 6.9.1p8.
Douglas Gregora74a2972009-03-06 22:43:54 +00001833 if (!getLangOptions().CPlusPlus &&
Douglas Gregora74a2972009-03-06 22:43:54 +00001834 Old->hasPrototype() && !New->hasPrototype() &&
John McCall9dd450b2009-09-21 23:43:11 +00001835 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregora74a2972009-03-06 22:43:54 +00001836 Old->getNumParams() == New->getNumParams()) {
1837 llvm::SmallVector<QualType, 16> ArgTypes;
1838 llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump11289f42009-09-09 15:08:12 +00001839 const FunctionProtoType *OldProto
John McCall9dd450b2009-09-21 23:43:11 +00001840 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00001841 const FunctionProtoType *NewProto
John McCall9dd450b2009-09-21 23:43:11 +00001842 = New->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00001843
Douglas Gregora74a2972009-03-06 22:43:54 +00001844 // Determine whether this is the GNU C extension.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001845 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
1846 NewProto->getResultType());
1847 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump11289f42009-09-09 15:08:12 +00001848 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001849 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregora74a2972009-03-06 22:43:54 +00001850 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
1851 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump11289f42009-09-09 15:08:12 +00001852 if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregora74a2972009-03-06 22:43:54 +00001853 NewProto->getArgType(Idx))) {
1854 ArgTypes.push_back(NewParm->getType());
1855 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor17ea3f52010-07-29 15:18:02 +00001856 NewParm->getType(),
1857 /*CompareUnqualified=*/true)) {
Mike Stump11289f42009-09-09 15:08:12 +00001858 GNUCompatibleParamWarning Warn
Douglas Gregora74a2972009-03-06 22:43:54 +00001859 = { OldParm, NewParm, NewProto->getArgType(Idx) };
1860 Warnings.push_back(Warn);
1861 ArgTypes.push_back(NewParm->getType());
1862 } else
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001863 LooseCompatible = false;
Douglas Gregora74a2972009-03-06 22:43:54 +00001864 }
1865
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001866 if (LooseCompatible) {
Douglas Gregora74a2972009-03-06 22:43:54 +00001867 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
1868 Diag(Warnings[Warn].NewParm->getLocation(),
1869 diag::ext_param_promoted_not_compatible_with_prototype)
1870 << Warnings[Warn].PromotedType
1871 << Warnings[Warn].OldParm->getType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00001872 if (Warnings[Warn].OldParm->getLocation().isValid())
1873 Diag(Warnings[Warn].OldParm->getLocation(),
1874 diag::note_previous_declaration);
Douglas Gregora74a2972009-03-06 22:43:54 +00001875 }
1876
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001877 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
1878 ArgTypes.size(),
John McCalldb40c7f2010-12-14 08:05:40 +00001879 OldProto->getExtProtoInfo()));
Douglas Gregora74a2972009-03-06 22:43:54 +00001880 return MergeCompatibleFunctionDecls(New, Old);
1881 }
1882
1883 // Fall through to diagnose conflicting types.
1884 }
1885
Steve Naroff17832a42008-01-16 15:01:34 +00001886 // A function that has already been declared has been redeclared or defined
1887 // with a different type- show appropriate diagnostic
Douglas Gregor15fc9562009-09-12 00:22:50 +00001888 if (unsigned BuiltinID = Old->getBuiltinID()) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001889 // The user has declared a builtin function with an incompatible
1890 // signature.
1891 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
1892 // The function the user is redeclaring is a library-defined
1893 // function like 'malloc' or 'printf'. Warn about the
Douglas Gregor893c2c92009-03-23 17:47:24 +00001894 // redeclaration, then pretend that we don't know about this
1895 // library built-in.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001896 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
1897 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
1898 << Old << Old->getType();
Douglas Gregor893c2c92009-03-23 17:47:24 +00001899 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
1900 Old->setInvalidDecl();
1901 return false;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001902 }
Steve Naroff17832a42008-01-16 15:01:34 +00001903
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001904 PrevDiag = diag::note_previous_builtin_declaration;
1905 }
1906
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001907 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001908 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001909 return true;
Chris Lattner01564d92007-01-27 19:27:06 +00001910}
1911
Douglas Gregore62c0a42009-02-24 01:23:02 +00001912/// \brief Completes the merge of two function declarations that are
Mike Stump11289f42009-09-09 15:08:12 +00001913/// known to be compatible.
Douglas Gregore62c0a42009-02-24 01:23:02 +00001914///
1915/// This routine handles the merging of attributes and other
1916/// properties of function declarations form the old declaration to
1917/// the new declaration, once we know that New is in fact a
1918/// redeclaration of Old.
1919///
1920/// \returns false
1921bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
1922 // Merge the attributes
John McCallf79e87d2011-03-02 04:00:57 +00001923 mergeDeclAttributes(New, Old, Context);
Douglas Gregore62c0a42009-02-24 01:23:02 +00001924
1925 // Merge the storage class.
John McCall8e7d6562010-08-26 03:08:43 +00001926 if (Old->getStorageClass() != SC_Extern &&
1927 Old->getStorageClass() != SC_None)
Douglas Gregor76fe50c2009-04-28 06:37:30 +00001928 New->setStorageClass(Old->getStorageClass());
Douglas Gregore62c0a42009-02-24 01:23:02 +00001929
Douglas Gregore62c0a42009-02-24 01:23:02 +00001930 // Merge "pure" flag.
1931 if (Old->isPure())
1932 New->setPure();
1933
John McCallf79e87d2011-03-02 04:00:57 +00001934 // Merge attributes from the parameters. These can mismatch with K&R
1935 // declarations.
1936 if (New->getNumParams() == Old->getNumParams())
1937 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
1938 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
1939 Context);
1940
Douglas Gregore62c0a42009-02-24 01:23:02 +00001941 if (getLangOptions().CPlusPlus)
1942 return MergeCXXFunctionDecl(New, Old);
1943
1944 return false;
1945}
1946
John McCall31168b02011-06-15 23:02:42 +00001947
John McCallf79e87d2011-03-02 04:00:57 +00001948void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
1949 const ObjCMethodDecl *oldMethod) {
1950 // Merge the attributes.
1951 mergeDeclAttributes(newMethod, oldMethod, Context);
1952
1953 // Merge attributes from the parameters.
1954 for (ObjCMethodDecl::param_iterator oi = oldMethod->param_begin(),
1955 ni = newMethod->param_begin(), ne = newMethod->param_end();
1956 ni != ne; ++ni, ++oi)
Douglas Gregor33823722011-06-11 01:09:30 +00001957 mergeParamDeclAttributes(*ni, *oi, Context);
1958
1959 CheckObjCMethodOverride(newMethod, oldMethod, true);
John McCallf79e87d2011-03-02 04:00:57 +00001960}
1961
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001962/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
1963/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith30482bc2011-02-20 03:19:35 +00001964/// emitting diagnostics as appropriate.
1965///
1966/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
1967/// to here in AddInitializerToDecl and AddCXXDirectInitializerToDecl. We can't
1968/// check them before the initializer is attached.
1969///
1970void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) {
1971 if (New->isInvalidDecl() || Old->isInvalidDecl())
1972 return;
1973
1974 QualType MergedT;
1975 if (getLangOptions().CPlusPlus) {
1976 AutoType *AT = New->getType()->getContainedAutoType();
1977 if (AT && !AT->isDeduced()) {
1978 // We don't know what the new type is until the initializer is attached.
1979 return;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001980 } else if (Context.hasSameType(New->getType(), Old->getType())) {
1981 // These could still be something that needs exception specs checked.
1982 return MergeVarDeclExceptionSpecs(New, Old);
1983 }
Richard Smith30482bc2011-02-20 03:19:35 +00001984 // C++ [basic.link]p10:
1985 // [...] the types specified by all declarations referring to a given
1986 // object or function shall be identical, except that declarations for an
1987 // array object can specify array types that differ by the presence or
1988 // absence of a major array bound (8.3.4).
1989 else if (Old->getType()->isIncompleteArrayType() &&
1990 New->getType()->isArrayType()) {
1991 CanQual<ArrayType> OldArray
1992 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1993 CanQual<ArrayType> NewArray
1994 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1995 if (OldArray->getElementType() == NewArray->getElementType())
1996 MergedT = New->getType();
1997 } else if (Old->getType()->isArrayType() &&
1998 New->getType()->isIncompleteArrayType()) {
1999 CanQual<ArrayType> OldArray
2000 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2001 CanQual<ArrayType> NewArray
2002 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2003 if (OldArray->getElementType() == NewArray->getElementType())
2004 MergedT = Old->getType();
2005 } else if (New->getType()->isObjCObjectPointerType()
2006 && Old->getType()->isObjCObjectPointerType()) {
2007 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2008 Old->getType());
2009 }
2010 } else {
2011 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2012 }
2013 if (MergedT.isNull()) {
2014 Diag(New->getLocation(), diag::err_redefinition_different_type)
2015 << New->getDeclName();
2016 Diag(Old->getLocation(), diag::note_previous_definition);
2017 return New->setInvalidDecl();
2018 }
2019 New->setType(MergedT);
2020}
2021
Chris Lattner01564d92007-01-27 19:27:06 +00002022/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2023/// and scope as a previous declaration 'Old'. Figure out how to resolve this
2024/// situation, merging decls or emitting diagnostics as appropriate.
2025///
Mike Stump11289f42009-09-09 15:08:12 +00002026/// Tentative definition rules (C99 6.9.2p2) are checked by
2027/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroff5bb8f222008-08-08 17:50:35 +00002028/// definitions here, since the initializer hasn't been attached.
Mike Stump11289f42009-09-09 15:08:12 +00002029///
John McCall1f82f242009-11-18 22:49:29 +00002030void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
2031 // If the new decl is already invalid, don't do any other checking.
2032 if (New->isInvalidDecl())
2033 return;
Mike Stump11289f42009-09-09 15:08:12 +00002034
Chris Lattnerc511efb2007-01-27 19:32:14 +00002035 // Verify the old decl was also a variable.
John McCall1f82f242009-11-18 22:49:29 +00002036 VarDecl *Old = 0;
2037 if (!Previous.isSingleResult() ||
2038 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
Chris Lattner651d42d2008-11-20 06:38:18 +00002039 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002040 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00002041 Diag(Previous.getRepresentativeDecl()->getLocation(),
2042 diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002043 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00002044 }
Chris Lattner84966392008-03-03 03:28:21 +00002045
Douglas Gregor2c7d9292010-08-30 14:32:14 +00002046 // C++ [class.mem]p1:
2047 // A member shall not be declared twice in the member-specification [...]
2048 //
2049 // Here, we need only consider static data members.
2050 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
2051 Diag(New->getLocation(), diag::err_duplicate_member)
2052 << New->getIdentifier();
2053 Diag(Old->getLocation(), diag::note_previous_declaration);
2054 New->setInvalidDecl();
2055 }
2056
John McCallf79e87d2011-03-02 04:00:57 +00002057 mergeDeclAttributes(New, Old, Context);
Fariborz Jahanian33e02262011-06-22 22:08:50 +00002058 // Warn if an already-declared variable is made a weak_import in a subsequent declaration
Fariborz Jahanianab578bf2011-06-20 17:50:03 +00002059 if (New->getAttr<WeakImportAttr>() &&
2060 Old->getStorageClass() == SC_None &&
Fariborz Jahanian33e02262011-06-22 22:08:50 +00002061 !Old->getAttr<WeakImportAttr>()) {
2062 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
2063 Diag(Old->getLocation(), diag::note_previous_definition);
2064 // Remove weak_import attribute on new declaration.
Fariborz Jahanian0dfc9502011-06-23 17:50:10 +00002065 New->dropAttr<WeakImportAttr>();
Fariborz Jahanian33e02262011-06-22 22:08:50 +00002066 }
Chris Lattner84966392008-03-03 03:28:21 +00002067
Richard Smith30482bc2011-02-20 03:19:35 +00002068 // Merge the types.
2069 MergeVarDeclTypes(New, Old);
2070 if (New->isInvalidDecl())
2071 return;
Douglas Gregor04e9a032009-03-11 23:52:16 +00002072
Steve Naroff1e787362008-01-30 00:44:01 +00002073 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
John McCall8e7d6562010-08-26 03:08:43 +00002074 if (New->getStorageClass() == SC_Static &&
2075 (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002076 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002077 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002078 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00002079 }
Mike Stump11289f42009-09-09 15:08:12 +00002080 // C99 6.2.2p4:
Douglas Gregor37311622009-03-19 22:01:50 +00002081 // For an identifier declared with the storage-class specifier
2082 // extern in a scope in which a prior declaration of that
2083 // identifier is visible,23) if the prior declaration specifies
2084 // internal or external linkage, the linkage of the identifier at
2085 // the later declaration is the same as the linkage specified at
2086 // the prior declaration. If no prior declaration is visible, or
2087 // if the prior declaration specifies no linkage, then the
2088 // identifier has external linkage.
Douglas Gregord4eca012009-03-23 16:17:01 +00002089 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor37311622009-03-19 22:01:50 +00002090 /* Okay */;
John McCall8e7d6562010-08-26 03:08:43 +00002091 else if (New->getStorageClass() != SC_Static &&
2092 Old->getStorageClass() == SC_Static) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002093 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002094 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002095 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00002096 }
Daniel Dunbar0ca16602009-04-14 02:25:56 +00002097
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00002098 // Check if extern is followed by non-extern and vice-versa.
2099 if (New->hasExternalStorage() &&
2100 !Old->hasLinkage() && Old->isLocalVarDecl()) {
2101 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
2102 Diag(Old->getLocation(), diag::note_previous_definition);
2103 return New->setInvalidDecl();
2104 }
2105 if (Old->hasExternalStorage() &&
2106 !New->hasLinkage() && New->isLocalVarDecl()) {
2107 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
2108 Diag(Old->getLocation(), diag::note_previous_definition);
2109 return New->setInvalidDecl();
2110 }
2111
Steve Naroffa5629372008-09-17 14:05:40 +00002112 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump11289f42009-09-09 15:08:12 +00002113
Daniel Dunbar0ca16602009-04-14 02:25:56 +00002114 // FIXME: The test for external storage here seems wrong? We still
2115 // need to check for mismatches.
2116 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor04e9a032009-03-11 23:52:16 +00002117 // Don't complain about out-of-line definitions of static members.
2118 !(Old->getLexicalDeclContext()->isRecord() &&
2119 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattnere3d20d92008-11-23 21:45:46 +00002120 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002121 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002122 return New->setInvalidDecl();
Steve Naroff6fbf0dc2007-03-16 00:33:25 +00002123 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00002124
Eli Friedmand5c0eed2009-04-19 20:27:55 +00002125 if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
2126 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
2127 Diag(Old->getLocation(), diag::note_previous_definition);
2128 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
2129 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
2130 Diag(Old->getLocation(), diag::note_previous_definition);
2131 }
2132
Sebastian Redlf1842912010-02-02 18:35:11 +00002133 // C++ doesn't have tentative definitions, so go right ahead and check here.
2134 const VarDecl *Def;
Sebastian Redld85be0c2010-02-03 02:08:48 +00002135 if (getLangOptions().CPlusPlus &&
2136 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redlf1842912010-02-02 18:35:11 +00002137 (Def = Old->getDefinition())) {
2138 Diag(New->getLocation(), diag::err_redefinition)
2139 << New->getDeclName();
2140 Diag(Def->getLocation(), diag::note_previous_definition);
2141 New->setInvalidDecl();
2142 return;
2143 }
Fariborz Jahanianad356a12010-06-25 00:05:45 +00002144 // c99 6.2.2 P4.
2145 // For an identifier declared with the storage-class specifier extern in a
2146 // scope in which a prior declaration of that identifier is visible, if
2147 // the prior declaration specifies internal or external linkage, the linkage
2148 // of the identifier at the later declaration is the same as the linkage
2149 // specified at the prior declaration.
2150 // FIXME. revisit this code.
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00002151 if (New->hasExternalStorage() &&
Fariborz Jahanian4f9c9d62010-06-24 18:50:41 +00002152 Old->getLinkage() == InternalLinkage &&
2153 New->getDeclContext() == Old->getDeclContext())
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00002154 New->setStorageClass(Old->getStorageClass());
2155
Douglas Gregor0760fa12009-03-10 23:43:53 +00002156 // Keep a chain of previous declarations.
2157 New->setPreviousDeclaration(Old);
John McCall401982f2010-01-20 21:53:11 +00002158
2159 // Inherit access appropriately.
2160 New->setAccess(Old->getAccess());
Chris Lattner01564d92007-01-27 19:27:06 +00002161}
2162
Chris Lattnerb6738ec2007-01-28 00:38:24 +00002163/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2164/// no declarator (e.g. "struct foo;") is parsed.
John McCall48871652010-08-21 09:40:31 +00002165Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallaa017372011-03-22 23:00:04 +00002166 DeclSpec &DS) {
Chandler Carruth7c9856d2011-05-03 18:35:10 +00002167 return ParsedFreeStandingDeclSpec(S, AS, DS,
2168 MultiTemplateParamsArg(*this, 0, 0));
2169}
2170
2171/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2172/// no declarator (e.g. "struct foo;") is parsed. It also accopts template
2173/// parameters to cope with template friend declarations.
2174Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2175 DeclSpec &DS,
2176 MultiTemplateParamsArg TemplateParams) {
John McCallc3987482009-10-07 23:34:25 +00002177 Decl *TagD = 0;
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002178 TagDecl *Tag = 0;
2179 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
2180 DS.getTypeSpecType() == DeclSpec::TST_struct ||
2181 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002182 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallba7bf592010-08-24 05:47:05 +00002183 TagD = DS.getRepAsDecl();
John McCallc3987482009-10-07 23:34:25 +00002184
2185 if (!TagD) // We probably had an error
John McCall48871652010-08-21 09:40:31 +00002186 return 0;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002187
John McCall07e91c02009-08-06 02:15:43 +00002188 // Note that the above type specs guarantee that the
2189 // type rep is a Decl, whereas in many of the others
2190 // it's a Type.
John McCallc3987482009-10-07 23:34:25 +00002191 Tag = dyn_cast<TagDecl>(TagD);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002192 }
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002193
Nuno Lopese9823fa2009-12-17 11:35:26 +00002194 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
2195 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
2196 // or incomplete types shall not be restrict-qualified."
2197 if (TypeQuals & DeclSpec::TQ_restrict)
2198 Diag(DS.getRestrictSpecLoc(),
2199 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
2200 << DS.getSourceRange();
2201 }
2202
Douglas Gregor3dad8422009-09-26 06:47:28 +00002203 if (DS.isFriendSpecified()) {
John McCallace48cd2010-10-19 01:40:49 +00002204 // If we're dealing with a decl but not a TagDecl, assume that
2205 // whatever routines created it handled the friendship aspect.
2206 if (TagD && !Tag)
John McCall48871652010-08-21 09:40:31 +00002207 return 0;
Chandler Carruth7c9856d2011-05-03 18:35:10 +00002208 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregor3dad8422009-09-26 06:47:28 +00002209 }
John McCallaa017372011-03-22 23:00:04 +00002210
2211 // Track whether we warned about the fact that there aren't any
2212 // declarators.
2213 bool emittedWarning = false;
Douglas Gregor3dad8422009-09-26 06:47:28 +00002214
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002215 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCall53fa7142010-12-24 02:08:15 +00002216 ProcessDeclAttributeList(S, Record, DS.getAttributes().getList());
Chris Lattnerecf328e2009-10-25 22:21:57 +00002217
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002218 if (!Record->getDeclName() && Record->isDefinition() &&
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002219 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
2220 if (getLangOptions().CPlusPlus ||
2221 Record->getDeclContext()->isRecord())
John McCallb54367d2010-05-21 20:45:30 +00002222 return BuildAnonymousStructOrUnion(S, DS, AS, Record);
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002223
Douglas Gregorf19ac0e2010-04-08 21:33:23 +00002224 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002225 << DS.getSourceRange();
John McCallaa017372011-03-22 23:00:04 +00002226 emittedWarning = true;
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002227 }
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002228 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002229
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002230 // Check for Microsoft C extension: anonymous struct.
2231 if (getLangOptions().Microsoft && !getLangOptions().CPlusPlus &&
2232 CurContext->isRecord() &&
2233 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
2234 // Handle 2 kinds of anonymous struct:
2235 // struct STRUCT;
2236 // and
2237 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
2238 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
2239 if ((Record && Record->getDeclName() && !Record->isDefinition()) ||
2240 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
2241 DS.getRepAsType().get()->isStructureType())) {
2242 Diag(DS.getSourceRange().getBegin(), diag::ext_ms_anonymous_struct)
2243 << DS.getSourceRange();
2244 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
2245 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002246 }
Douglas Gregor3dad8422009-09-26 06:47:28 +00002247
Douglas Gregoraa8c9722010-07-13 06:24:26 +00002248 if (getLangOptions().CPlusPlus &&
2249 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
2250 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
2251 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
John McCallaa017372011-03-22 23:00:04 +00002252 !Enum->getIdentifier() && !Enum->isInvalidDecl()) {
Douglas Gregoraa8c9722010-07-13 06:24:26 +00002253 Diag(Enum->getLocation(), diag::ext_no_declarators)
2254 << DS.getSourceRange();
John McCallaa017372011-03-22 23:00:04 +00002255 emittedWarning = true;
2256 }
2257
2258 // Skip all the checks below if we have a type error.
2259 if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD;
Douglas Gregoraa8c9722010-07-13 06:24:26 +00002260
John McCallaa017372011-03-22 23:00:04 +00002261 if (!DS.isMissingDeclaratorOk()) {
Douglas Gregor2d9dde0e2009-01-22 16:23:54 +00002262 // Warn about typedefs of enums without names, since this is an
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00002263 // extension in both Microsoft and GNU.
Douglas Gregor051d8fd2009-01-17 02:55:50 +00002264 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
2265 Tag && isa<EnumDecl>(Tag)) {
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00002266 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
2267 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00002268 return Tag;
Douglas Gregor2b136fe2009-01-13 23:10:51 +00002269 }
2270
Douglas Gregorf19ac0e2010-04-08 21:33:23 +00002271 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
Sebastian Redla2b5e312008-12-28 15:28:59 +00002272 << DS.getSourceRange();
John McCallaa017372011-03-22 23:00:04 +00002273 emittedWarning = true;
Sebastian Redla2b5e312008-12-28 15:28:59 +00002274 }
Mike Stump11289f42009-09-09 15:08:12 +00002275
John McCallaa017372011-03-22 23:00:04 +00002276 // We're going to complain about a bunch of spurious specifiers;
2277 // only do this if we're declaring a tag, because otherwise we
2278 // should be getting diag::ext_no_declarators.
2279 if (emittedWarning || (TagD && TagD->isInvalidDecl()))
2280 return TagD;
2281
John McCall4d55f5a2011-03-26 02:09:52 +00002282 // Note that a linkage-specification sets a storage class, but
2283 // 'extern "C" struct foo;' is actually valid and not theoretically
2284 // useless.
John McCallaa017372011-03-22 23:00:04 +00002285 if (DeclSpec::SCS scs = DS.getStorageClassSpec())
John McCall4d55f5a2011-03-26 02:09:52 +00002286 if (!DS.isExternInLinkageSpec())
2287 Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier)
2288 << DeclSpec::getSpecifierName(scs);
2289
John McCallaa017372011-03-22 23:00:04 +00002290 if (DS.isThreadSpecified())
2291 Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread";
2292 if (DS.getTypeQualifiers()) {
2293 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2294 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const";
2295 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2296 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile";
2297 // Restrict is covered above.
2298 }
2299 if (DS.isInlineSpecified())
2300 Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline";
2301 if (DS.isVirtualSpecified())
2302 Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual";
2303 if (DS.isExplicitSpecified())
2304 Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit";
2305
2306 // FIXME: Warn on useless attributes
2307
John McCall48871652010-08-21 09:40:31 +00002308 return TagD;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002309}
2310
Fariborz Jahanian1db5c942010-09-28 20:42:35 +00002311/// ActOnVlaStmt - This rouine if finds a vla expression in a decl spec.
2312/// builds a statement for it and returns it so it is evaluated.
2313StmtResult Sema::ActOnVlaStmt(const DeclSpec &DS) {
2314 StmtResult R;
2315 if (DS.getTypeSpecType() == DeclSpec::TST_typeofExpr) {
2316 Expr *Exp = DS.getRepAsExpr();
2317 QualType Ty = Exp->getType();
2318 if (Ty->isPointerType()) {
2319 do
2320 Ty = Ty->getAs<PointerType>()->getPointeeType();
2321 while (Ty->isPointerType());
2322 }
2323 if (Ty->isVariableArrayType()) {
2324 R = ActOnExprStmt(MakeFullExpr(Exp));
2325 }
2326 }
2327 return R;
2328}
2329
John McCallea305ed2009-12-18 10:40:03 +00002330/// We are trying to inject an anonymous member into the given scope;
John McCall1f82f242009-11-18 22:49:29 +00002331/// check if there's an existing declaration that can't be overloaded.
2332///
2333/// \return true if this is a forbidden redeclaration
John McCallea305ed2009-12-18 10:40:03 +00002334static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
2335 Scope *S,
Fariborz Jahanian53967e22010-01-22 18:30:17 +00002336 DeclContext *Owner,
John McCallea305ed2009-12-18 10:40:03 +00002337 DeclarationName Name,
2338 SourceLocation NameLoc,
2339 unsigned diagnostic) {
2340 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
2341 Sema::ForRedeclaration);
2342 if (!SemaRef.LookupName(R, S)) return false;
John McCall1f82f242009-11-18 22:49:29 +00002343
John McCallea305ed2009-12-18 10:40:03 +00002344 if (R.getAsSingle<TagDecl>())
John McCall1f82f242009-11-18 22:49:29 +00002345 return false;
2346
2347 // Pick a representative declaration.
John McCallea305ed2009-12-18 10:40:03 +00002348 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidise619e992010-09-23 14:26:01 +00002349 assert(PrevDecl && "Expected a non-null Decl");
2350
2351 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
2352 return false;
John McCall1f82f242009-11-18 22:49:29 +00002353
John McCallea305ed2009-12-18 10:40:03 +00002354 SemaRef.Diag(NameLoc, diagnostic) << Name;
2355 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall1f82f242009-11-18 22:49:29 +00002356
2357 return true;
2358}
2359
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002360/// InjectAnonymousStructOrUnionMembers - Inject the members of the
2361/// anonymous struct or union AnonRecord into the owning context Owner
2362/// and scope S. This routine will be invoked just after we realize
2363/// that an unnamed union or struct is actually an anonymous union or
2364/// struct, e.g.,
2365///
2366/// @code
2367/// union {
2368/// int i;
2369/// float f;
2370/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
2371/// // f into the surrounding scope.x
2372/// @endcode
2373///
2374/// This routine is recursive, injecting the names of nested anonymous
2375/// structs/unions into the owning context and scope as well.
John McCallb54367d2010-05-21 20:45:30 +00002376static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
2377 DeclContext *Owner,
2378 RecordDecl *AnonRecord,
Francois Pichet783dd6e2010-11-21 06:08:52 +00002379 AccessSpecifier AS,
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002380 llvm::SmallVector<NamedDecl*, 2> &Chaining,
2381 bool MSAnonStruct) {
John McCall1f82f242009-11-18 22:49:29 +00002382 unsigned diagKind
2383 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
2384 : diag::err_anonymous_struct_member_redecl;
2385
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002386 bool Invalid = false;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002387
2388 // Look every FieldDecl and IndirectFieldDecl with a name.
2389 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
2390 DEnd = AnonRecord->decls_end();
2391 D != DEnd; ++D) {
2392 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
2393 cast<NamedDecl>(*D)->getDeclName()) {
2394 ValueDecl *VD = cast<ValueDecl>(*D);
2395 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
2396 VD->getLocation(), diagKind)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002397 // C++ [class.union]p2:
2398 // The names of the members of an anonymous union shall be
2399 // distinct from the names of any other entity in the
2400 // scope in which the anonymous union is declared.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002401 Invalid = true;
2402 } else {
2403 // C++ [class.union]p2:
2404 // For the purpose of name lookup, after the anonymous union
2405 // definition, the members of the anonymous union are
2406 // considered to have been defined in the scope in which the
2407 // anonymous union is declared.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002408 unsigned OldChainingSize = Chaining.size();
2409 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
2410 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
2411 PE = IF->chain_end(); PI != PE; ++PI)
2412 Chaining.push_back(*PI);
2413 else
2414 Chaining.push_back(VD);
2415
Francois Pichet783dd6e2010-11-21 06:08:52 +00002416 assert(Chaining.size() >= 2);
2417 NamedDecl **NamedChain =
2418 new (SemaRef.Context)NamedDecl*[Chaining.size()];
2419 for (unsigned i = 0; i < Chaining.size(); i++)
2420 NamedChain[i] = Chaining[i];
2421
2422 IndirectFieldDecl* IndirectField =
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002423 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
2424 VD->getIdentifier(), VD->getType(),
Francois Pichet783dd6e2010-11-21 06:08:52 +00002425 NamedChain, Chaining.size());
2426
2427 IndirectField->setAccess(AS);
2428 IndirectField->setImplicit();
2429 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallb54367d2010-05-21 20:45:30 +00002430
2431 // That includes picking up the appropriate access specifier.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002432 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002433
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002434 Chaining.resize(OldChainingSize);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002435 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002436 }
2437 }
2438
2439 return Invalid;
2440}
2441
Douglas Gregorc4df4072010-04-19 22:54:31 +00002442/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
2443/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCall8e7d6562010-08-26 03:08:43 +00002444/// illegal input values are mapped to SC_None.
2445static StorageClass
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00002446StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
Douglas Gregorc4df4072010-04-19 22:54:31 +00002447 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00002448 case DeclSpec::SCS_unspecified: return SC_None;
2449 case DeclSpec::SCS_extern: return SC_Extern;
2450 case DeclSpec::SCS_static: return SC_Static;
2451 case DeclSpec::SCS_auto: return SC_Auto;
2452 case DeclSpec::SCS_register: return SC_Register;
2453 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002454 // Illegal SCSs map to None: error reporting is up to the caller.
2455 case DeclSpec::SCS_mutable: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00002456 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002457 }
2458 llvm_unreachable("unknown storage class specifier");
2459}
2460
2461/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
John McCall8e7d6562010-08-26 03:08:43 +00002462/// a StorageClass. Any error reporting is up to the caller:
2463/// illegal input values are mapped to SC_None.
2464static StorageClass
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00002465StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
Douglas Gregorc4df4072010-04-19 22:54:31 +00002466 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00002467 case DeclSpec::SCS_unspecified: return SC_None;
2468 case DeclSpec::SCS_extern: return SC_Extern;
2469 case DeclSpec::SCS_static: return SC_Static;
2470 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002471 // Illegal SCSs map to None: error reporting is up to the caller.
2472 case DeclSpec::SCS_auto: // Fall through.
2473 case DeclSpec::SCS_mutable: // Fall through.
2474 case DeclSpec::SCS_register: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00002475 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002476 }
2477 llvm_unreachable("unknown storage class specifier");
2478}
2479
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002480/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002481/// anonymous structure or union. Anonymous unions are a C++ feature
2482/// (C++ [class.union]) and a GNU C extension; anonymous structures
Mike Stump11289f42009-09-09 15:08:12 +00002483/// are a GNU C and GNU C++ extension.
John McCall48871652010-08-21 09:40:31 +00002484Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2485 AccessSpecifier AS,
2486 RecordDecl *Record) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002487 DeclContext *Owner = Record->getDeclContext();
2488
2489 // Diagnose whether this anonymous struct/union is an extension.
2490 if (Record->isUnion() && !getLangOptions().CPlusPlus)
2491 Diag(Record->getLocation(), diag::ext_anonymous_union);
2492 else if (!Record->isUnion())
2493 Diag(Record->getLocation(), diag::ext_anonymous_struct);
Mike Stump11289f42009-09-09 15:08:12 +00002494
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002495 // C and C++ require different kinds of checks for anonymous
2496 // structs/unions.
2497 bool Invalid = false;
2498 if (getLangOptions().CPlusPlus) {
2499 const char* PrevSpec = 0;
John McCall49bfce42009-08-03 20:12:06 +00002500 unsigned DiagID;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002501 // C++ [class.union]p3:
2502 // Anonymous unions declared in a named namespace or in the
2503 // global namespace shall be declared static.
2504 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
2505 (isa<TranslationUnitDecl>(Owner) ||
Mike Stump11289f42009-09-09 15:08:12 +00002506 (isa<NamespaceDecl>(Owner) &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002507 cast<NamespaceDecl>(Owner)->getDeclName()))) {
2508 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
2509 Invalid = true;
2510
2511 // Recover by adding 'static'.
John McCall49bfce42009-08-03 20:12:06 +00002512 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(),
Peter Collingbournede32b202011-02-11 19:59:54 +00002513 PrevSpec, DiagID, getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +00002514 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002515 // C++ [class.union]p3:
2516 // A storage class is not allowed in a declaration of an
2517 // anonymous union in a class scope.
2518 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
2519 isa<RecordDecl>(Owner)) {
Mike Stump11289f42009-09-09 15:08:12 +00002520 Diag(DS.getStorageClassSpecLoc(),
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002521 diag::err_anonymous_union_with_storage_spec);
2522 Invalid = true;
2523
2524 // Recover by removing the storage specifier.
2525 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
Peter Collingbournede32b202011-02-11 19:59:54 +00002526 PrevSpec, DiagID, getLangOptions());
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002527 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00002528
Douglas Gregor0f8bc972011-05-09 23:05:33 +00002529 // Ignore const/volatile/restrict qualifiers.
2530 if (DS.getTypeQualifiers()) {
2531 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2532 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
2533 << Record->isUnion() << 0
2534 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
2535 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2536 Diag(DS.getVolatileSpecLoc(), diag::ext_anonymous_struct_union_qualified)
2537 << Record->isUnion() << 1
2538 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
2539 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
2540 Diag(DS.getRestrictSpecLoc(), diag::ext_anonymous_struct_union_qualified)
2541 << Record->isUnion() << 2
2542 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
2543
2544 DS.ClearTypeQualifiers();
2545 }
2546
Mike Stump11289f42009-09-09 15:08:12 +00002547 // C++ [class.union]p2:
Douglas Gregorf4d33272009-01-07 19:46:03 +00002548 // The member-specification of an anonymous union shall only
2549 // define non-static data members. [Note: nested types and
2550 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002551 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
2552 MemEnd = Record->decls_end();
Douglas Gregorf4d33272009-01-07 19:46:03 +00002553 Mem != MemEnd; ++Mem) {
2554 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
2555 // C++ [class.union]p3:
2556 // An anonymous union shall not have private or protected
2557 // members (clause 11).
John McCallb54367d2010-05-21 20:45:30 +00002558 assert(FD->getAccess() != AS_none);
2559 if (FD->getAccess() != AS_public) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00002560 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
2561 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
2562 Invalid = true;
2563 }
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00002564
Alexis Hunt97ab5542011-05-16 22:41:40 +00002565 // C++ [class.union]p1
2566 // An object of a class with a non-trivial constructor, a non-trivial
2567 // copy constructor, a non-trivial destructor, or a non-trivial copy
2568 // assignment operator cannot be a member of a union, nor can an
2569 // array of such objects.
2570 if (!getLangOptions().CPlusPlus0x && CheckNontrivialField(FD))
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00002571 Invalid = true;
Douglas Gregorf4d33272009-01-07 19:46:03 +00002572 } else if ((*Mem)->isImplicit()) {
2573 // Any implicit members are fine.
Douglas Gregor8761da52009-02-03 00:34:39 +00002574 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
2575 // This is a type that showed up in an
2576 // elaborated-type-specifier inside the anonymous struct or
2577 // union, but which actually declares a type outside of the
2578 // anonymous struct or union. It's okay.
Douglas Gregorf4d33272009-01-07 19:46:03 +00002579 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
2580 if (!MemRecord->isAnonymousStructOrUnion() &&
2581 MemRecord->getDeclName()) {
Francois Pichet4ad4b582010-09-08 11:32:25 +00002582 // Visual C++ allows type definition in anonymous struct or union.
2583 if (getLangOptions().Microsoft)
2584 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
2585 << (int)Record->isUnion();
2586 else {
2587 // This is a nested type declaration.
2588 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
2589 << (int)Record->isUnion();
2590 Invalid = true;
2591 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00002592 }
Abramo Bagnarad7340582010-06-05 05:09:32 +00002593 } else if (isa<AccessSpecDecl>(*Mem)) {
2594 // Any access specifier is fine.
Douglas Gregorf4d33272009-01-07 19:46:03 +00002595 } else {
2596 // We have something that isn't a non-static data
2597 // member. Complain about it.
2598 unsigned DK = diag::err_anonymous_record_bad_member;
2599 if (isa<TypeDecl>(*Mem))
2600 DK = diag::err_anonymous_record_with_type;
2601 else if (isa<FunctionDecl>(*Mem))
2602 DK = diag::err_anonymous_record_with_function;
2603 else if (isa<VarDecl>(*Mem))
2604 DK = diag::err_anonymous_record_with_static;
Francois Pichet4ad4b582010-09-08 11:32:25 +00002605
2606 // Visual C++ allows type definition in anonymous struct or union.
2607 if (getLangOptions().Microsoft &&
2608 DK == diag::err_anonymous_record_with_type)
2609 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregorf4d33272009-01-07 19:46:03 +00002610 << (int)Record->isUnion();
Francois Pichet4ad4b582010-09-08 11:32:25 +00002611 else {
2612 Diag((*Mem)->getLocation(), DK)
2613 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00002614 Invalid = true;
Francois Pichet4ad4b582010-09-08 11:32:25 +00002615 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00002616 }
2617 }
Mike Stump11289f42009-09-09 15:08:12 +00002618 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002619
2620 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002621 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
2622 << (int)getLangOptions().CPlusPlus;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002623 Invalid = true;
2624 }
2625
John McCallfa2d6922009-10-22 23:31:08 +00002626 // Mock up a declarator.
Argyrios Kyrtzidis7baa0af2011-06-28 03:01:18 +00002627 Declarator Dc(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00002628 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCallbcd03502009-12-07 02:54:59 +00002629 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCallfa2d6922009-10-22 23:31:08 +00002630
Mike Stump11289f42009-09-09 15:08:12 +00002631 // Create a declaration for this anonymous struct/union.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002632 NamedDecl *Anon = 0;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002633 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00002634 Anon = FieldDecl::Create(Context, OwningClass,
2635 DS.getSourceRange().getBegin(),
2636 Record->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002637 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00002638 Context.getTypeDeclType(Record),
John McCallbcd03502009-12-07 02:54:59 +00002639 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00002640 /*BitWidth=*/0, /*Mutable=*/false,
2641 /*HasInit=*/false);
John McCallb54367d2010-05-21 20:45:30 +00002642 Anon->setAccess(AS);
Douglas Gregor9d5938a2010-09-28 20:38:10 +00002643 if (getLangOptions().CPlusPlus)
Douglas Gregorf4d33272009-01-07 19:46:03 +00002644 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002645 } else {
Douglas Gregorc4df4072010-04-19 22:54:31 +00002646 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
2647 assert(SCSpec != DeclSpec::SCS_typedef &&
2648 "Parser allowed 'typedef' as storage class VarDecl.");
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00002649 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregorc4df4072010-04-19 22:54:31 +00002650 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002651 // mutable can only appear on non-static class members, so it's always
2652 // an error here
2653 Diag(Record->getLocation(), diag::err_mutable_nonmember);
2654 Invalid = true;
John McCall8e7d6562010-08-26 03:08:43 +00002655 SC = SC_None;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002656 }
Douglas Gregorc4df4072010-04-19 22:54:31 +00002657 SCSpec = DS.getStorageClassSpecAsWritten();
2658 VarDecl::StorageClass SCAsWritten
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00002659 = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002660
Abramo Bagnaradff19302011-03-08 08:55:46 +00002661 Anon = VarDecl::Create(Context, Owner,
2662 DS.getSourceRange().getBegin(),
2663 Record->getLocation(), /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00002664 Context.getTypeDeclType(Record),
Douglas Gregorc4df4072010-04-19 22:54:31 +00002665 TInfo, SC, SCAsWritten);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002666 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00002667 Anon->setImplicit();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002668
2669 // Add the anonymous struct/union object to the current
2670 // context. We'll be referencing this object when we refer to one of
2671 // its members.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002672 Owner->addDecl(Anon);
Douglas Gregor456ad1a2010-05-03 15:18:25 +00002673
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002674 // Inject the members of the anonymous struct/union into the owning
2675 // context and into the identifier resolver chain for name lookup
2676 // purposes.
Francois Pichet783dd6e2010-11-21 06:08:52 +00002677 llvm::SmallVector<NamedDecl*, 2> Chain;
2678 Chain.push_back(Anon);
2679
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002680 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
2681 Chain, false))
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002682 Invalid = true;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002683
2684 // Mark this as an anonymous struct/union type. Note that we do not
2685 // do this until after we have already checked and injected the
2686 // members of this anonymous struct/union type, because otherwise
2687 // the members could be injected twice: once by DeclContext when it
2688 // builds its lookup table, and once by
Mike Stump11289f42009-09-09 15:08:12 +00002689 // InjectAnonymousStructOrUnionMembers.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002690 Record->setAnonymousStructOrUnion(true);
2691
2692 if (Invalid)
2693 Anon->setInvalidDecl();
2694
John McCall48871652010-08-21 09:40:31 +00002695 return Anon;
Chris Lattnerb6738ec2007-01-28 00:38:24 +00002696}
2697
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002698/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
2699/// Microsoft C anonymous structure.
2700/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
2701/// Example:
2702///
2703/// struct A { int a; };
2704/// struct B { struct A; int b; };
2705///
2706/// void foo() {
2707/// B var;
2708/// var.a = 3;
2709/// }
2710///
2711Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2712 RecordDecl *Record) {
2713
2714 // If there is no Record, get the record via the typedef.
2715 if (!Record)
2716 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
2717
2718 // Mock up a declarator.
2719 Declarator Dc(DS, Declarator::TypeNameContext);
2720 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
2721 assert(TInfo && "couldn't build declarator info for anonymous struct");
2722
2723 // Create a declaration for this anonymous struct.
2724 NamedDecl* Anon = FieldDecl::Create(Context,
2725 cast<RecordDecl>(CurContext),
2726 DS.getSourceRange().getBegin(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002727 DS.getSourceRange().getBegin(),
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002728 /*IdentifierInfo=*/0,
2729 Context.getTypeDeclType(Record),
2730 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00002731 /*BitWidth=*/0, /*Mutable=*/false,
2732 /*HasInit=*/false);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002733 Anon->setImplicit();
2734
2735 // Add the anonymous struct object to the current context.
2736 CurContext->addDecl(Anon);
2737
2738 // Inject the members of the anonymous struct into the current
2739 // context and into the identifier resolver chain for name lookup
2740 // purposes.
2741 llvm::SmallVector<NamedDecl*, 2> Chain;
2742 Chain.push_back(Anon);
2743
2744 if (InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
2745 Record->getDefinition(),
2746 AS_none, Chain, true))
2747 Anon->setInvalidDecl();
2748
2749 return Anon;
2750}
Steve Naroff2fea1392007-09-02 02:04:30 +00002751
Douglas Gregor92751d42008-11-17 22:58:34 +00002752/// GetNameForDeclarator - Determine the full declaration name for the
2753/// given Declarator.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002754DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregora121b752009-11-03 16:56:39 +00002755 return GetNameFromUnqualifiedId(D.getName());
2756}
2757
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002758/// \brief Retrieves the declaration name from a parsed unqualified-id.
2759DeclarationNameInfo
2760Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
2761 DeclarationNameInfo NameInfo;
2762 NameInfo.setLoc(Name.StartLocation);
2763
Douglas Gregor7861a802009-11-03 01:35:08 +00002764 switch (Name.getKind()) {
Alexis Hunt34458502009-11-28 04:44:28 +00002765
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00002766 case UnqualifiedId::IK_ImplicitSelfParam:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002767 case UnqualifiedId::IK_Identifier:
2768 NameInfo.setName(Name.Identifier);
2769 NameInfo.setLoc(Name.StartLocation);
2770 return NameInfo;
Alexis Hunt34458502009-11-28 04:44:28 +00002771
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002772 case UnqualifiedId::IK_OperatorFunctionId:
2773 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
2774 Name.OperatorFunctionId.Operator));
2775 NameInfo.setLoc(Name.StartLocation);
2776 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
2777 = Name.OperatorFunctionId.SymbolLocations[0];
2778 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
2779 = Name.EndLocation.getRawEncoding();
2780 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002781
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002782 case UnqualifiedId::IK_LiteralOperatorId:
2783 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
2784 Name.Identifier));
2785 NameInfo.setLoc(Name.StartLocation);
2786 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
2787 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002788
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002789 case UnqualifiedId::IK_ConversionFunctionId: {
2790 TypeSourceInfo *TInfo;
2791 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
2792 if (Ty.isNull())
2793 return DeclarationNameInfo();
2794 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
2795 Context.getCanonicalType(Ty)));
2796 NameInfo.setLoc(Name.StartLocation);
2797 NameInfo.setNamedTypeInfo(TInfo);
2798 return NameInfo;
Douglas Gregord90fd522009-09-25 21:45:23 +00002799 }
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002800
2801 case UnqualifiedId::IK_ConstructorName: {
2802 TypeSourceInfo *TInfo;
2803 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
2804 if (Ty.isNull())
2805 return DeclarationNameInfo();
2806 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
2807 Context.getCanonicalType(Ty)));
2808 NameInfo.setLoc(Name.StartLocation);
2809 NameInfo.setNamedTypeInfo(TInfo);
2810 return NameInfo;
2811 }
2812
2813 case UnqualifiedId::IK_ConstructorTemplateId: {
2814 // In well-formed code, we can only have a constructor
2815 // template-id that refers to the current context, so go there
2816 // to find the actual type being constructed.
2817 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
2818 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
2819 return DeclarationNameInfo();
2820
2821 // Determine the type of the class being constructed.
2822 QualType CurClassType = Context.getTypeDeclType(CurClass);
2823
2824 // FIXME: Check two things: that the template-id names the same type as
2825 // CurClassType, and that the template-id does not occur when the name
2826 // was qualified.
2827
2828 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
2829 Context.getCanonicalType(CurClassType)));
2830 NameInfo.setLoc(Name.StartLocation);
2831 // FIXME: should we retrieve TypeSourceInfo?
2832 NameInfo.setNamedTypeInfo(0);
2833 return NameInfo;
2834 }
2835
2836 case UnqualifiedId::IK_DestructorName: {
2837 TypeSourceInfo *TInfo;
2838 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
2839 if (Ty.isNull())
2840 return DeclarationNameInfo();
2841 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
2842 Context.getCanonicalType(Ty)));
2843 NameInfo.setLoc(Name.StartLocation);
2844 NameInfo.setNamedTypeInfo(TInfo);
2845 return NameInfo;
2846 }
2847
2848 case UnqualifiedId::IK_TemplateId: {
John McCall3e56fd42010-08-23 07:28:44 +00002849 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002850 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
2851 return Context.getNameForTemplate(TName, TNameLoc);
2852 }
2853
2854 } // switch (Name.getKind())
2855
Douglas Gregor92751d42008-11-17 22:58:34 +00002856 assert(false && "Unknown name kind");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002857 return DeclarationNameInfo();
Douglas Gregor92751d42008-11-17 22:58:34 +00002858}
2859
Douglas Gregor8af63e42009-02-06 17:46:57 +00002860/// isNearlyMatchingFunction - Determine whether the C++ functions
2861/// Declaration and Definition are "nearly" matching. This heuristic
2862/// is used to improve diagnostics in the case where an out-of-line
2863/// function definition doesn't match any declaration within
2864/// the class or namespace.
2865static bool isNearlyMatchingFunction(ASTContext &Context,
2866 FunctionDecl *Declaration,
2867 FunctionDecl *Definition) {
Douglas Gregorad590502008-12-15 23:53:10 +00002868 if (Declaration->param_size() != Definition->param_size())
2869 return false;
2870 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
2871 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
2872 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
2873
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002874 if (!Context.hasSameUnqualifiedType(DeclParamTy.getNonReferenceType(),
2875 DefParamTy.getNonReferenceType()))
Douglas Gregorad590502008-12-15 23:53:10 +00002876 return false;
2877 }
2878
2879 return true;
2880}
2881
John McCall99b2fe52010-04-29 23:50:39 +00002882/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
2883/// declarator needs to be rebuilt in the current instantiation.
2884/// Any bits of declarator which appear before the name are valid for
2885/// consideration here. That's specifically the type in the decl spec
2886/// and the base type in any member-pointer chunks.
2887static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
2888 DeclarationName Name) {
2889 // The types we specifically need to rebuild are:
2890 // - typenames, typeofs, and decltypes
2891 // - types which will become injected class names
2892 // Of course, we also need to rebuild any type referencing such a
2893 // type. It's safest to just say "dependent", but we call out a
2894 // few cases here.
2895
2896 DeclSpec &DS = D.getMutableDeclSpec();
2897 switch (DS.getTypeSpecType()) {
2898 case DeclSpec::TST_typename:
2899 case DeclSpec::TST_typeofType:
Alexis Hunt4a257072011-05-19 05:37:45 +00002900 case DeclSpec::TST_decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002901 case DeclSpec::TST_underlyingType: {
John McCall99b2fe52010-04-29 23:50:39 +00002902 // Grab the type from the parser.
2903 TypeSourceInfo *TSI = 0;
John McCallba7bf592010-08-24 05:47:05 +00002904 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall99b2fe52010-04-29 23:50:39 +00002905 if (T.isNull() || !T->isDependentType()) break;
2906
2907 // Make sure there's a type source info. This isn't really much
2908 // of a waste; most dependent types should have type source info
2909 // attached already.
2910 if (!TSI)
2911 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
2912
2913 // Rebuild the type in the current instantiation.
2914 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
2915 if (!TSI) return true;
2916
2917 // Store the new type back in the decl spec.
John McCallba7bf592010-08-24 05:47:05 +00002918 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
2919 DS.UpdateTypeRep(LocType);
2920 break;
2921 }
2922
2923 case DeclSpec::TST_typeofExpr: {
2924 Expr *E = DS.getRepAsExpr();
John McCalldadc5752010-08-24 06:29:42 +00002925 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallba7bf592010-08-24 05:47:05 +00002926 if (Result.isInvalid()) return true;
2927 DS.UpdateExprRep(Result.get());
John McCall99b2fe52010-04-29 23:50:39 +00002928 break;
2929 }
2930
2931 default:
2932 // Nothing to do for these decl specs.
2933 break;
2934 }
2935
2936 // It doesn't matter what order we do this in.
2937 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
2938 DeclaratorChunk &Chunk = D.getTypeObject(I);
2939
2940 // The only type information in the declarator which can come
2941 // before the declaration name is the base type of a member
2942 // pointer.
2943 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
2944 continue;
2945
2946 // Rebuild the scope specifier in-place.
2947 CXXScopeSpec &SS = Chunk.Mem.Scope();
2948 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
2949 return true;
2950 }
2951
2952 return false;
2953}
2954
Anders Carlsson1052fd72011-07-04 16:28:17 +00002955Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002956 return HandleDeclarator(S, D, MultiTemplateParamsArg(*this),
Anders Carlsson1052fd72011-07-04 16:28:17 +00002957 /*IsFunctionDefinition=*/false);
John McCallde6836a2010-08-24 07:21:54 +00002958}
2959
Richard Smithdda56e42011-04-15 14:24:37 +00002960/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
2961/// If T is the name of a class, then each of the following shall have a
2962/// name different from T:
2963/// - every static data member of class T;
2964/// - every member function of class T
2965/// - every member of class T that is itself a type;
2966/// \returns true if the declaration name violates these rules.
2967bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
2968 DeclarationNameInfo NameInfo) {
2969 DeclarationName Name = NameInfo.getName();
2970
2971 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
2972 if (Record->getIdentifier() && Record->getDeclName() == Name) {
2973 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
2974 return true;
2975 }
2976
2977 return false;
2978}
2979
John McCall48871652010-08-21 09:40:31 +00002980Decl *Sema::HandleDeclarator(Scope *S, Declarator &D,
2981 MultiTemplateParamsArg TemplateParamLists,
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002982 bool IsFunctionDefinition) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002983 // TODO: consider using NameInfo for diagnostic.
2984 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2985 DeclarationName Name = NameInfo.getName();
Douglas Gregor92751d42008-11-17 22:58:34 +00002986
Chris Lattner02c04392007-07-25 00:24:17 +00002987 // All of these full declarators require an identifier. If it doesn't have
2988 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor92751d42008-11-17 22:58:34 +00002989 if (!Name) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002990 if (!D.isInvalidType()) // Reject this if we think it is valid.
Chris Lattner8c5dd732008-11-11 06:13:16 +00002991 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002992 diag::err_declarator_need_ident)
2993 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00002994 return 0;
Douglas Gregorc4356532010-12-16 00:46:58 +00002995 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
2996 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002997
Chris Lattner1a76a3c2007-08-26 06:24:45 +00002998 // The scope passed in may not be a decl scope. Zip up the scope tree until
2999 // we find one that is.
Douglas Gregor91f84212008-12-11 16:49:14 +00003000 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregorded2d7b2009-02-04 19:02:06 +00003001 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner1a76a3c2007-08-26 06:24:45 +00003002 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003003
John McCall99b2fe52010-04-29 23:50:39 +00003004 DeclContext *DC = CurContext;
3005 if (D.getCXXScopeSpec().isInvalid())
3006 D.setInvalidType();
3007 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6c110f32010-12-16 01:14:37 +00003008 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
3009 UPPC_DeclarationQualifier))
3010 return 0;
3011
John McCall99b2fe52010-04-29 23:50:39 +00003012 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
3013 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
3014 if (!DC) {
3015 // If we could not compute the declaration context, it's because the
3016 // declaration context is dependent but does not refer to a class,
3017 // class template, or class template partial specialization. Complain
3018 // and return early, to avoid the coming semantic disaster.
3019 Diag(D.getIdentifierLoc(),
3020 diag::err_template_qualified_declarator_no_match)
3021 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
3022 << D.getCXXScopeSpec().getRange();
John McCall48871652010-08-21 09:40:31 +00003023 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00003024 }
John McCall99b2fe52010-04-29 23:50:39 +00003025 bool IsDependentContext = DC->isDependentContext();
John McCall4d6d6132009-12-19 09:35:56 +00003026
John McCall99b2fe52010-04-29 23:50:39 +00003027 if (!IsDependentContext &&
John McCall0b66eb32010-05-01 00:40:08 +00003028 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCall48871652010-08-21 09:40:31 +00003029 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00003030
Douglas Gregora007d362010-10-13 22:19:53 +00003031 if (isa<CXXRecordDecl>(DC)) {
3032 if (!cast<CXXRecordDecl>(DC)->hasDefinition()) {
3033 Diag(D.getIdentifierLoc(),
3034 diag::err_member_def_undefined_record)
3035 << Name << DC << D.getCXXScopeSpec().getRange();
3036 D.setInvalidType();
3037 } else if (isa<CXXRecordDecl>(CurContext) &&
3038 !D.getDeclSpec().isFriendSpecified()) {
3039 // The user provided a superfluous scope specifier inside a class
3040 // definition:
3041 //
3042 // class X {
3043 // void X::f();
3044 // };
3045 if (CurContext->Equals(DC))
3046 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
3047 << Name << FixItHint::CreateRemoval(D.getCXXScopeSpec().getRange());
3048 else
3049 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3050 << Name << D.getCXXScopeSpec().getRange();
3051
3052 // Pretend that this qualifier was not here.
3053 D.getCXXScopeSpec().clear();
3054 }
John McCall99b2fe52010-04-29 23:50:39 +00003055 }
3056
3057 // Check whether we need to rebuild the type of the given
3058 // declaration in the current instantiation.
3059 if (EnteringContext && IsDependentContext &&
3060 TemplateParamLists.size() != 0) {
3061 ContextRAII SavedContext(*this, DC);
3062 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
3063 D.setInvalidType();
Douglas Gregor15acfb92009-08-06 16:20:37 +00003064 }
3065 }
Richard Smithdda56e42011-04-15 14:24:37 +00003066
3067 if (DiagnoseClassNameShadow(DC, NameInfo))
3068 // If this is a typedef, we'll end up spewing multiple diagnostics.
3069 // Just return early; it's safer.
3070 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3071 return 0;
Douglas Gregor36c22a22010-10-15 13:21:21 +00003072
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003073 NamedDecl *New;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00003074
John McCall8cb7bdf2010-06-04 23:28:52 +00003075 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3076 QualType R = TInfo->getType();
Douglas Gregoreddf4332009-02-24 20:03:32 +00003077
Douglas Gregor506bd562010-12-13 22:49:22 +00003078 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
3079 UPPC_DeclarationType))
3080 D.setInvalidType();
3081
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003082 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00003083 ForRedeclaration);
3084
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003085 // See if this is a redefinition of a variable in the same scope.
John McCall99b2fe52010-04-29 23:50:39 +00003086 if (!D.getCXXScopeSpec().isSet()) {
John McCall1f82f242009-11-18 22:49:29 +00003087 bool IsLinkageLookup = false;
Douglas Gregoreddf4332009-02-24 20:03:32 +00003088
3089 // If the declaration we're planning to build will be a function
3090 // or object with linkage, then look for another declaration with
3091 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
3092 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3093 /* Do nothing*/;
3094 else if (R->isFunctionType()) {
Douglas Gregor20749772009-07-07 17:00:05 +00003095 if (CurContext->isFunctionOrMethod() ||
3096 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall1f82f242009-11-18 22:49:29 +00003097 IsLinkageLookup = true;
Douglas Gregoreddf4332009-02-24 20:03:32 +00003098 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
John McCall1f82f242009-11-18 22:49:29 +00003099 IsLinkageLookup = true;
Sebastian Redl50c68252010-08-31 00:36:30 +00003100 else if (CurContext->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor20749772009-07-07 17:00:05 +00003101 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall1f82f242009-11-18 22:49:29 +00003102 IsLinkageLookup = true;
3103
3104 if (IsLinkageLookup)
3105 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregoreddf4332009-02-24 20:03:32 +00003106
John McCall1f82f242009-11-18 22:49:29 +00003107 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003108 } else { // Something like "int foo::x;"
John McCall1f82f242009-11-18 22:49:29 +00003109 LookupQualifiedName(Previous, DC);
3110
3111 // Don't consider using declarations as previous declarations for
3112 // out-of-line members.
3113 RemoveUsingDecls(Previous);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003114
3115 // C++ 7.3.1.2p2:
3116 // Members (including explicit specializations of templates) of a named
3117 // namespace can also be defined outside that namespace by explicit
3118 // qualification of the name being defined, provided that the entity being
3119 // defined was already declared in the namespace and the definition appears
3120 // after the point of declaration in a namespace that encloses the
3121 // declarations namespace.
3122 //
Douglas Gregorad590502008-12-15 23:53:10 +00003123 // Note that we only check the context at this point. We don't yet
3124 // have enough information to make sure that PrevDecl is actually
3125 // the declaration we want to match. For example, given:
3126 //
Douglas Gregor4287b372008-12-12 08:25:50 +00003127 // class X {
3128 // void f();
Douglas Gregorad590502008-12-15 23:53:10 +00003129 // void f(float);
Douglas Gregor4287b372008-12-12 08:25:50 +00003130 // };
3131 //
Douglas Gregorad590502008-12-15 23:53:10 +00003132 // void X::f(int) { } // ill-formed
3133 //
3134 // In this case, PrevDecl will point to the overload set
3135 // containing the two f's declared in X, but neither of them
Mike Stump11289f42009-09-09 15:08:12 +00003136 // matches.
Douglas Gregor8af63e42009-02-06 17:46:57 +00003137
3138 // First check whether we named the global scope.
3139 if (isa<TranslationUnitDecl>(DC)) {
Mike Stump11289f42009-09-09 15:08:12 +00003140 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
Douglas Gregor8af63e42009-02-06 17:46:57 +00003141 << Name << D.getCXXScopeSpec().getRange();
Sebastian Redlafb8be72009-11-08 11:36:54 +00003142 } else {
3143 DeclContext *Cur = CurContext;
3144 while (isa<LinkageSpecDecl>(Cur))
3145 Cur = Cur->getParent();
3146 if (!Cur->Encloses(DC)) {
3147 // The qualifying scope doesn't enclose the original declaration.
3148 // Emit diagnostic based on current scope.
3149 SourceLocation L = D.getIdentifierLoc();
3150 SourceRange R = D.getCXXScopeSpec().getRange();
3151 if (isa<FunctionDecl>(Cur))
3152 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
3153 else
3154 Diag(L, diag::err_invalid_declarator_scope)
3155 << Name << cast<NamedDecl>(DC) << R;
3156 D.setInvalidType();
3157 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003158 }
3159 }
3160
John McCall1f82f242009-11-18 22:49:29 +00003161 if (Previous.isSingleResult() &&
3162 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00003163 // Maybe we will complain about the shadowed template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003164 if (!D.isInvalidType())
John McCall1f82f242009-11-18 22:49:29 +00003165 if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
3166 Previous.getFoundDecl()))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003167 D.setInvalidType();
Mike Stump11289f42009-09-09 15:08:12 +00003168
Douglas Gregor5101c242008-12-05 18:15:24 +00003169 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00003170 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00003171 }
3172
Douglas Gregor83a586e2008-04-13 21:07:44 +00003173 // In C++, the previous declaration we find might be a tag type
3174 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorfb034662009-01-28 17:15:10 +00003175 // tag type. Note that this does does not apply if we're declaring a
3176 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00003177 if (Previous.isSingleTagDecl() &&
Douglas Gregorfb034662009-01-28 17:15:10 +00003178 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall1f82f242009-11-18 22:49:29 +00003179 Previous.clear();
Douglas Gregor83a586e2008-04-13 21:07:44 +00003180
Douglas Gregor75a45ba2009-02-16 17:45:42 +00003181 bool Redeclaration = false;
Chris Lattner01a7c532007-01-25 23:09:03 +00003182 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003183 if (TemplateParamLists.size()) {
3184 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
John McCall48871652010-08-21 09:40:31 +00003185 return 0;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003186 }
Mike Stump11289f42009-09-09 15:08:12 +00003187
John McCallbcd03502009-12-07 02:54:59 +00003188 New = ActOnTypedefDeclarator(S, D, DC, R, TInfo, Previous, Redeclaration);
Douglas Gregoreddf4332009-02-24 20:03:32 +00003189 } else if (R->isFunctionType()) {
John McCallbcd03502009-12-07 02:54:59 +00003190 New = ActOnFunctionDeclarator(S, D, DC, R, TInfo, Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003191 move(TemplateParamLists),
Alexis Hunt5a7fa252011-05-12 06:15:49 +00003192 IsFunctionDefinition, Redeclaration);
Chris Lattner01a7c532007-01-25 23:09:03 +00003193 } else {
John McCallbcd03502009-12-07 02:54:59 +00003194 New = ActOnVariableDeclarator(S, D, DC, R, TInfo, Previous,
Douglas Gregorb09f3d82009-07-22 17:18:37 +00003195 move(TemplateParamLists),
3196 Redeclaration);
Chris Lattner01a7c532007-01-25 23:09:03 +00003197 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00003198
3199 if (New == 0)
John McCall48871652010-08-21 09:40:31 +00003200 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003201
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003202 // If this has an identifier and is not an invalid redeclaration or
3203 // function template specialization, add it to the scope stack.
Douglas Gregor536f0912010-07-24 00:10:38 +00003204 if (New->getDeclName() && !(Redeclaration && New->isInvalidDecl()))
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00003205 PushOnScopeChains(New, S);
Mike Stump11289f42009-09-09 15:08:12 +00003206
John McCall48871652010-08-21 09:40:31 +00003207 return New;
Chris Lattnere168f762006-11-10 05:29:30 +00003208}
3209
Eli Friedmana3b1d032009-02-21 00:44:51 +00003210/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3211/// types into constant array types in certain situations which would otherwise
3212/// be errors (for GCC compatibility).
3213static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3214 ASTContext &Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003215 bool &SizeIsNegative,
3216 llvm::APSInt &Oversized) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00003217 // This method tries to turn a variable array into a constant
3218 // array even when the size isn't an ICE. This is necessary
3219 // for compatibility with code that depends on gcc's buggy
3220 // constant expression folding, like struct {char x[(int)(char*)2];}
3221 SizeIsNegative = false;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003222 Oversized = 0;
3223
3224 if (T->isDependentType())
3225 return QualType();
3226
John McCall8ccfcb52009-09-24 19:53:00 +00003227 QualifierCollector Qs;
3228 const Type *Ty = Qs.strip(T);
3229
3230 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00003231 QualType Pointee = PTy->getPointeeType();
3232 QualType FixedType =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003233 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
3234 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003235 if (FixedType.isNull()) return FixedType;
Eli Friedman44c0f2a2009-02-21 00:58:02 +00003236 FixedType = Context.getPointerType(FixedType);
John McCall717d9b02010-12-10 11:01:00 +00003237 return Qs.apply(Context, FixedType);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003238 }
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003239 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
3240 QualType Inner = PTy->getInnerType();
3241 QualType FixedType =
3242 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
3243 Oversized);
3244 if (FixedType.isNull()) return FixedType;
3245 FixedType = Context.getParenType(FixedType);
3246 return Qs.apply(Context, FixedType);
3247 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00003248
3249 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanadf40d42009-02-26 03:58:54 +00003250 if (!VLATy)
3251 return QualType();
3252 // FIXME: We should probably handle this case
3253 if (VLATy->getElementType()->isVariablyModifiedType())
3254 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00003255
Eli Friedmana3b1d032009-02-21 00:44:51 +00003256 Expr::EvalResult EvalResult;
3257 if (!VLATy->getSizeExpr() ||
Eli Friedmanadf40d42009-02-26 03:58:54 +00003258 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
3259 !EvalResult.Val.isInt())
Eli Friedmana3b1d032009-02-21 00:44:51 +00003260 return QualType();
Eli Friedmanadf40d42009-02-26 03:58:54 +00003261
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003262 // Check whether the array size is negative.
Eli Friedmana3b1d032009-02-21 00:44:51 +00003263 llvm::APSInt &Res = EvalResult.Val.getInt();
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003264 if (Res.isSigned() && Res.isNegative()) {
3265 SizeIsNegative = true;
3266 return QualType();
Douglas Gregor04318252009-07-06 15:59:29 +00003267 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00003268
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003269 // Check whether the array is too large to be addressed.
3270 unsigned ActiveSizeBits
3271 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
3272 Res);
3273 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
3274 Oversized = Res;
3275 return QualType();
3276 }
3277
3278 return Context.getConstantArrayType(VLATy->getElementType(),
3279 Res, ArrayType::Normal, 0);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003280}
3281
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003282/// \brief Register the given locally-scoped external C declaration so
3283/// that it can be found later for redeclarations
Mike Stump11289f42009-09-09 15:08:12 +00003284void
John McCall1f82f242009-11-18 22:49:29 +00003285Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
3286 const LookupResult &Previous,
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003287 Scope *S) {
3288 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
3289 "Decl is not a locally-scoped decl!");
3290 // Note that we have a locally-scoped external with this name.
3291 LocallyScopedExternalDecls[ND->getDeclName()] = ND;
3292
John McCall1f82f242009-11-18 22:49:29 +00003293 if (!Previous.isSingleResult())
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003294 return;
3295
John McCall1f82f242009-11-18 22:49:29 +00003296 NamedDecl *PrevDecl = Previous.getFoundDecl();
3297
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003298 // If there was a previous declaration of this variable, it may be
3299 // in our identifier chain. Update the identifier chain with the new
3300 // declaration.
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003301 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003302 // The previous declaration was found on the identifer resolver
3303 // chain, so remove it from its scope.
Douglas Gregor825faf72011-06-29 21:22:02 +00003304
3305 if (S->isDeclScope(PrevDecl)) {
3306 // Special case for redeclarations in the SAME scope.
3307 // Because this declaration is going to be added to the identifier chain
3308 // later, we should temporarily take it OFF the chain.
3309 IdResolver.RemoveDecl(ND);
3310
3311 } else {
3312 // Find the scope for the original declaration.
3313 while (S && !S->isDeclScope(PrevDecl))
3314 S = S->getParent();
3315 }
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003316
3317 if (S)
John McCall48871652010-08-21 09:40:31 +00003318 S->RemoveDecl(PrevDecl);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003319 }
3320}
3321
Eli Friedman574c7452009-04-07 19:37:57 +00003322/// \brief Diagnose function specifiers on a declaration of an identifier that
3323/// does not identify a function.
3324void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
3325 // FIXME: We should probably indicate the identifier in question to avoid
3326 // confusion for constructs like "inline int a(), b;"
3327 if (D.getDeclSpec().isInlineSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00003328 Diag(D.getDeclSpec().getInlineSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00003329 diag::err_inline_non_function);
3330
3331 if (D.getDeclSpec().isVirtualSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00003332 Diag(D.getDeclSpec().getVirtualSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00003333 diag::err_virtual_non_function);
3334
3335 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00003336 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00003337 diag::err_explicit_non_function);
3338}
3339
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003340NamedDecl*
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003341Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
John McCallbcd03502009-12-07 02:54:59 +00003342 QualType R, TypeSourceInfo *TInfo,
John McCall1f82f242009-11-18 22:49:29 +00003343 LookupResult &Previous, bool &Redeclaration) {
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003344 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
3345 if (D.getCXXScopeSpec().isSet()) {
3346 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
3347 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003348 D.setInvalidType();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003349 // Pretend we didn't see the scope specifier.
Douglas Gregorb525ef82010-03-23 15:26:55 +00003350 DC = CurContext;
3351 Previous.clear();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003352 }
3353
Douglas Gregor0c880302009-03-11 23:00:04 +00003354 if (getLangOptions().CPlusPlus) {
3355 // Check that there are no default arguments (C++ only).
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003356 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00003357 }
3358
Eli Friedman574c7452009-04-07 19:37:57 +00003359 DiagnoseFunctionSpecifiers(D);
3360
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003361 if (D.getDeclSpec().isThreadSpecified())
3362 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
3363
Douglas Gregord8f446f2010-07-13 06:37:01 +00003364 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
3365 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
3366 << D.getName().getSourceRange();
3367 return 0;
3368 }
3369
John McCallbcd03502009-12-07 02:54:59 +00003370 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, TInfo);
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003371 if (!NewTD) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003372
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003373 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00003374 ProcessDeclAttributes(S, NewTD, D);
John McCall1f82f242009-11-18 22:49:29 +00003375
Richard Smith3f1b5d02011-05-05 21:57:07 +00003376 CheckTypedefForVariablyModifiedType(S, NewTD);
3377
Richard Smithdda56e42011-04-15 14:24:37 +00003378 return ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
3379}
3380
Richard Smith3f1b5d02011-05-05 21:57:07 +00003381void
3382Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner9fecd742009-04-19 05:21:20 +00003383 // C99 6.7.7p2: If a typedef name specifies a variably modified type
3384 // then it shall have block scope.
Eli Friedman88f4ed92010-08-10 03:13:15 +00003385 // Note that variably modified types must be fixed before merging the decl so
3386 // that redeclarations will match.
Chris Lattner9fecd742009-04-19 05:21:20 +00003387 QualType T = NewTD->getUnderlyingType();
3388 if (T->isVariablyModifiedType()) {
John McCallaab3e412010-08-25 08:40:02 +00003389 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00003390
Chris Lattner9fecd742009-04-19 05:21:20 +00003391 if (S->getFnParent() == 0) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00003392 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003393 llvm::APSInt Oversized;
Eli Friedmana3b1d032009-02-21 00:44:51 +00003394 QualType FixedTy =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003395 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
3396 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003397 if (!FixedTy.isNull()) {
Richard Smithdda56e42011-04-15 14:24:37 +00003398 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
John McCallbcd03502009-12-07 02:54:59 +00003399 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
Eli Friedmana3b1d032009-02-21 00:44:51 +00003400 } else {
3401 if (SizeIsNegative)
Richard Smithdda56e42011-04-15 14:24:37 +00003402 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003403 else if (T->isVariableArrayType())
Richard Smithdda56e42011-04-15 14:24:37 +00003404 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003405 else if (Oversized.getBoolValue())
Richard Smithdda56e42011-04-15 14:24:37 +00003406 Diag(NewTD->getLocation(), diag::err_array_too_large) << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003407 else
Richard Smithdda56e42011-04-15 14:24:37 +00003408 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003409 NewTD->setInvalidDecl();
Eli Friedmana3b1d032009-02-21 00:44:51 +00003410 }
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003411 }
3412 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003413}
Douglas Gregor27821ce2009-07-07 16:35:42 +00003414
Richard Smith3f1b5d02011-05-05 21:57:07 +00003415
3416/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
3417/// declares a typedef-name, either using the 'typedef' type specifier or via
3418/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
3419NamedDecl*
3420Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
3421 LookupResult &Previous, bool &Redeclaration) {
Eli Friedman88f4ed92010-08-10 03:13:15 +00003422 // Merge the decl with the existing one if appropriate. If the decl is
3423 // in an outer scope, it isn't the same thing.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003424 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
Douglas Gregordb446112011-03-07 16:54:27 +00003425 /*ExplicitInstantiationOrSpecialization=*/false);
Eli Friedman88f4ed92010-08-10 03:13:15 +00003426 if (!Previous.empty()) {
3427 Redeclaration = true;
Richard Smithdda56e42011-04-15 14:24:37 +00003428 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00003429 }
3430
Douglas Gregor27821ce2009-07-07 16:35:42 +00003431 // If this is the C FILE type, notify the AST context.
3432 if (IdentifierInfo *II = NewTD->getIdentifier())
3433 if (!NewTD->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003434 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stumpa4de80b2009-07-28 02:25:19 +00003435 if (II->isStr("FILE"))
3436 Context.setFILEDecl(NewTD);
3437 else if (II->isStr("jmp_buf"))
3438 Context.setjmp_bufDecl(NewTD);
3439 else if (II->isStr("sigjmp_buf"))
3440 Context.setsigjmp_bufDecl(NewTD);
Douglas Gregor2c2c4cd2010-10-05 15:41:24 +00003441 else if (II->isStr("__builtin_va_list"))
3442 Context.setBuiltinVaListType(Context.getTypedefType(NewTD));
Mike Stumpa4de80b2009-07-28 02:25:19 +00003443 }
3444
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003445 return NewTD;
3446}
3447
Douglas Gregor5d68a202009-02-24 19:23:27 +00003448/// \brief Determines whether the given declaration is an out-of-scope
3449/// previous declaration.
3450///
3451/// This routine should be invoked when name lookup has found a
3452/// previous declaration (PrevDecl) that is not in the scope where a
3453/// new declaration by the same name is being introduced. If the new
3454/// declaration occurs in a local scope, previous declarations with
3455/// linkage may still be considered previous declarations (C99
3456/// 6.2.2p4-5, C++ [basic.link]p6).
3457///
3458/// \param PrevDecl the previous declaration found by name
3459/// lookup
Mike Stump11289f42009-09-09 15:08:12 +00003460///
Douglas Gregor5d68a202009-02-24 19:23:27 +00003461/// \param DC the context in which the new declaration is being
3462/// declared.
3463///
3464/// \returns true if PrevDecl is an out-of-scope previous declaration
3465/// for a new delcaration with the same name.
Mike Stump11289f42009-09-09 15:08:12 +00003466static bool
Douglas Gregor5d68a202009-02-24 19:23:27 +00003467isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
3468 ASTContext &Context) {
3469 if (!PrevDecl)
Sebastian Redl50c68252010-08-31 00:36:30 +00003470 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00003471
Douglas Gregoreddf4332009-02-24 20:03:32 +00003472 if (!PrevDecl->hasLinkage())
3473 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00003474
3475 if (Context.getLangOptions().CPlusPlus) {
3476 // C++ [basic.link]p6:
3477 // If there is a visible declaration of an entity with linkage
3478 // having the same name and type, ignoring entities declared
3479 // outside the innermost enclosing namespace scope, the block
3480 // scope declaration declares that same entity and receives the
3481 // linkage of the previous declaration.
Sebastian Redl50c68252010-08-31 00:36:30 +00003482 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor5d68a202009-02-24 19:23:27 +00003483 if (!OuterContext->isFunctionOrMethod())
3484 // This rule only applies to block-scope declarations.
3485 return false;
Douglas Gregorfcee9462010-08-27 22:55:10 +00003486
3487 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
3488 if (PrevOuterContext->isRecord())
3489 // We found a member function: ignore it.
3490 return false;
3491
3492 // Find the innermost enclosing namespace for the new and
3493 // previous declarations.
Sebastian Redl50c68252010-08-31 00:36:30 +00003494 OuterContext = OuterContext->getEnclosingNamespaceContext();
3495 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump11289f42009-09-09 15:08:12 +00003496
Douglas Gregorfcee9462010-08-27 22:55:10 +00003497 // The previous declaration is in a different namespace, so it
3498 // isn't the same function.
3499 if (!OuterContext->Equals(PrevOuterContext))
3500 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00003501 }
3502
Douglas Gregor5d68a202009-02-24 19:23:27 +00003503 return true;
3504}
3505
John McCall3e11ebe2010-03-15 10:12:16 +00003506static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
3507 CXXScopeSpec &SS = D.getCXXScopeSpec();
3508 if (!SS.isSet()) return;
Douglas Gregor14454802011-02-25 02:25:35 +00003509 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00003510}
3511
John McCall31168b02011-06-15 23:02:42 +00003512bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
3513 QualType type = decl->getType();
3514 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
3515 if (lifetime == Qualifiers::OCL_Autoreleasing) {
3516 // Various kinds of declaration aren't allowed to be __autoreleasing.
3517 unsigned kind = -1U;
3518 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
3519 if (var->hasAttr<BlocksAttr>())
3520 kind = 0; // __block
3521 else if (!var->hasLocalStorage())
3522 kind = 1; // global
3523 } else if (isa<ObjCIvarDecl>(decl)) {
3524 kind = 3; // ivar
3525 } else if (isa<FieldDecl>(decl)) {
3526 kind = 2; // field
3527 }
3528
3529 if (kind != -1U) {
3530 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
3531 << kind;
3532 }
3533 } else if (lifetime == Qualifiers::OCL_None) {
3534 // Try to infer lifetime.
3535 if (!type->isObjCLifetimeType())
3536 return false;
3537
3538 lifetime = type->getObjCARCImplicitLifetime();
3539 type = Context.getLifetimeQualifiedType(type, lifetime);
3540 decl->setType(type);
3541 }
3542
3543 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
3544 // Thread-local variables cannot have lifetime.
3545 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
3546 var->isThreadSpecified()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003547 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCall31168b02011-06-15 23:02:42 +00003548 << var->getType();
3549 return true;
3550 }
3551 }
3552
3553 return false;
3554}
3555
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003556NamedDecl*
Chris Lattner88fdea82010-10-10 18:16:20 +00003557Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
John McCallbcd03502009-12-07 02:54:59 +00003558 QualType R, TypeSourceInfo *TInfo,
John McCall1f82f242009-11-18 22:49:29 +00003559 LookupResult &Previous,
Douglas Gregorb09f3d82009-07-22 17:18:37 +00003560 MultiTemplateParamsArg TemplateParamLists,
Douglas Gregor75a45ba2009-02-16 17:45:42 +00003561 bool &Redeclaration) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003562 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003563
3564 // Check that there are no default arguments (C++ only).
3565 if (getLangOptions().CPlusPlus)
3566 CheckExtraCXXDefaultArguments(D);
3567
Douglas Gregorc4df4072010-04-19 22:54:31 +00003568 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
3569 assert(SCSpec != DeclSpec::SCS_typedef &&
3570 "Parser allowed 'typedef' as storage class VarDecl.");
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00003571 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregorc4df4072010-04-19 22:54:31 +00003572 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003573 // mutable can only appear on non-static class members, so it's always
3574 // an error here
3575 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003576 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003577 SC = SC_None;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003578 }
Douglas Gregorc4df4072010-04-19 22:54:31 +00003579 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
3580 VarDecl::StorageClass SCAsWritten
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00003581 = StorageClassSpecToVarDeclStorageClass(SCSpec);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003582
3583 IdentifierInfo *II = Name.getAsIdentifierInfo();
3584 if (!II) {
3585 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
3586 << Name.getAsString();
3587 return 0;
3588 }
3589
Eli Friedman574c7452009-04-07 19:37:57 +00003590 DiagnoseFunctionSpecifiers(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00003591
Douglas Gregor212cab32009-03-11 20:22:50 +00003592 if (!DC->isRecord() && S->getFnParent() == 0) {
3593 // C99 6.9p2: The storage-class specifiers auto and register shall not
3594 // appear in the declaration specifiers in an external declaration.
John McCall8e7d6562010-08-26 03:08:43 +00003595 if (SC == SC_Auto || SC == SC_Register) {
Mike Stump11289f42009-09-09 15:08:12 +00003596
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00003597 // If this is a register variable with an asm label specified, then this
3598 // is a GNU extension.
John McCall8e7d6562010-08-26 03:08:43 +00003599 if (SC == SC_Register && D.getAsmLabel())
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00003600 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
3601 else
3602 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003603 D.setInvalidType();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003604 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003605 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003606
Ted Kremenek582a0992011-01-23 17:04:59 +00003607 bool isExplicitSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003608 VarDecl *NewVD;
3609 if (!getLangOptions().CPlusPlus) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003610 NewVD = VarDecl::Create(Context, DC, D.getSourceRange().getBegin(),
3611 D.getIdentifierLoc(), II,
3612 R, TInfo, SC, SCAsWritten);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003613
3614 if (D.isInvalidType())
3615 NewVD->setInvalidDecl();
3616 } else {
3617 if (DC->isRecord() && !CurContext->isRecord()) {
3618 // This is an out-of-line definition of a static data member.
3619 if (SC == SC_Static) {
3620 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
3621 diag::err_static_out_of_line)
3622 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3623 } else if (SC == SC_None)
3624 SC = SC_Static;
Anders Carlssond2e8adf2009-06-24 00:28:53 +00003625 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003626 if (SC == SC_Static) {
3627 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
3628 if (RD->isLocalClass())
3629 Diag(D.getIdentifierLoc(),
3630 diag::err_static_data_member_not_allowed_in_local_class)
3631 << Name << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003632
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003633 // C++ [class.union]p1: If a union contains a static data member,
3634 // the program is ill-formed.
3635 //
3636 // We also disallow static data members in anonymous structs.
3637 if (CurContext->isRecord() && (RD->isUnion() || !RD->getDeclName()))
3638 Diag(D.getIdentifierLoc(),
3639 diag::err_static_data_member_not_allowed_in_union_or_anon_struct)
3640 << Name << RD->isUnion();
3641 }
3642 }
3643
3644 // Match up the template parameter lists with the scope specifier, then
3645 // determine whether we have a template or a template specialization.
3646 isExplicitSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003647 bool Invalid = false;
3648 if (TemplateParameterList *TemplateParams
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003649 = MatchTemplateParametersToScopeSpecifier(
Douglas Gregor972fe532011-05-10 18:27:06 +00003650 D.getDeclSpec().getSourceRange().getBegin(),
3651 D.getIdentifierLoc(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003652 D.getCXXScopeSpec(),
John McCallace48cd2010-10-19 01:40:49 +00003653 TemplateParamLists.get(),
3654 TemplateParamLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00003655 /*never a friend*/ false,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003656 isExplicitSpecialization,
3657 Invalid)) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003658 if (TemplateParams->size() > 0) {
3659 // There is no such thing as a variable template.
3660 Diag(D.getIdentifierLoc(), diag::err_template_variable)
3661 << II
3662 << SourceRange(TemplateParams->getTemplateLoc(),
3663 TemplateParams->getRAngleLoc());
3664 return 0;
3665 } else {
3666 // There is an extraneous 'template<>' for this variable. Complain
3667 // about it, but allow the declaration of the variable.
3668 Diag(TemplateParams->getTemplateLoc(),
3669 diag::err_template_variable_noparams)
3670 << II
3671 << SourceRange(TemplateParams->getTemplateLoc(),
3672 TemplateParams->getRAngleLoc());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003673 }
Douglas Gregorb09f3d82009-07-22 17:18:37 +00003674 }
Mike Stump11289f42009-09-09 15:08:12 +00003675
Abramo Bagnaradff19302011-03-08 08:55:46 +00003676 NewVD = VarDecl::Create(Context, DC, D.getSourceRange().getBegin(),
3677 D.getIdentifierLoc(), II,
3678 R, TInfo, SC, SCAsWritten);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003679
Richard Smithb2bc2e62011-02-21 20:05:19 +00003680 // If this decl has an auto type in need of deduction, make a note of the
3681 // Decl so we can diagnose uses of it in its own initializer.
3682 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
3683 R->getContainedAutoType())
3684 ParsingInitForAutoVars.insert(NewVD);
Richard Smith30482bc2011-02-20 03:19:35 +00003685
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003686 if (D.isInvalidType() || Invalid)
3687 NewVD->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003688
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003689 SetNestedNameSpecifier(NewVD, D);
John McCall3e11ebe2010-03-15 10:12:16 +00003690
Abramo Bagnara60804e12011-03-18 15:16:37 +00003691 if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003692 NewVD->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00003693 TemplateParamLists.size(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003694 TemplateParamLists.release());
3695 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003696 }
3697
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003698 if (D.getDeclSpec().isThreadSpecified()) {
3699 if (NewVD->hasLocalStorage())
3700 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
Eli Friedmandaea3f62009-04-19 21:48:33 +00003701 else if (!Context.Target.isTLSSupported())
3702 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003703 else
3704 NewVD->setThreadSpecified(true);
3705 }
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003706
Douglas Gregor04e9a032009-03-11 23:52:16 +00003707 // Set the lexical context. If the declarator has a C++ scope specifier, the
3708 // lexical context will be different from the semantic context.
3709 NewVD->setLexicalDeclContext(CurContext);
3710
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003711 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00003712 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003713
John McCall31168b02011-06-15 23:02:42 +00003714 // In auto-retain/release, infer strong retension for variables of
3715 // retainable type.
3716 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
3717 NewVD->setInvalidDecl();
3718
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003719 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner88fdea82010-10-10 18:16:20 +00003720 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003721 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00003722 StringLiteral *SE = cast<StringLiteral>(E);
Rafael Espindola478abca2011-01-01 21:47:03 +00003723 llvm::StringRef Label = SE->getString();
Abramo Bagnara13392232011-01-11 15:16:52 +00003724 if (S->getFnParent() != 0) {
3725 switch (SC) {
3726 case SC_None:
3727 case SC_Auto:
3728 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
3729 break;
3730 case SC_Register:
3731 if (!Context.Target.isValidGCCRegisterName(Label))
3732 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
3733 break;
3734 case SC_Static:
3735 case SC_Extern:
3736 case SC_PrivateExtern:
3737 break;
3738 }
3739 }
3740
3741 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Rafael Espindola478abca2011-01-01 21:47:03 +00003742 Context, Label));
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003743 }
3744
John McCalla2a3f7d2010-03-16 21:48:18 +00003745 // Diagnose shadowed variables before filtering for scope.
John McCall2d8c7602010-03-20 04:12:52 +00003746 if (!D.getCXXScopeSpec().isSet())
John McCalldf8b37c2010-03-22 09:20:08 +00003747 CheckShadow(S, NewVD, Previous);
John McCalla2a3f7d2010-03-16 21:48:18 +00003748
John McCall1f82f242009-11-18 22:49:29 +00003749 // Don't consider existing declarations that are in a different
3750 // scope and are out-of-semantic-context declarations (if the new
3751 // declaration has linkage).
Richard Smith3f1b5d02011-05-05 21:57:07 +00003752 FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(),
Douglas Gregordb446112011-03-07 16:54:27 +00003753 isExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00003754
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003755 if (!getLangOptions().CPlusPlus)
3756 CheckVariableDeclaration(NewVD, Previous, Redeclaration);
3757 else {
3758 // Merge the decl with the existing one if appropriate.
3759 if (!Previous.empty()) {
3760 if (Previous.isSingleResult() &&
3761 isa<FieldDecl>(Previous.getFoundDecl()) &&
3762 D.getCXXScopeSpec().isSet()) {
3763 // The user tried to define a non-static data member
3764 // out-of-line (C++ [dcl.meaning]p1).
3765 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
3766 << D.getCXXScopeSpec().getRange();
3767 Previous.clear();
3768 NewVD->setInvalidDecl();
3769 }
3770 } else if (D.getCXXScopeSpec().isSet()) {
3771 // No previous declaration in the qualifying scope.
3772 Diag(D.getIdentifierLoc(), diag::err_no_member)
3773 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003774 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003775 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003776 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003777
3778 CheckVariableDeclaration(NewVD, Previous, Redeclaration);
3779
3780 // This is an explicit specialization of a static data member. Check it.
3781 if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
3782 CheckMemberSpecialization(NewVD, Previous))
3783 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003784 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003785
Ryan Flynne5dc8592009-07-25 22:29:44 +00003786 // attributes declared post-definition are currently ignored
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003787 // FIXME: This should be handled in attribute merging, not
3788 // here.
John McCall1f82f242009-11-18 22:49:29 +00003789 if (Previous.isSingleResult()) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00003790 VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl());
3791 if (Def && (Def = Def->getDefinition()) &&
3792 Def != NewVD && D.hasAttributes()) {
Ryan Flynne5dc8592009-07-25 22:29:44 +00003793 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
3794 Diag(Def->getLocation(), diag::note_previous_definition);
3795 }
3796 }
3797
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003798 // If this is a locally-scoped extern C variable, update the map of
3799 // such variables.
Douglas Gregor16618f22009-09-12 00:17:51 +00003800 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003801 !NewVD->isInvalidDecl())
John McCall1f82f242009-11-18 22:49:29 +00003802 RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003803
Eli Friedman570024a2010-08-05 06:57:20 +00003804 // If there's a #pragma GCC visibility in scope, and this isn't a class
3805 // member, set the visibility of this variable.
3806 if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord())
3807 AddPushedVisibilityAttribute(NewVD);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003808
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00003809 MarkUnusedFileScopedDecl(NewVD);
3810
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003811 return NewVD;
3812}
3813
John McCalldf8b37c2010-03-22 09:20:08 +00003814/// \brief Diagnose variable or built-in function shadowing. Implements
3815/// -Wshadow.
John McCalla2a3f7d2010-03-16 21:48:18 +00003816///
John McCalldf8b37c2010-03-22 09:20:08 +00003817/// This method is called whenever a VarDecl is added to a "useful"
3818/// scope.
John McCalla2a3f7d2010-03-16 21:48:18 +00003819///
John McCall2d8c7602010-03-20 04:12:52 +00003820/// \param S the scope in which the shadowing name is being declared
3821/// \param R the lookup of the name
John McCalla2a3f7d2010-03-16 21:48:18 +00003822///
John McCalldf8b37c2010-03-22 09:20:08 +00003823void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCalla2a3f7d2010-03-16 21:48:18 +00003824 // Return if warning is ignored.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003825 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
3826 Diagnostic::Ignored)
John McCalla2a3f7d2010-03-16 21:48:18 +00003827 return;
3828
Argyrios Kyrtzidis898fdbf2011-02-08 18:21:25 +00003829 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00003830 if (D->hasGlobalStorage())
John McCalla2a3f7d2010-03-16 21:48:18 +00003831 return;
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00003832
3833 DeclContext *NewDC = D->getDeclContext();
3834
John McCall2d8c7602010-03-20 04:12:52 +00003835 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregor319aa6c2010-03-17 16:03:44 +00003836 if (R.getResultKind() != LookupResult::Found)
John McCalla2a3f7d2010-03-16 21:48:18 +00003837 return;
John McCalla2a3f7d2010-03-16 21:48:18 +00003838
John McCalla2a3f7d2010-03-16 21:48:18 +00003839 NamedDecl* ShadowedDecl = R.getFoundDecl();
3840 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
3841 return;
3842
Argyrios Kyrtzidisf46cc652011-01-31 07:04:54 +00003843 // Fields are not shadowed by variables in C++ static methods.
3844 if (isa<FieldDecl>(ShadowedDecl))
3845 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
3846 if (MD->isStatic())
3847 return;
3848
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00003849 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
3850 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00003851 // For shadowing external vars, make sure that we point to the global
3852 // declaration, not a locally scoped extern declaration.
3853 for (VarDecl::redecl_iterator
3854 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
3855 I != E; ++I)
3856 if (I->isFileVarDecl()) {
3857 ShadowedDecl = *I;
3858 break;
3859 }
3860 }
3861
3862 DeclContext *OldDC = ShadowedDecl->getDeclContext();
3863
John McCall2d8c7602010-03-20 04:12:52 +00003864 // Only warn about certain kinds of shadowing for class members.
3865 if (NewDC && NewDC->isRecord()) {
3866 // In particular, don't warn about shadowing non-class members.
3867 if (!OldDC->isRecord())
3868 return;
3869
3870 // TODO: should we warn about static data members shadowing
3871 // static data members from base classes?
3872
3873 // TODO: don't diagnose for inaccessible shadowed members.
3874 // This is hard to do perfectly because we might friend the
3875 // shadowing context, but that's just a false negative.
3876 }
3877
3878 // Determine what kind of declaration we're shadowing.
John McCalla2a3f7d2010-03-16 21:48:18 +00003879 unsigned Kind;
John McCall2d8c7602010-03-20 04:12:52 +00003880 if (isa<RecordDecl>(OldDC)) {
John McCalla2a3f7d2010-03-16 21:48:18 +00003881 if (isa<FieldDecl>(ShadowedDecl))
3882 Kind = 3; // field
3883 else
3884 Kind = 2; // static data member
John McCall2d8c7602010-03-20 04:12:52 +00003885 } else if (OldDC->isFileContext())
John McCalla2a3f7d2010-03-16 21:48:18 +00003886 Kind = 1; // global
3887 else
3888 Kind = 0; // local
3889
John McCall2d8c7602010-03-20 04:12:52 +00003890 DeclarationName Name = R.getLookupName();
3891
John McCalla2a3f7d2010-03-16 21:48:18 +00003892 // Emit warning and note.
John McCall2d8c7602010-03-20 04:12:52 +00003893 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCalla2a3f7d2010-03-16 21:48:18 +00003894 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
3895}
3896
John McCalldf8b37c2010-03-22 09:20:08 +00003897/// \brief Check -Wshadow without the advantage of a previous lookup.
3898void Sema::CheckShadow(Scope *S, VarDecl *D) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003899 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
3900 Diagnostic::Ignored)
3901 return;
3902
John McCalldf8b37c2010-03-22 09:20:08 +00003903 LookupResult R(*this, D->getDeclName(), D->getLocation(),
3904 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
3905 LookupName(R, S);
3906 CheckShadow(S, D, R);
3907}
3908
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003909/// \brief Perform semantic checking on a newly-created variable
3910/// declaration.
3911///
3912/// This routine performs all of the type-checking required for a
Douglas Gregorf16a8a72009-05-01 15:47:09 +00003913/// variable declaration once it has been built. It is used both to
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003914/// check variables after they have been parsed and their declarators
Douglas Gregorf16a8a72009-05-01 15:47:09 +00003915/// have been translated into a declaration, and to check variables
3916/// that have been instantiated from a template.
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003917///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003918/// Sets NewVD->isInvalidDecl() if an error was encountered.
John McCall1f82f242009-11-18 22:49:29 +00003919void Sema::CheckVariableDeclaration(VarDecl *NewVD,
3920 LookupResult &Previous,
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003921 bool &Redeclaration) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003922 // If the decl is already known invalid, don't check it.
3923 if (NewVD->isInvalidDecl())
3924 return;
Mike Stump11289f42009-09-09 15:08:12 +00003925
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003926 QualType T = NewVD->getType();
3927
John McCall8b07ec22010-05-15 11:32:37 +00003928 if (T->isObjCObjectType()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003929 Diag(NewVD->getLocation(), diag::err_statically_allocated_object);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003930 return NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003931 }
Mike Stump11289f42009-09-09 15:08:12 +00003932
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003933 // Emit an error if an address space was applied to decl with local storage.
3934 // This includes arrays of objects with address space qualifiers, but not
3935 // automatic variables that point to other address spaces.
3936 // ISO/IEC TR 18037 S5.1.2
Chris Lattner88fdea82010-10-10 18:16:20 +00003937 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003938 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003939 return NewVD->setInvalidDecl();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003940 }
Fariborz Jahanian0c9404e2009-02-21 19:44:02 +00003941
Mike Stumpca5ae662009-04-14 00:57:29 +00003942 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00003943 && !NewVD->hasAttr<BlocksAttr>()) {
3944 if (getLangOptions().getGCMode() != LangOptions::NonGC)
3945 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
3946 else
3947 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
3948 }
Chris Lattner88fdea82010-10-10 18:16:20 +00003949
Chris Lattner9fecd742009-04-19 05:21:20 +00003950 bool isVM = T->isVariablyModifiedType();
Chris Lattner9662cd32009-07-19 20:17:11 +00003951 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalld4e1b762010-08-01 01:24:59 +00003952 NewVD->hasAttr<BlocksAttr>())
John McCallaab3e412010-08-25 08:40:02 +00003953 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00003954
Chris Lattner9fecd742009-04-19 05:21:20 +00003955 if ((isVM && NewVD->hasLinkage()) ||
3956 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson6c885802009-02-28 21:56:50 +00003957 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003958 llvm::APSInt Oversized;
Anders Carlsson6c885802009-02-28 21:56:50 +00003959 QualType FixedTy =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003960 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
3961 Oversized);
Mike Stump11289f42009-09-09 15:08:12 +00003962
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003963 if (FixedTy.isNull() && T->isVariableArrayType()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003964 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00003965 // FIXME: This won't give the correct result for
3966 // int a[10][n];
Anders Carlsson6c885802009-02-28 21:56:50 +00003967 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003968
Anders Carlsson6c885802009-02-28 21:56:50 +00003969 if (NewVD->isFileVarDecl())
3970 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003971 << SizeRange;
John McCall8e7d6562010-08-26 03:08:43 +00003972 else if (NewVD->getStorageClass() == SC_Static)
Anders Carlsson6c885802009-02-28 21:56:50 +00003973 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003974 << SizeRange;
Anders Carlsson6c885802009-02-28 21:56:50 +00003975 else
3976 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003977 << SizeRange;
3978 return NewVD->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003979 }
3980
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003981 if (FixedTy.isNull()) {
Anders Carlsson6c885802009-02-28 21:56:50 +00003982 if (NewVD->isFileVarDecl())
3983 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
3984 else
3985 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003986 return NewVD->setInvalidDecl();
Anders Carlsson6c885802009-02-28 21:56:50 +00003987 }
Mike Stump11289f42009-09-09 15:08:12 +00003988
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003989 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
3990 NewVD->setType(FixedTy);
Anders Carlsson6c885802009-02-28 21:56:50 +00003991 }
3992
John McCall1f82f242009-11-18 22:49:29 +00003993 if (Previous.empty() && NewVD->isExternC()) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003994 // Since we did not find anything by this name and we're declaring
3995 // an extern "C" variable, look for a non-visible extern "C"
3996 // declaration with the same name.
3997 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003998 = LocallyScopedExternalDecls.find(NewVD->getDeclName());
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003999 if (Pos != LocallyScopedExternalDecls.end())
John McCall1f82f242009-11-18 22:49:29 +00004000 Previous.addDecl(Pos->second);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004001 }
4002
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004003 if (T->isVoidType() && !NewVD->hasExternalStorage()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004004 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
4005 << T;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004006 return NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004007 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004008
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004009 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00004010 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
4011 return NewVD->setInvalidDecl();
4012 }
Mike Stump11289f42009-09-09 15:08:12 +00004013
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004014 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpa7128632009-05-01 23:41:47 +00004015 Diag(NewVD->getLocation(), diag::err_block_on_vm);
4016 return NewVD->setInvalidDecl();
4017 }
4018
Sebastian Redl5467c9f2010-07-12 23:11:43 +00004019 // Function pointers and references cannot have qualified function type, only
4020 // function pointer-to-members can do that.
4021 QualType Pointee;
4022 unsigned PtrOrRef = 0;
4023 if (const PointerType *Ptr = T->getAs<PointerType>())
4024 Pointee = Ptr->getPointeeType();
4025 else if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
4026 Pointee = Ref->getPointeeType();
4027 PtrOrRef = 1;
4028 }
4029 if (!Pointee.isNull() && Pointee->isFunctionProtoType() &&
4030 Pointee->getAs<FunctionProtoType>()->getTypeQuals() != 0) {
4031 Diag(NewVD->getLocation(), diag::err_invalid_qualified_function_pointer)
4032 << PtrOrRef;
4033 return NewVD->setInvalidDecl();
4034 }
4035
John McCall1f82f242009-11-18 22:49:29 +00004036 if (!Previous.empty()) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00004037 Redeclaration = true;
John McCall1f82f242009-11-18 22:49:29 +00004038 MergeVarDecl(NewVD, Previous);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004039 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004040}
4041
Douglas Gregor36d1b142009-10-06 17:59:45 +00004042/// \brief Data used with FindOverriddenMethod
4043struct FindOverriddenMethodData {
4044 Sema *S;
4045 CXXMethodDecl *Method;
4046};
4047
4048/// \brief Member lookup function that determines whether a given C++
4049/// method overrides a method in a base class, to be used with
4050/// CXXRecordDecl::lookupInBases().
John McCall84c16cf2009-11-12 03:15:40 +00004051static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregor36d1b142009-10-06 17:59:45 +00004052 CXXBasePath &Path,
4053 void *UserData) {
4054 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlssone985fae2009-11-26 20:50:40 +00004055
Douglas Gregor36d1b142009-10-06 17:59:45 +00004056 FindOverriddenMethodData *Data
4057 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlssone985fae2009-11-26 20:50:40 +00004058
4059 DeclarationName Name = Data->Method->getDeclName();
4060
4061 // FIXME: Do we care about other names here too?
4062 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCalle9cccd82010-06-16 08:42:20 +00004063 // We really want to find the base class destructor here.
Anders Carlssone985fae2009-11-26 20:50:40 +00004064 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
4065 CanQualType CT = Data->S->Context.getCanonicalType(T);
4066
Anders Carlsson5a4f7722009-11-27 01:26:58 +00004067 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlssone985fae2009-11-26 20:50:40 +00004068 }
4069
4070 for (Path.Decls = BaseRecord->lookup(Name);
Douglas Gregor36d1b142009-10-06 17:59:45 +00004071 Path.Decls.first != Path.Decls.second;
4072 ++Path.Decls.first) {
John McCall38e5f432010-06-16 09:33:39 +00004073 NamedDecl *D = *Path.Decls.first;
John McCalle9cccd82010-06-16 08:42:20 +00004074 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4075 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregor36d1b142009-10-06 17:59:45 +00004076 return true;
4077 }
4078 }
4079
4080 return false;
4081}
4082
Sebastian Redld5b24532009-11-18 21:51:29 +00004083/// AddOverriddenMethods - See if a method overrides any in the base classes,
4084/// and if so, check that it's a valid override and remember it.
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004085bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redld5b24532009-11-18 21:51:29 +00004086 // Look for virtual methods in base classes that this method might override.
4087 CXXBasePaths Paths;
4088 FindOverriddenMethodData Data;
4089 Data.Method = MD;
4090 Data.S = this;
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004091 bool AddedAny = false;
Sebastian Redld5b24532009-11-18 21:51:29 +00004092 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
4093 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
4094 E = Paths.found_decls_end(); I != E; ++I) {
4095 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
Richard Trieu95d88092011-07-01 20:02:53 +00004096 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redld5b24532009-11-18 21:51:29 +00004097 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Alexis Hunt96d5c762009-11-21 08:43:09 +00004098 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
Anders Carlsson3f610c72011-01-20 16:25:36 +00004099 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004100 AddedAny = true;
4101 }
Sebastian Redld5b24532009-11-18 21:51:29 +00004102 }
4103 }
4104 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004105
4106 return AddedAny;
Sebastian Redld5b24532009-11-18 21:51:29 +00004107}
4108
John McCallf7cfb222010-10-13 05:45:15 +00004109static void DiagnoseInvalidRedeclaration(Sema &S, FunctionDecl *NewFD) {
4110 LookupResult Prev(S, NewFD->getDeclName(), NewFD->getLocation(),
4111 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
4112 S.LookupQualifiedName(Prev, NewFD->getDeclContext());
4113 assert(!Prev.isAmbiguous() &&
4114 "Cannot have an ambiguity in previous-declaration lookup");
4115 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
4116 Func != FuncEnd; ++Func) {
4117 if (isa<FunctionDecl>(*Func) &&
4118 isNearlyMatchingFunction(S.Context, cast<FunctionDecl>(*Func), NewFD))
4119 S.Diag((*Func)->getLocation(), diag::note_member_def_close_match);
4120 }
4121}
4122
Mike Stump11289f42009-09-09 15:08:12 +00004123NamedDecl*
Nick Lewycky0bdf13e2011-07-02 02:05:12 +00004124Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
John McCallbcd03502009-12-07 02:54:59 +00004125 QualType R, TypeSourceInfo *TInfo,
John McCall1f82f242009-11-18 22:49:29 +00004126 LookupResult &Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004127 MultiTemplateParamsArg TemplateParamLists,
Alexis Hunt5a7fa252011-05-12 06:15:49 +00004128 bool IsFunctionDefinition, bool &Redeclaration) {
Zhongxing Xubece5d62009-01-16 01:13:29 +00004129 assert(R.getTypePtr()->isFunctionType());
4130
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004131 // TODO: consider using NameInfo for diagnostic.
4132 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4133 DeclarationName Name = NameInfo.getName();
John McCall8e7d6562010-08-26 03:08:43 +00004134 FunctionDecl::StorageClass SC = SC_None;
Zhongxing Xubece5d62009-01-16 01:13:29 +00004135 switch (D.getDeclSpec().getStorageClassSpec()) {
4136 default: assert(0 && "Unknown storage class!");
4137 case DeclSpec::SCS_auto:
4138 case DeclSpec::SCS_register:
4139 case DeclSpec::SCS_mutable:
Mike Stump11289f42009-09-09 15:08:12 +00004140 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregore62c0a42009-02-24 01:23:02 +00004141 diag::err_typecheck_sclass_func);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004142 D.setInvalidType();
Zhongxing Xubece5d62009-01-16 01:13:29 +00004143 break;
John McCall8e7d6562010-08-26 03:08:43 +00004144 case DeclSpec::SCS_unspecified: SC = SC_None; break;
4145 case DeclSpec::SCS_extern: SC = SC_Extern; break;
Douglas Gregore62c0a42009-02-24 01:23:02 +00004146 case DeclSpec::SCS_static: {
Sebastian Redl50c68252010-08-31 00:36:30 +00004147 if (CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregore62c0a42009-02-24 01:23:02 +00004148 // C99 6.7.1p5:
4149 // The declaration of an identifier for a function that has
4150 // block scope shall have no explicit storage-class specifier
4151 // other than extern
4152 // See also (C++ [dcl.stc]p4).
Mike Stump11289f42009-09-09 15:08:12 +00004153 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregore62c0a42009-02-24 01:23:02 +00004154 diag::err_static_block_func);
John McCall8e7d6562010-08-26 03:08:43 +00004155 SC = SC_None;
Douglas Gregore62c0a42009-02-24 01:23:02 +00004156 } else
John McCall8e7d6562010-08-26 03:08:43 +00004157 SC = SC_Static;
Douglas Gregore62c0a42009-02-24 01:23:02 +00004158 break;
4159 }
Gabor Greif80c21832010-09-08 00:31:13 +00004160 case DeclSpec::SCS_private_extern: SC = SC_PrivateExtern; break;
Zhongxing Xubece5d62009-01-16 01:13:29 +00004161 }
4162
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004163 if (D.getDeclSpec().isThreadSpecified())
4164 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4165
Chris Lattner347eec92009-04-11 19:17:25 +00004166 // Do not allow returning a objc interface by-value.
John McCall8b07ec22010-05-15 11:32:37 +00004167 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
Chris Lattner347eec92009-04-11 19:17:25 +00004168 Diag(D.getIdentifierLoc(),
4169 diag::err_object_cannot_be_passed_returned_by_value) << 0
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004170 << R->getAs<FunctionType>()->getResultType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004171 D.setInvalidType();
Chris Lattner347eec92009-04-11 19:17:25 +00004172 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004173
Zhongxing Xubece5d62009-01-16 01:13:29 +00004174 FunctionDecl *NewFD;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004175 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor513e63c2010-12-10 19:28:19 +00004176 bool isFriend = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004177 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
4178 FunctionDecl::StorageClass SCAsWritten
4179 = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
Douglas Gregor513e63c2010-12-10 19:28:19 +00004180 FunctionTemplateDecl *FunctionTemplate = 0;
4181 bool isExplicitSpecialization = false;
4182 bool isFunctionTemplateSpecialization = false;
Abramo Bagnara60804e12011-03-18 15:16:37 +00004183
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004184 if (!getLangOptions().CPlusPlus) {
Douglas Gregor2797d322009-03-19 18:33:54 +00004185 // Determine whether the function was written with a
4186 // prototype. This true when:
Douglas Gregor2797d322009-03-19 18:33:54 +00004187 // - there is a prototype in the declarator, or
4188 // - the type R of the function is some kind of typedef or other reference
4189 // to a type name (which eventually refers to a function type).
Mike Stump11289f42009-09-09 15:08:12 +00004190 bool HasPrototype =
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004191 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004192 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
4193
Abramo Bagnaradff19302011-03-08 08:55:46 +00004194 NewFD = FunctionDecl::Create(Context, DC, D.getSourceRange().getBegin(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004195 NameInfo, R, TInfo, SC, SCAsWritten, isInline,
Douglas Gregorc4df4072010-04-19 22:54:31 +00004196 HasPrototype);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004197 if (D.isInvalidType())
4198 NewFD->setInvalidDecl();
4199
4200 // Set the lexical context.
4201 NewFD->setLexicalDeclContext(CurContext);
4202 // Filter out previous declarations that don't match the scope.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004203 FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(),
Douglas Gregordb446112011-03-07 16:54:27 +00004204 /*ExplicitInstantiationOrSpecialization=*/false);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004205 } else {
4206 isFriend = D.getDeclSpec().isFriendSpecified();
Douglas Gregor513e63c2010-12-10 19:28:19 +00004207 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
4208 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
4209 bool isVirtualOkay = false;
Zhongxing Xubece5d62009-01-16 01:13:29 +00004210
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004211 // Check that the return type is not an abstract class type.
4212 // For record types, this is done by the AbstractClassUsageDiagnoser once
4213 // the class has been completely parsed.
4214 if (!DC->isRecord() &&
4215 RequireNonAbstractType(D.getIdentifierLoc(),
4216 R->getAs<FunctionType>()->getResultType(),
4217 diag::err_abstract_type_in_decl,
4218 AbstractReturnType))
4219 D.setInvalidType();
Mike Stump11289f42009-09-09 15:08:12 +00004220
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004221 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
4222 // This is a C++ constructor declaration.
4223 assert(DC->isRecord() &&
4224 "Constructors can only be declared in a member context");
4225
4226 R = CheckConstructorDeclarator(D, R, SC);
4227
4228 // Create the new declaration
Alexis Hunt5dafebc2011-05-06 01:42:00 +00004229 CXXConstructorDecl *NewCD = CXXConstructorDecl::Create(
4230 Context,
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004231 cast<CXXRecordDecl>(DC),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004232 D.getSourceRange().getBegin(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004233 NameInfo, R, TInfo,
4234 isExplicit, isInline,
Alexis Hunt58dad7d2011-05-06 00:11:07 +00004235 /*isImplicitlyDeclared=*/false);
Alexis Hunt5dafebc2011-05-06 01:42:00 +00004236
4237 NewFD = NewCD;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004238 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4239 // This is a C++ destructor declaration.
4240 if (DC->isRecord()) {
4241 R = CheckDestructorDeclarator(D, R, SC);
Sebastian Redl623ea822011-05-19 05:13:44 +00004242 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004243
Sebastian Redl623ea822011-05-19 05:13:44 +00004244 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004245 D.getSourceRange().getBegin(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004246 NameInfo, R, TInfo,
4247 isInline,
4248 /*isImplicitlyDeclared=*/false);
Sebastian Redl623ea822011-05-19 05:13:44 +00004249 NewFD = NewDD;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004250 isVirtualOkay = true;
Sebastian Redl623ea822011-05-19 05:13:44 +00004251
4252 // If the class is complete, then we now create the implicit exception
4253 // specification. If the class is incomplete or dependent, we can't do
4254 // it yet.
4255 if (getLangOptions().CPlusPlus0x && !Record->isDependentType() &&
4256 Record->getDefinition() && !Record->isBeingDefined() &&
4257 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
4258 AdjustDestructorExceptionSpec(Record, NewDD);
4259 }
4260
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004261 } else {
4262 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
4263
4264 // Create a FunctionDecl to satisfy the function definition parsing
4265 // code path.
Abramo Bagnaradff19302011-03-08 08:55:46 +00004266 NewFD = FunctionDecl::Create(Context, DC, D.getSourceRange().getBegin(),
4267 D.getIdentifierLoc(), Name, R, TInfo,
4268 SC, SCAsWritten, isInline,
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004269 /*hasPrototype=*/true);
4270 D.setInvalidType();
4271 }
4272 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
4273 if (!DC->isRecord()) {
4274 Diag(D.getIdentifierLoc(),
4275 diag::err_conv_function_not_member);
4276 return 0;
4277 }
4278
4279 CheckConversionDeclarator(D, R, SC);
4280 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004281 D.getSourceRange().getBegin(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004282 NameInfo, R, TInfo,
Douglas Gregorf2f08062011-03-08 17:10:18 +00004283 isInline, isExplicit,
4284 SourceLocation());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004285
4286 isVirtualOkay = true;
4287 } else if (DC->isRecord()) {
4288 // If the of the function is the same as the name of the record, then this
4289 // must be an invalid constructor that has a return type.
4290 // (The parser checks for a return type and makes the declarator a
4291 // constructor if it has no return type).
4292 // must have an invalid constructor that has a return type
4293 if (Name.getAsIdentifierInfo() &&
4294 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
4295 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
4296 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4297 << SourceRange(D.getIdentifierLoc());
4298 return 0;
4299 }
4300
4301 bool isStatic = SC == SC_Static;
Sebastian Redl37588092011-03-14 18:08:30 +00004302
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004303 // [class.free]p1:
4304 // Any allocation function for a class T is a static member
4305 // (even if not explicitly declared static).
4306 if (Name.getCXXOverloadedOperator() == OO_New ||
4307 Name.getCXXOverloadedOperator() == OO_Array_New)
4308 isStatic = true;
4309
4310 // [class.free]p6 Any deallocation function for a class X is a static member
4311 // (even if not explicitly declared static).
4312 if (Name.getCXXOverloadedOperator() == OO_Delete ||
4313 Name.getCXXOverloadedOperator() == OO_Array_Delete)
4314 isStatic = true;
Sebastian Redl37588092011-03-14 18:08:30 +00004315
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004316 // This is a C++ method declaration.
Alexis Hunt5dafebc2011-05-06 01:42:00 +00004317 CXXMethodDecl *NewMD = CXXMethodDecl::Create(
4318 Context, cast<CXXRecordDecl>(DC),
4319 D.getSourceRange().getBegin(),
4320 NameInfo, R, TInfo,
4321 isStatic, SCAsWritten, isInline,
4322 SourceLocation());
4323 NewFD = NewMD;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004324
4325 isVirtualOkay = !isStatic;
4326 } else {
4327 // Determine whether the function was written with a
4328 // prototype. This true when:
4329 // - we're in C++ (where every function has a prototype),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004330 NewFD = FunctionDecl::Create(Context, DC, D.getSourceRange().getBegin(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004331 NameInfo, R, TInfo, SC, SCAsWritten, isInline,
4332 true/*HasPrototype*/);
4333 }
Abramo Bagnaraa3088e62011-03-18 15:21:59 +00004334
4335 if (isFriend && !isInline && IsFunctionDefinition) {
4336 // C++ [class.friend]p5
4337 // A function can be defined in a friend declaration of a
4338 // class . . . . Such a function is implicitly inline.
4339 NewFD->setImplicitlyInline();
4340 }
4341
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004342 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004343 isExplicitSpecialization = false;
4344 isFunctionTemplateSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004345 if (D.isInvalidType())
4346 NewFD->setInvalidDecl();
4347
4348 // Set the lexical context. If the declarator has a C++
4349 // scope specifier, or is the object of a friend declaration, the
4350 // lexical context will be different from the semantic context.
4351 NewFD->setLexicalDeclContext(CurContext);
4352
4353 // Match up the template parameter lists with the scope specifier, then
4354 // determine whether we have a template or a template specialization.
4355 bool Invalid = false;
4356 if (TemplateParameterList *TemplateParams
Douglas Gregor93ded322011-03-04 22:45:55 +00004357 = MatchTemplateParametersToScopeSpecifier(
Douglas Gregord8d297c2009-07-21 23:53:31 +00004358 D.getDeclSpec().getSourceRange().getBegin(),
Douglas Gregor972fe532011-05-10 18:27:06 +00004359 D.getIdentifierLoc(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00004360 D.getCXXScopeSpec(),
John McCall2c2eb122010-10-16 06:59:13 +00004361 TemplateParamLists.get(),
4362 TemplateParamLists.size(),
4363 isFriend,
4364 isExplicitSpecialization,
4365 Invalid)) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00004366 if (TemplateParams->size() > 0) {
4367 // This is a function template
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00004368
Abramo Bagnara60804e12011-03-18 15:16:37 +00004369 // Check that we can declare a template here.
4370 if (CheckTemplateDeclScope(S, TemplateParams))
4371 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004372
Abramo Bagnara60804e12011-03-18 15:16:37 +00004373 // A destructor cannot be a template.
4374 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4375 Diag(NewFD->getLocation(), diag::err_destructor_template);
4376 return 0;
John McCall1f0479e2010-03-24 08:27:58 +00004377 }
4378
Abramo Bagnara60804e12011-03-18 15:16:37 +00004379 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
4380 NewFD->getLocation(),
4381 Name, TemplateParams,
4382 NewFD);
4383 FunctionTemplate->setLexicalDeclContext(CurContext);
4384 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
4385
4386 // For source fidelity, store the other template param lists.
4387 if (TemplateParamLists.size() > 1) {
4388 NewFD->setTemplateParameterListsInfo(Context,
4389 TemplateParamLists.size() - 1,
4390 TemplateParamLists.release());
4391 }
4392 } else {
4393 // This is a function template specialization.
4394 isFunctionTemplateSpecialization = true;
4395 // For source fidelity, store all the template param lists.
4396 NewFD->setTemplateParameterListsInfo(Context,
4397 TemplateParamLists.size(),
4398 TemplateParamLists.release());
4399
4400 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
4401 if (isFriend) {
4402 // We want to remove the "template<>", found here.
4403 SourceRange RemoveRange = TemplateParams->getSourceRange();
4404
4405 // If we remove the template<> and the name is not a
4406 // template-id, we're actually silently creating a problem:
4407 // the friend declaration will refer to an untemplated decl,
4408 // and clearly the user wants a template specialization. So
4409 // we need to insert '<>' after the name.
4410 SourceLocation InsertLoc;
4411 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
4412 InsertLoc = D.getName().getSourceRange().getEnd();
4413 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
4414 }
4415
4416 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
4417 << Name << RemoveRange
4418 << FixItHint::CreateRemoval(RemoveRange)
4419 << FixItHint::CreateInsertion(InsertLoc, "<>");
4420 }
4421 }
4422 }
4423 else {
4424 // All template param lists were matched against the scope specifier:
4425 // this is NOT (an explicit specialization of) a template.
4426 if (TemplateParamLists.size() > 0)
4427 // For source fidelity, store all the template param lists.
4428 NewFD->setTemplateParameterListsInfo(Context,
4429 TemplateParamLists.size(),
4430 TemplateParamLists.release());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004431 }
4432
4433 if (Invalid) {
4434 NewFD->setInvalidDecl();
4435 if (FunctionTemplate)
4436 FunctionTemplate->setInvalidDecl();
4437 }
4438
4439 // C++ [dcl.fct.spec]p5:
4440 // The virtual specifier shall only be used in declarations of
4441 // nonstatic class member functions that appear within a
4442 // member-specification of a class declaration; see 10.3.
4443 //
4444 if (isVirtual && !NewFD->isInvalidDecl()) {
4445 if (!isVirtualOkay) {
4446 Diag(D.getDeclSpec().getVirtualSpecLoc(),
4447 diag::err_virtual_non_function);
4448 } else if (!CurContext->isRecord()) {
4449 // 'virtual' was specified outside of the class.
Anders Carlssone9738992011-01-22 14:43:56 +00004450 Diag(D.getDeclSpec().getVirtualSpecLoc(),
4451 diag::err_virtual_out_of_class)
4452 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
4453 } else if (NewFD->getDescribedFunctionTemplate()) {
4454 // C++ [temp.mem]p3:
4455 // A member function template shall not be virtual.
4456 Diag(D.getDeclSpec().getVirtualSpecLoc(),
4457 diag::err_virtual_member_function_template)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004458 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
4459 } else {
4460 // Okay: Add virtual to the method.
4461 NewFD->setVirtualAsWritten(true);
John McCall816d75b2010-03-24 07:46:06 +00004462 }
Douglas Gregorc1da0f02009-06-24 00:23:40 +00004463 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00004464
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004465 // C++ [dcl.fct.spec]p3:
4466 // The inline specifier shall not appear on a block scope function declaration.
4467 if (isInline && !NewFD->isInvalidDecl()) {
4468 if (CurContext->isFunctionOrMethod()) {
4469 // 'inline' is not allowed on block scope function declaration.
4470 Diag(D.getDeclSpec().getInlineSpecLoc(),
4471 diag::err_inline_declaration_block_scope) << Name
4472 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
4473 }
4474 }
4475
4476 // C++ [dcl.fct.spec]p6:
4477 // The explicit specifier shall be used only in the declaration of a
4478 // constructor or conversion function within its class definition; see 12.3.1
4479 // and 12.3.2.
4480 if (isExplicit && !NewFD->isInvalidDecl()) {
4481 if (!CurContext->isRecord()) {
4482 // 'explicit' was specified outside of the class.
4483 Diag(D.getDeclSpec().getExplicitSpecLoc(),
4484 diag::err_explicit_out_of_class)
4485 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
4486 } else if (!isa<CXXConstructorDecl>(NewFD) &&
4487 !isa<CXXConversionDecl>(NewFD)) {
4488 // 'explicit' was specified on a function that wasn't a constructor
4489 // or conversion function.
4490 Diag(D.getDeclSpec().getExplicitSpecLoc(),
4491 diag::err_explicit_non_ctor_or_conv_function)
4492 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
4493 }
4494 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00004495
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004496 // Filter out previous declarations that don't match the scope.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004497 FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(),
Douglas Gregordb446112011-03-07 16:54:27 +00004498 isExplicitSpecialization ||
4499 isFunctionTemplateSpecialization);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004500
4501 if (isFriend) {
4502 // For now, claim that the objects have no previous declaration.
4503 if (FunctionTemplate) {
4504 FunctionTemplate->setObjectOfFriendDecl(false);
4505 FunctionTemplate->setAccess(AS_public);
4506 }
4507 NewFD->setObjectOfFriendDecl(false);
4508 NewFD->setAccess(AS_public);
4509 }
4510
John McCall357d0f32010-12-15 04:00:32 +00004511 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && IsFunctionDefinition) {
4512 // A method is implicitly inline if it's defined in its class
4513 // definition.
4514 NewFD->setImplicitlyInline();
4515 }
4516
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004517 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
4518 !CurContext->isRecord()) {
4519 // C++ [class.static]p1:
4520 // A data or function member of a class may be declared static
4521 // in a class definition, in which case it is a static member of
4522 // the class.
4523
4524 // Complain about the 'static' specifier if it's on an out-of-line
4525 // member function definition.
4526 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4527 diag::err_static_out_of_line)
4528 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4529 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00004530 }
4531
Zhongxing Xubece5d62009-01-16 01:13:29 +00004532 // Handle GNU asm-label extension (encoded as an attribute).
4533 if (Expr *E = (Expr*) D.getAsmLabel()) {
4534 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00004535 StringLiteral *SE = cast<StringLiteral>(E);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004536 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
4537 SE->getString()));
Zhongxing Xubece5d62009-01-16 01:13:29 +00004538 }
4539
Chris Lattner9af40c12009-04-25 06:12:16 +00004540 // Copy the parameter declarations from the declarator D to the function
4541 // declaration NewFD, if they are available. First scavenge them into Params.
4542 llvm::SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara6d810632010-12-14 22:11:44 +00004543 if (D.isFunctionDeclarator()) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004544 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xubece5d62009-01-16 01:13:29 +00004545
Zhongxing Xubece5d62009-01-16 01:13:29 +00004546 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
4547 // function that takes no arguments, not a function that takes a
4548 // single void argument.
4549 // We let through "const void" here because Sema::GetTypeForDeclarator
4550 // already checks for that case.
4551 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4552 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00004553 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
Chris Lattner9af40c12009-04-25 06:12:16 +00004554 // Empty arg list, don't push any params.
John McCall48871652010-08-21 09:40:31 +00004555 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[0].Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00004556
4557 // In C++, the empty parameter-type-list must be spelled "void"; a
4558 // typedef of void is not permitted.
4559 if (getLangOptions().CPlusPlus &&
Richard Smithdda56e42011-04-15 14:24:37 +00004560 Param->getType().getUnqualifiedType() != Context.VoidTy) {
4561 bool IsTypeAlias = false;
4562 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
4563 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00004564 else if (const TemplateSpecializationType *TST =
4565 Param->getType()->getAs<TemplateSpecializationType>())
4566 IsTypeAlias = TST->isTypeAlias();
Richard Smithdda56e42011-04-15 14:24:37 +00004567 Diag(Param->getLocation(), diag::err_param_typedef_of_void)
4568 << IsTypeAlias;
4569 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004570 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00004571 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +00004572 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00004573 assert(Param->getDeclContext() != NewFD && "Was set before ?");
4574 Param->setDeclContext(NewFD);
4575 Params.push_back(Param);
John McCallb7238602010-04-14 01:27:20 +00004576
4577 if (Param->isInvalidDecl())
4578 NewFD->setInvalidDecl();
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00004579 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004580 }
Mike Stump11289f42009-09-09 15:08:12 +00004581
John McCall9dd450b2009-09-21 23:43:11 +00004582 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner47c0d002009-04-25 06:03:53 +00004583 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xubece5d62009-01-16 01:13:29 +00004584 // following example, we'll need to synthesize (unnamed)
4585 // parameters for use in the declaration.
4586 //
4587 // @code
4588 // typedef void fn(int);
4589 // fn f;
4590 // @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004591
Chris Lattner47c0d002009-04-25 06:03:53 +00004592 // Synthesize a parameter for each argument type.
Chris Lattner47c0d002009-04-25 06:03:53 +00004593 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
4594 AE = FT->arg_type_end(); AI != AE; ++AI) {
John McCalla3ccba02010-06-04 11:21:44 +00004595 ParmVarDecl *Param =
4596 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
John McCall8fb0d9d2011-05-01 22:35:37 +00004597 Param->setScopeInfo(0, Params.size());
Chris Lattner47c0d002009-04-25 06:03:53 +00004598 Params.push_back(Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00004599 }
Chris Lattner49303b22009-04-25 18:38:18 +00004600 } else {
4601 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
4602 "Should not need args for typedef of non-prototype fn");
Zhongxing Xubece5d62009-01-16 01:13:29 +00004603 }
Chris Lattner9af40c12009-04-25 06:12:16 +00004604 // Finally, we know we have the right number of parameters, install them.
Douglas Gregord5058122010-02-11 01:19:42 +00004605 NewFD->setParams(Params.data(), Params.size());
Mike Stump11289f42009-09-09 15:08:12 +00004606
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004607 // Process the non-inheritable attributes on this declaration.
4608 ProcessDeclAttributes(S, NewFD, D,
4609 /*NonInheritable=*/true, /*Inheritable=*/false);
4610
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004611 if (!getLangOptions().CPlusPlus) {
4612 // Perform semantic checking on the function declaration.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00004613 bool isExplicitSpecialization=false;
4614 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization,
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004615 Redeclaration);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004616 assert((NewFD->isInvalidDecl() || !Redeclaration ||
4617 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
4618 "previous declaration set still overloaded");
4619 } else {
4620 // If the declarator is a template-id, translate the parser's template
4621 // argument list into our AST format.
4622 bool HasExplicitTemplateArgs = false;
4623 TemplateArgumentListInfo TemplateArgs;
4624 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4625 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4626 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4627 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
4628 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4629 TemplateId->getTemplateArgs(),
4630 TemplateId->NumArgs);
4631 translateTemplateArguments(TemplateArgsPtr,
4632 TemplateArgs);
4633 TemplateArgsPtr.release();
Douglas Gregor0e876e02009-09-25 23:53:26 +00004634
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004635 HasExplicitTemplateArgs = true;
Douglas Gregor0e876e02009-09-25 23:53:26 +00004636
Douglas Gregor522d5eb2011-06-06 15:22:55 +00004637 if (NewFD->isInvalidDecl()) {
4638 HasExplicitTemplateArgs = false;
4639 } else if (FunctionTemplate) {
Douglas Gregora5f6f9c2011-01-24 18:54:39 +00004640 // Function template with explicit template arguments.
4641 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
4642 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
4643
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004644 HasExplicitTemplateArgs = false;
4645 } else if (!isFunctionTemplateSpecialization &&
4646 !D.getDeclSpec().isFriendSpecified()) {
4647 // We have encountered something that the user meant to be a
4648 // specialization (because it has explicitly-specified template
4649 // arguments) but that was not introduced with a "template<>" (or had
4650 // too few of them).
4651 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
4652 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
4653 << FixItHint::CreateInsertion(
4654 D.getDeclSpec().getSourceRange().getBegin(),
4655 "template<> ");
4656 isFunctionTemplateSpecialization = true;
John McCallf7cfb222010-10-13 05:45:15 +00004657 } else {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004658 // "friend void foo<>(int);" is an implicit specialization decl.
4659 isFunctionTemplateSpecialization = true;
Francois Pichet6d76e6c2010-10-01 21:19:28 +00004660 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004661 } else if (isFriend && isFunctionTemplateSpecialization) {
4662 // This combination is only possible in a recovery case; the user
4663 // wrote something like:
4664 // template <> friend void foo(int);
4665 // which we're recovering from as if the user had written:
4666 // friend void foo<>(int);
4667 // Go ahead and fake up a template id.
4668 HasExplicitTemplateArgs = true;
4669 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
4670 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004671 }
John McCallf7cfb222010-10-13 05:45:15 +00004672
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004673 // If it's a friend (and only if it's a friend), it's possible
4674 // that either the specialized function type or the specialized
4675 // template is dependent, and therefore matching will fail. In
4676 // this case, don't check the specialization yet.
4677 if (isFunctionTemplateSpecialization && isFriend &&
4678 (NewFD->getType()->isDependentType() || DC->isDependentContext())) {
4679 assert(HasExplicitTemplateArgs &&
4680 "friend function specialization without template args");
4681 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
4682 Previous))
4683 NewFD->setInvalidDecl();
4684 } else if (isFunctionTemplateSpecialization) {
Douglas Gregor63fab342011-03-16 19:27:09 +00004685 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetb5037052011-06-03 13:59:45 +00004686 && !isFriend) {
Douglas Gregor63fab342011-03-16 19:27:09 +00004687 Diag(NewFD->getLocation(), diag::err_function_specialization_in_class)
4688 << NewFD->getDeclName();
4689 NewFD->setInvalidDecl();
4690 return 0;
4691 } else if (CheckFunctionTemplateSpecialization(NewFD,
4692 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
4693 Previous))
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004694 NewFD->setInvalidDecl();
Douglas Gregor781ba6e2011-05-21 18:53:30 +00004695
4696 // C++ [dcl.stc]p1:
4697 // A storage-class-specifier shall not be specified in an explicit
4698 // specialization (14.7.3)
4699 if (SC != SC_None) {
Douglas Gregor84265a02011-06-17 05:09:08 +00004700 if (SC != NewFD->getStorageClass())
4701 Diag(NewFD->getLocation(),
4702 diag::err_explicit_specialization_inconsistent_storage_class)
4703 << SC
4704 << FixItHint::CreateRemoval(
4705 D.getDeclSpec().getStorageClassSpecLoc());
4706
4707 else
4708 Diag(NewFD->getLocation(),
4709 diag::ext_explicit_specialization_storage_class)
4710 << FixItHint::CreateRemoval(
4711 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregor781ba6e2011-05-21 18:53:30 +00004712 }
4713
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004714 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
4715 if (CheckMemberSpecialization(NewFD, Previous))
4716 NewFD->setInvalidDecl();
4717 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004718
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004719 // Perform semantic checking on the function declaration.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004720 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization,
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004721 Redeclaration);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004722
4723 assert((NewFD->isInvalidDecl() || !Redeclaration ||
4724 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
4725 "previous declaration set still overloaded");
4726
4727 NamedDecl *PrincipalDecl = (FunctionTemplate
4728 ? cast<NamedDecl>(FunctionTemplate)
4729 : NewFD);
4730
4731 if (isFriend && Redeclaration) {
4732 AccessSpecifier Access = AS_public;
4733 if (!NewFD->isInvalidDecl())
4734 Access = NewFD->getPreviousDeclaration()->getAccess();
4735
4736 NewFD->setAccess(Access);
4737 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
4738
4739 PrincipalDecl->setObjectOfFriendDecl(true);
4740 }
4741
4742 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
4743 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4744 PrincipalDecl->setNonMemberOperator();
4745
4746 // If we have a function template, check the template parameter
4747 // list. This will check and merge default template arguments.
4748 if (FunctionTemplate) {
4749 FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration();
4750 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
4751 PrevTemplate? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregora99fb4c2011-02-04 04:20:44 +00004752 D.getDeclSpec().isFriendSpecified()
4753 ? (IsFunctionDefinition
4754 ? TPC_FriendFunctionTemplateDefinition
4755 : TPC_FriendFunctionTemplate)
4756 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor4d5c2972011-02-04 12:22:53 +00004757 DC && DC->isRecord() &&
4758 DC->isDependentContext())
Douglas Gregora99fb4c2011-02-04 04:20:44 +00004759 ? TPC_ClassTemplateMember
4760 : TPC_FunctionTemplate);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004761 }
4762
4763 if (NewFD->isInvalidDecl()) {
4764 // Ignore all the rest of this.
4765 } else if (!Redeclaration) {
4766 // Fake up an access specifier if it's supposed to be a class member.
4767 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
4768 NewFD->setAccess(AS_public);
4769
4770 // Qualified decls generally require a previous declaration.
4771 if (D.getCXXScopeSpec().isSet()) {
4772 // ...with the major exception of templated-scope or
4773 // dependent-scope friend declarations.
4774
4775 // TODO: we currently also suppress this check in dependent
4776 // contexts because (1) the parameter depth will be off when
4777 // matching friend templates and (2) we might actually be
4778 // selecting a friend based on a dependent factor. But there
4779 // are situations where these conditions don't apply and we
4780 // can actually do this check immediately.
4781 if (isFriend &&
Abramo Bagnara60804e12011-03-18 15:16:37 +00004782 (TemplateParamLists.size() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004783 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
4784 CurContext->isDependentContext())) {
4785 // ignore these
4786 } else {
4787 // The user tried to provide an out-of-line definition for a
4788 // function that is a member of a class or namespace, but there
4789 // was no such member function declared (C++ [class.mfct]p2,
4790 // C++ [namespace.memdef]p2). For example:
4791 //
4792 // class X {
4793 // void f() const;
4794 // };
4795 //
4796 // void X::f() { } // ill-formed
4797 //
4798 // Complain about this problem, and attempt to suggest close
4799 // matches (e.g., those that differ only in cv-qualifiers and
4800 // whether the parameter types are references).
4801 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
4802 << Name << DC << D.getCXXScopeSpec().getRange();
4803 NewFD->setInvalidDecl();
4804
4805 DiagnoseInvalidRedeclaration(*this, NewFD);
4806 }
4807
4808 // Unqualified local friend declarations are required to resolve
4809 // to something.
4810 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
4811 Diag(D.getIdentifierLoc(), diag::err_no_matching_local_friend);
4812 NewFD->setInvalidDecl();
4813 DiagnoseInvalidRedeclaration(*this, NewFD);
4814 }
4815
4816 } else if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
4817 !isFriend && !isFunctionTemplateSpecialization &&
Alexis Hunt5a7fa252011-05-12 06:15:49 +00004818 !isExplicitSpecialization) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004819 // An out-of-line member function declaration must also be a
4820 // definition (C++ [dcl.meaning]p1).
4821 // Note that this is not the case for explicit specializations of
4822 // function templates or member functions of class templates, per
4823 // C++ [temp.expl.spec]p2. We also allow these declarations as an extension
4824 // for compatibility with old SWIG code which likes to generate them.
4825 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
4826 << D.getCXXScopeSpec().getRange();
4827 }
4828 }
Alexis Hunt5a7fa252011-05-12 06:15:49 +00004829
4830
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004831 // Handle attributes. We need to have merged decls when handling attributes
4832 // (for example to check for conflicts, etc).
4833 // FIXME: This needs to happen before we merge declarations. Then,
4834 // let attribute merging cope with attribute conflicts.
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004835 ProcessDeclAttributes(S, NewFD, D,
4836 /*NonInheritable=*/false, /*Inheritable=*/true);
Ryan Flynne5dc8592009-07-25 22:29:44 +00004837
4838 // attributes declared post-definition are currently ignored
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004839 // FIXME: This should happen during attribute merging
John McCall1f82f242009-11-18 22:49:29 +00004840 if (Redeclaration && Previous.isSingleResult()) {
4841 const FunctionDecl *Def;
4842 FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004843 if (PrevFD && PrevFD->isDefined(Def) && D.hasAttributes()) {
Ryan Flynne5dc8592009-07-25 22:29:44 +00004844 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
4845 Diag(Def->getLocation(), diag::note_previous_definition);
4846 }
4847 }
4848
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004849 AddKnownFunctionAttributes(NewFD);
4850
Douglas Gregor72609052010-08-06 13:50:58 +00004851 if (NewFD->hasAttr<OverloadableAttr>() &&
4852 !NewFD->getType()->getAs<FunctionProtoType>()) {
4853 Diag(NewFD->getLocation(),
4854 diag::err_attribute_overloadable_no_prototype)
4855 << NewFD;
4856
4857 // Turn this into a variadic function with no parameters.
4858 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
John McCalldb40c7f2010-12-14 08:05:40 +00004859 FunctionProtoType::ExtProtoInfo EPI;
4860 EPI.Variadic = true;
4861 EPI.ExtInfo = FT->getExtInfo();
4862
4863 QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI);
Douglas Gregor72609052010-08-06 13:50:58 +00004864 NewFD->setType(R);
4865 }
4866
Eli Friedman570024a2010-08-05 06:57:20 +00004867 // If there's a #pragma GCC visibility in scope, and this isn't a class
4868 // member, set the visibility of this function.
4869 if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
4870 AddPushedVisibilityAttribute(NewFD);
4871
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004872 // If this is a locally-scoped extern C function, update the
4873 // map of such names.
Douglas Gregor16618f22009-09-12 00:17:51 +00004874 if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004875 && !NewFD->isInvalidDecl())
John McCall1f82f242009-11-18 22:49:29 +00004876 RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004877
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00004878 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraea947882011-03-08 16:41:52 +00004879 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00004880
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004881 if (getLangOptions().CPlusPlus) {
4882 if (FunctionTemplate) {
4883 if (NewFD->isInvalidDecl())
4884 FunctionTemplate->setInvalidDecl();
4885 return FunctionTemplate;
4886 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004887 }
Mike Stump11289f42009-09-09 15:08:12 +00004888
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004889 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004890
4891 if (getLangOptions().CUDA)
4892 if (IdentifierInfo *II = NewFD->getIdentifier())
4893 if (!NewFD->isInvalidDecl() &&
4894 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
4895 if (II->isStr("cudaConfigureCall")) {
4896 if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
4897 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
4898
4899 Context.setcudaConfigureCallDecl(NewFD);
4900 }
4901 }
4902
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004903 return NewFD;
4904}
4905
4906/// \brief Perform semantic checking of a new function declaration.
4907///
4908/// Performs semantic analysis of the new function declaration
4909/// NewFD. This routine performs all semantic checking that does not
4910/// require the actual declarator involved in the declaration, and is
4911/// used both for the declaration of functions as they are parsed
4912/// (called via ActOnDeclarator) and for the declaration of functions
4913/// that have been instantiated via C++ template instantiation (called
4914/// via InstantiateDecl).
4915///
Douglas Gregorcf915552009-10-13 16:30:37 +00004916/// \param IsExplicitSpecialiation whether this new function declaration is
4917/// an explicit specialization of the previous declaration.
4918///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004919/// This sets NewFD->isInvalidDecl() to true if there was an error.
John McCall84d87672009-12-10 09:41:52 +00004920void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall1f82f242009-11-18 22:49:29 +00004921 LookupResult &Previous,
Douglas Gregorcf915552009-10-13 16:30:37 +00004922 bool IsExplicitSpecialization,
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004923 bool &Redeclaration) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004924 // If NewFD is already known erroneous, don't do any of this checking.
John McCall12d53da2010-08-12 00:57:17 +00004925 if (NewFD->isInvalidDecl()) {
4926 // If this is a class member, mark the class invalid immediately.
4927 // This avoids some consistency errors later.
4928 if (isa<CXXMethodDecl>(NewFD))
4929 cast<CXXMethodDecl>(NewFD)->getParent()->setInvalidDecl();
4930
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004931 return;
John McCall12d53da2010-08-12 00:57:17 +00004932 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004933
Eli Friedman54135832009-05-16 12:15:55 +00004934 if (NewFD->getResultType()->isVariablyModifiedType()) {
4935 // Functions returning a variably modified type violate C99 6.7.5.2p2
4936 // because all functions have linkage.
4937 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
4938 return NewFD->setInvalidDecl();
4939 }
4940
Douglas Gregor16618f22009-09-12 00:17:51 +00004941 if (NewFD->isMain())
4942 CheckMain(NewFD);
John McCalld9baf6a2009-07-24 03:03:21 +00004943
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004944 // Check for a previous declaration of this name.
John McCall1f82f242009-11-18 22:49:29 +00004945 if (Previous.empty() && NewFD->isExternC()) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004946 // Since we did not find anything by this name and we're declaring
4947 // an extern "C" function, look for a non-visible extern "C"
4948 // declaration with the same name.
4949 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004950 = LocallyScopedExternalDecls.find(NewFD->getDeclName());
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004951 if (Pos != LocallyScopedExternalDecls.end())
John McCall1f82f242009-11-18 22:49:29 +00004952 Previous.addDecl(Pos->second);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004953 }
4954
Douglas Gregore62c0a42009-02-24 01:23:02 +00004955 // Merge or overload the declaration with an existing declaration of
4956 // the same name, if appropriate.
John McCall1f82f242009-11-18 22:49:29 +00004957 if (!Previous.empty()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00004958 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xubece5d62009-01-16 01:13:29 +00004959 // a declaration that requires merging. If it's an overload,
4960 // there's no more work to do here; we'll just add the new
4961 // function to the scope.
Douglas Gregor633b7372009-02-13 00:26:38 +00004962
John McCall1f82f242009-11-18 22:49:29 +00004963 NamedDecl *OldDecl = 0;
John McCalldaa3d6b2009-12-09 03:35:25 +00004964 if (!AllowOverloadingOfFunction(Previous, Context)) {
4965 Redeclaration = true;
4966 OldDecl = Previous.getFoundDecl();
4967 } else {
John McCalle9cccd82010-06-16 08:42:20 +00004968 switch (CheckOverload(S, NewFD, Previous, OldDecl,
4969 /*NewIsUsingDecl*/ false)) {
John McCalldaa3d6b2009-12-09 03:35:25 +00004970 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00004971 Redeclaration = true;
John McCalldaa3d6b2009-12-09 03:35:25 +00004972 break;
4973
4974 case Ovl_NonFunction:
4975 Redeclaration = true;
4976 break;
4977
4978 case Ovl_Overload:
4979 Redeclaration = false;
4980 break;
John McCall1f82f242009-11-18 22:49:29 +00004981 }
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004982
4983 if (!getLangOptions().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
4984 // If a function name is overloadable in C, then every function
4985 // with that name must be marked "overloadable".
4986 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
4987 << Redeclaration << NewFD;
4988 NamedDecl *OverloadedDecl = 0;
4989 if (Redeclaration)
4990 OverloadedDecl = OldDecl;
4991 else if (!Previous.empty())
4992 OverloadedDecl = Previous.getRepresentativeDecl();
4993 if (OverloadedDecl)
4994 Diag(OverloadedDecl->getLocation(),
4995 diag::note_attribute_overloadable_prev_overload);
4996 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
4997 Context));
4998 }
John McCall1f82f242009-11-18 22:49:29 +00004999 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005000
John McCall1f82f242009-11-18 22:49:29 +00005001 if (Redeclaration) {
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005002 // NewFD and OldDecl represent declarations that need to be
Mike Stump11289f42009-09-09 15:08:12 +00005003 // merged.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00005004 if (MergeFunctionDecl(NewFD, OldDecl))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005005 return NewFD->setInvalidDecl();
Zhongxing Xubece5d62009-01-16 01:13:29 +00005006
John McCall1f82f242009-11-18 22:49:29 +00005007 Previous.clear();
5008 Previous.addDecl(OldDecl);
5009
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005010 if (FunctionTemplateDecl *OldTemplateDecl
Douglas Gregorca027af2009-10-12 22:27:17 +00005011 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
Douglas Gregorcf915552009-10-13 16:30:37 +00005012 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
Douglas Gregorca027af2009-10-12 22:27:17 +00005013 FunctionTemplateDecl *NewTemplateDecl
5014 = NewFD->getDescribedFunctionTemplate();
5015 assert(NewTemplateDecl && "Template/non-template mismatch");
5016 if (CXXMethodDecl *Method
5017 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
5018 Method->setAccess(OldTemplateDecl->getAccess());
5019 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
5020 }
Douglas Gregorcf915552009-10-13 16:30:37 +00005021
5022 // If this is an explicit specialization of a member that is a function
5023 // template, mark it as a member specialization.
5024 if (IsExplicitSpecialization &&
5025 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
5026 NewTemplateDecl->setMemberSpecialization();
5027 assert(OldTemplateDecl->isMemberSpecialization());
5028 }
Douglas Gregorca027af2009-10-12 22:27:17 +00005029 } else {
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00005030 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
5031 NewFD->setAccess(OldDecl->getAccess());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005032 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00005033 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005034 }
Douglas Gregor8af63e42009-02-06 17:46:57 +00005035 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005036
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005037 // Semantic checking for this function declaration (in isolation).
5038 if (getLangOptions().CPlusPlus) {
5039 // C++-specific checks.
5040 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
5041 CheckConstructor(Constructor);
Anders Carlsson2a50e952009-11-15 22:49:34 +00005042 } else if (CXXDestructorDecl *Destructor =
5043 dyn_cast<CXXDestructorDecl>(NewFD)) {
5044 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005045 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson2a50e952009-11-15 22:49:34 +00005046
Douglas Gregor7454c562010-07-02 20:37:36 +00005047 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson2a50e952009-11-15 22:49:34 +00005048 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005049 if (!ClassType->isDependentType()) {
5050 DeclarationName Name
5051 = Context.DeclarationNames.getCXXDestructorName(
5052 Context.getCanonicalType(ClassType));
5053 if (NewFD->getDeclName() != Name) {
5054 Diag(NewFD->getLocation(), diag::err_destructor_name);
5055 return NewFD->setInvalidDecl();
5056 }
5057 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005058 } else if (CXXConversionDecl *Conversion
Douglas Gregor21920e372009-12-01 17:24:26 +00005059 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005060 ActOnConversionDeclarator(Conversion);
Douglas Gregor21920e372009-12-01 17:24:26 +00005061 }
5062
5063 // Find any virtual functions that this function overrides.
Douglas Gregor6be3de32009-12-01 17:35:23 +00005064 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
5065 if (!Method->isFunctionTemplateSpecialization() &&
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005066 !Method->getDescribedFunctionTemplate()) {
5067 if (AddOverriddenMethods(Method->getParent(), Method)) {
5068 // If the function was marked as "static", we have a problem.
5069 if (NewFD->getStorageClass() == SC_Static) {
5070 Diag(NewFD->getLocation(), diag::err_static_overrides_virtual)
5071 << NewFD->getDeclName();
5072 for (CXXMethodDecl::method_iterator
5073 Overridden = Method->begin_overridden_methods(),
5074 OverriddenEnd = Method->end_overridden_methods();
5075 Overridden != OverriddenEnd;
5076 ++Overridden) {
5077 Diag((*Overridden)->getLocation(),
5078 diag::note_overridden_virtual_function);
5079 }
5080 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005081 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005082 }
Douglas Gregor6be3de32009-12-01 17:35:23 +00005083 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005084
5085 // Extra checking for C++ overloaded operators (C++ [over.oper]).
5086 if (NewFD->isOverloadedOperator() &&
5087 CheckOverloadedOperatorDeclaration(NewFD))
5088 return NewFD->setInvalidDecl();
Alexis Huntc88db062010-01-13 09:01:02 +00005089
5090 // Extra checking for C++0x literal operators (C++0x [over.literal]).
5091 if (NewFD->getLiteralIdentifier() &&
5092 CheckLiteralOperatorDeclaration(NewFD))
5093 return NewFD->setInvalidDecl();
5094
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005095 // In C++, check default arguments now that we have merged decls. Unless
5096 // the lexical context is the class, because in this case this is done
5097 // during delayed parsing anyway.
5098 if (!CurContext->isRecord())
5099 CheckCXXDefaultArguments(NewFD);
Douglas Gregor9246b682010-12-21 19:47:46 +00005100
5101 // If this function declares a builtin function, check the type of this
5102 // declaration against the expected type for the builtin.
5103 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
5104 ASTContext::GetBuiltinTypeError Error;
5105 QualType T = Context.GetBuiltinType(BuiltinID, Error);
5106 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
5107 // The type of this function differs from the type of the builtin,
5108 // so forget about the builtin entirely.
5109 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
5110 }
5111 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005112 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005113}
5114
John McCalld9baf6a2009-07-24 03:03:21 +00005115void Sema::CheckMain(FunctionDecl* FD) {
John McCall02dee0a2009-07-25 04:36:53 +00005116 // C++ [basic.start.main]p3: A program that declares main to be inline
5117 // or static is ill-formed.
5118 // C99 6.7.4p4: In a hosted environment, the inline function specifier
5119 // shall not appear in a declaration of main.
5120 // static main is not an error under C99, but we should warn about it.
Douglas Gregor35b57532009-10-27 21:01:01 +00005121 bool isInline = FD->isInlineSpecified();
John McCall8e7d6562010-08-26 03:08:43 +00005122 bool isStatic = FD->getStorageClass() == SC_Static;
John McCall02dee0a2009-07-25 04:36:53 +00005123 if (isInline || isStatic) {
5124 unsigned diagID = diag::warn_unusual_main_decl;
5125 if (isInline || getLangOptions().CPlusPlus)
5126 diagID = diag::err_unusual_main_decl;
5127
5128 int which = isStatic + (isInline << 1) - 1;
5129 Diag(FD->getLocation(), diagID) << which;
5130 }
5131
5132 QualType T = FD->getType();
5133 assert(T->isFunctionType() && "function decl is not of function type");
John McCall9dd450b2009-09-21 23:43:11 +00005134 const FunctionType* FT = T->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00005135
John McCall02dee0a2009-07-25 04:36:53 +00005136 if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
Douglas Gregorf05c0952011-02-19 19:04:23 +00005137 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
John McCall02dee0a2009-07-25 04:36:53 +00005138 FD->setInvalidDecl(true);
5139 }
5140
5141 // Treat protoless main() as nullary.
5142 if (isa<FunctionNoProtoType>(FT)) return;
5143
5144 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
5145 unsigned nparams = FTP->getNumArgs();
5146 assert(FD->getNumParams() == nparams);
5147
John McCall0e21fcc2009-12-24 09:58:38 +00005148 bool HasExtraParameters = (nparams > 3);
5149
5150 // Darwin passes an undocumented fourth argument of type char**. If
5151 // other platforms start sprouting these, the logic below will start
5152 // getting shifty.
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00005153 if (nparams == 4 && Context.Target.getTriple().isOSDarwin())
John McCall0e21fcc2009-12-24 09:58:38 +00005154 HasExtraParameters = false;
5155
5156 if (HasExtraParameters) {
John McCall02dee0a2009-07-25 04:36:53 +00005157 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
5158 FD->setInvalidDecl(true);
5159 nparams = 3;
5160 }
5161
5162 // FIXME: a lot of the following diagnostics would be improved
5163 // if we had some location information about types.
5164
5165 QualType CharPP =
5166 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall0e21fcc2009-12-24 09:58:38 +00005167 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall02dee0a2009-07-25 04:36:53 +00005168
5169 for (unsigned i = 0; i < nparams; ++i) {
5170 QualType AT = FTP->getArgType(i);
5171
5172 bool mismatch = true;
5173
5174 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
5175 mismatch = false;
5176 else if (Expected[i] == CharPP) {
5177 // As an extension, the following forms are okay:
5178 // char const **
5179 // char const * const *
5180 // char * const *
5181
John McCall8ccfcb52009-09-24 19:53:00 +00005182 QualifierCollector qs;
John McCall02dee0a2009-07-25 04:36:53 +00005183 const PointerType* PT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005184 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
5185 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
John McCall02dee0a2009-07-25 04:36:53 +00005186 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
5187 qs.removeConst();
5188 mismatch = !qs.empty();
5189 }
5190 }
5191
5192 if (mismatch) {
5193 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
5194 // TODO: suggest replacing given type with expected type
5195 FD->setInvalidDecl(true);
5196 }
5197 }
5198
5199 if (nparams == 1 && !FD->isInvalidDecl()) {
5200 Diag(FD->getLocation(), diag::warn_main_one_arg);
5201 }
Douglas Gregorbff62032010-10-21 16:57:46 +00005202
5203 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
5204 Diag(FD->getLocation(), diag::err_main_template_decl);
5205 FD->setInvalidDecl();
5206 }
John McCalld9baf6a2009-07-24 03:03:21 +00005207}
5208
Eli Friedmand5a55bd2008-05-20 13:48:25 +00005209bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00005210 // FIXME: Need strict checking. In C89, we need to check for
5211 // any assignment, increment, decrement, function-calls, or
5212 // commas outside of a sizeof. In C99, it's the same list,
5213 // except that the aforementioned are allowed in unevaluated
5214 // expressions. Everything else falls under the
5215 // "may accept other forms of constant expressions" exception.
5216 // (We never end up here for C++, so the constant expression
5217 // rules there don't matter.)
John McCall8b0f4ff2010-08-02 21:13:48 +00005218 if (Init->isConstantInitializer(Context, false))
Eli Friedman7bfab362009-02-22 06:45:27 +00005219 return false;
Eli Friedman4f294cf2009-02-26 04:47:58 +00005220 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
5221 << Init->getSourceRange();
Eli Friedmand5a55bd2008-05-20 13:48:25 +00005222 return true;
Steve Naroff98f72032008-01-10 22:15:12 +00005223}
5224
Chandler Carruth33bf3e72011-03-27 09:46:56 +00005225namespace {
5226 // Visits an initialization expression to see if OrigDecl is evaluated in
5227 // its own initialization and throws a warning if it does.
5228 class SelfReferenceChecker
5229 : public EvaluatedExprVisitor<SelfReferenceChecker> {
5230 Sema &S;
5231 Decl *OrigDecl;
5232
5233 public:
5234 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
5235
5236 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
5237 S(S), OrigDecl(OrigDecl) { }
5238
5239 void VisitExpr(Expr *E) {
5240 if (isa<ObjCMessageExpr>(*E)) return;
5241 Inherited::VisitExpr(E);
5242 }
5243
5244 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
5245 CheckForSelfReference(E);
5246 Inherited::VisitImplicitCastExpr(E);
5247 }
5248
5249 void CheckForSelfReference(ImplicitCastExpr *E) {
5250 if (E->getCastKind() != CK_LValueToRValue) return;
5251 Expr* SubExpr = E->getSubExpr()->IgnoreParenImpCasts();
5252 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr);
5253 if (!DRE) return;
5254 Decl* ReferenceDecl = DRE->getDecl();
5255 if (OrigDecl != ReferenceDecl) return;
5256 LookupResult Result(S, DRE->getNameInfo(), Sema::LookupOrdinaryName,
5257 Sema::NotForRedeclaration);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005258 S.DiagRuntimeBehavior(SubExpr->getLocStart(), SubExpr,
5259 S.PDiag(diag::warn_uninit_self_reference_in_init)
5260 << Result.getLookupName()
5261 << OrigDecl->getLocation()
5262 << SubExpr->getSourceRange());
Chandler Carruth33bf3e72011-03-27 09:46:56 +00005263 }
5264 };
5265}
5266
Douglas Gregor5fb53972009-01-14 15:45:31 +00005267/// AddInitializerToDecl - Adds the initializer Init to the
5268/// declaration dcl. If DirectInit is true, this is C++ direct
5269/// initialization rather than copy initialization.
Richard Smith30482bc2011-02-20 03:19:35 +00005270void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
5271 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner8beb9de2007-10-19 20:10:30 +00005272 // If there is no declaration, there was an error parsing it. Just ignore
5273 // the initializer.
Richard Smith30482bc2011-02-20 03:19:35 +00005274 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner8beb9de2007-10-19 20:10:30 +00005275 return;
Mike Stump11289f42009-09-09 15:08:12 +00005276
Ted Kremenek37881932011-04-04 23:29:12 +00005277 // Check for self-references within variable initializers.
5278 if (VarDecl *vd = dyn_cast<VarDecl>(RealDecl)) {
5279 // Variables declared within a function/method body are handled
5280 // by a dataflow analysis.
5281 if (!vd->hasLocalStorage() && !vd->isStaticLocal())
5282 SelfReferenceChecker(*this, RealDecl).VisitExpr(Init);
5283 }
5284 else {
5285 SelfReferenceChecker(*this, RealDecl).VisitExpr(Init);
5286 }
Chandler Carruth33bf3e72011-03-27 09:46:56 +00005287
Douglas Gregor0c880302009-03-11 23:00:04 +00005288 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
5289 // With declarators parsed the way they are, the parser cannot
5290 // distinguish between a normal initializer and a pure-specifier.
5291 // Thus this grotesque test.
5292 IntegerLiteral *IL;
Douglas Gregor0c880302009-03-11 23:00:04 +00005293 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor21920e372009-12-01 17:24:26 +00005294 Context.getCanonicalType(IL->getType()) == Context.IntTy)
5295 CheckPureMethod(Method, Init->getSourceRange());
5296 else {
Douglas Gregor0c880302009-03-11 23:00:04 +00005297 Diag(Method->getLocation(), diag::err_member_function_initialization)
5298 << Method->getDeclName() << Init->getSourceRange();
5299 Method->setInvalidDecl();
5300 }
5301 return;
5302 }
5303
Steve Naroff437b4d82007-09-12 20:13:48 +00005304 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5305 if (!VDecl) {
Richard Smith4a4beec2011-06-12 11:43:46 +00005306 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
5307 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +00005308 RealDecl->setInvalidDecl();
5309 return;
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00005310 }
5311
Richard Smith30482bc2011-02-20 03:19:35 +00005312 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
5313 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith9647d3c2011-03-17 16:11:59 +00005314 TypeSourceInfo *DeducedType = 0;
5315 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith30482bc2011-02-20 03:19:35 +00005316 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
5317 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
5318 << Init->getSourceRange();
Richard Smith9647d3c2011-03-17 16:11:59 +00005319 if (!DeducedType) {
Richard Smith30482bc2011-02-20 03:19:35 +00005320 RealDecl->setInvalidDecl();
5321 return;
5322 }
Richard Smith9647d3c2011-03-17 16:11:59 +00005323 VDecl->setTypeSourceInfo(DeducedType);
5324 VDecl->setType(DeducedType->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00005325
John McCall31168b02011-06-15 23:02:42 +00005326 // In ARC, infer lifetime.
5327 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
5328 VDecl->setInvalidDecl();
5329
Richard Smith30482bc2011-02-20 03:19:35 +00005330 // If this is a redeclaration, check that the type we just deduced matches
5331 // the previously declared type.
5332 if (VarDecl *Old = VDecl->getPreviousDeclaration())
5333 MergeVarDeclTypes(VDecl, Old);
5334 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00005335
5336
Eli Friedmanc9827d12009-11-14 03:40:14 +00005337 // A definition must end up with a complete type, which means it must be
5338 // complete with the restriction that an array type might be completed by the
5339 // initializer; note that later code assumes this restriction.
5340 QualType BaseDeclType = VDecl->getType();
5341 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
5342 BaseDeclType = Array->getElementType();
5343 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
Eli Friedman337cd3a2009-04-13 21:28:54 +00005344 diag::err_typecheck_decl_incomplete_type)) {
5345 RealDecl->setInvalidDecl();
5346 return;
5347 }
5348
Douglas Gregorc99f1552009-12-03 18:33:45 +00005349 // The variable can not have an abstract class type.
5350 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5351 diag::err_abstract_type_in_decl,
5352 AbstractVariableType))
5353 VDecl->setInvalidDecl();
5354
Sebastian Redl5ca79842010-02-01 20:16:42 +00005355 const VarDecl *Def;
5356 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00005357 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor0760fa12009-03-10 23:43:53 +00005358 << VDecl->getDeclName();
5359 Diag(Def->getLocation(), diag::note_previous_definition);
5360 VDecl->setInvalidDecl();
5361 return;
5362 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00005363
Douglas Gregorf0f83692010-08-24 05:27:49 +00005364 const VarDecl* PrevInit = 0;
Douglas Gregor71f39c92010-12-16 01:31:22 +00005365 if (getLangOptions().CPlusPlus) {
5366 // C++ [class.static.data]p4
5367 // If a static data member is of const integral or const
5368 // enumeration type, its declaration in the class definition can
5369 // specify a constant-initializer which shall be an integral
5370 // constant expression (5.19). In that case, the member can appear
5371 // in integral constant expressions. The member shall still be
5372 // defined in a namespace scope if it is used in the program and the
5373 // namespace scope definition shall not contain an initializer.
5374 //
5375 // We already performed a redefinition check above, but for static
5376 // data members we also need to check whether there was an in-class
5377 // declaration with an initializer.
5378 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5379 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5380 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5381 return;
5382 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00005383
Douglas Gregor71f39c92010-12-16 01:31:22 +00005384 if (VDecl->hasLocalStorage())
5385 getCurFunction()->setHasBranchProtectedScope();
5386
5387 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
5388 VDecl->setInvalidDecl();
5389 return;
5390 }
5391 }
John McCalld4e1b762010-08-01 01:24:59 +00005392
Douglas Gregor85dabae2009-12-16 01:38:02 +00005393 // Capture the variable that is being initialized and the style of
5394 // initialization.
5395 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5396
5397 // FIXME: Poor source location information.
5398 InitializationKind Kind
5399 = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(),
5400 Init->getLocStart(),
5401 Init->getLocEnd())
5402 : InitializationKind::CreateCopy(VDecl->getLocation(),
5403 Init->getLocStart());
5404
Steve Naroff61091402007-09-12 14:07:44 +00005405 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +00005406 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +00005407 QualType DclT = VDecl->getType(), SavT = DclT;
John McCall1c9c3fd2010-10-15 04:57:14 +00005408 if (VDecl->isLocalVarDecl()) {
Daniel Dunbar0ca16602009-04-14 02:25:56 +00005409 if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
Steve Naroff437b4d82007-09-12 20:13:48 +00005410 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff08899ff2008-04-15 22:42:06 +00005411 VDecl->setInvalidDecl();
5412 } else if (!VDecl->isInvalidDecl()) {
Eli Friedman78275202009-12-19 08:11:05 +00005413 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
John McCalldadc5752010-08-24 06:29:42 +00005414 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00005415 MultiExprArg(*this, &Init, 1),
Eli Friedman463e5232009-12-22 02:10:53 +00005416 &DclT);
5417 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00005418 VDecl->setInvalidDecl();
Eli Friedman78275202009-12-19 08:11:05 +00005419 return;
5420 }
Mike Stump11289f42009-09-09 15:08:12 +00005421
Eli Friedman463e5232009-12-22 02:10:53 +00005422 Init = Result.takeAs<Expr>();
5423
Anders Carlsson41e08812008-08-22 05:00:02 +00005424 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmance982572009-02-20 01:34:21 +00005425 // Don't check invalid declarations to avoid emitting useless diagnostics.
5426 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
John McCall8e7d6562010-08-26 03:08:43 +00005427 if (VDecl->getStorageClass() == SC_Static) // C99 6.7.8p4.
Anders Carlsson41e08812008-08-22 05:00:02 +00005428 CheckForConstantInitializer(Init, DclT);
5429 }
Steve Naroff61091402007-09-12 14:07:44 +00005430 }
Mike Stump11289f42009-09-09 15:08:12 +00005431 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor0c880302009-03-11 23:00:04 +00005432 VDecl->getLexicalDeclContext()->isRecord()) {
5433 // This is an in-class initialization for a static data member, e.g.,
5434 //
5435 // struct S {
5436 // static const int value = 17;
5437 // };
5438
John McCalldb768922010-09-10 23:21:22 +00005439 // Try to perform the initialization regardless.
5440 if (!VDecl->isInvalidDecl()) {
5441 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
5442 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
5443 MultiExprArg(*this, &Init, 1),
5444 &DclT);
5445 if (Result.isInvalid()) {
5446 VDecl->setInvalidDecl();
5447 return;
5448 }
5449
5450 Init = Result.takeAs<Expr>();
5451 }
Douglas Gregor0c880302009-03-11 23:00:04 +00005452
5453 // C++ [class.mem]p4:
5454 // A member-declarator can contain a constant-initializer only
5455 // if it declares a static member (9.4) of const integral or
5456 // const enumeration type, see 9.4.2.
5457 QualType T = VDecl->getType();
John McCalldb768922010-09-10 23:21:22 +00005458
5459 // Do nothing on dependent types.
5460 if (T->isDependentType()) {
5461
5462 // Require constness.
5463 } else if (!T.isConstQualified()) {
5464 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
5465 << Init->getSourceRange();
Douglas Gregor0c880302009-03-11 23:00:04 +00005466 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00005467
5468 // We allow integer constant expressions in all cases.
5469 } else if (T->isIntegralOrEnumerationType()) {
Chris Lattner9925ec82011-06-14 05:46:29 +00005470 // Check whether the expression is a constant expression.
5471 SourceLocation Loc;
5472 if (Init->isValueDependent())
5473 ; // Nothing to check.
5474 else if (Init->isIntegerConstantExpr(Context, &Loc))
5475 ; // Ok, it's an ICE!
5476 else if (Init->isEvaluatable(Context)) {
5477 // If we can constant fold the initializer through heroics, accept it,
5478 // but report this as a use of an extension for -pedantic.
5479 Diag(Loc, diag::ext_in_class_initializer_non_constant)
5480 << Init->getSourceRange();
5481 } else {
5482 // Otherwise, this is some crazy unknown case. Report the issue at the
5483 // location provided by the isIntegerConstantExpr failed check.
5484 Diag(Loc, diag::err_in_class_initializer_non_constant)
5485 << Init->getSourceRange();
5486 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00005487 }
5488
5489 // We allow floating-point constants as an extension in C++03, and
5490 // C++0x has far more complicated rules that we don't really
5491 // implement fully.
5492 } else {
5493 bool Allowed = false;
5494 if (getLangOptions().CPlusPlus0x) {
5495 Allowed = T->isLiteralType();
5496 } else if (T->isFloatingType()) { // also permits complex, which is ok
5497 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
5498 << T << Init->getSourceRange();
5499 Allowed = true;
5500 }
5501
5502 if (!Allowed) {
5503 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
5504 << T << Init->getSourceRange();
5505 VDecl->setInvalidDecl();
5506
5507 // TODO: there are probably expressions that pass here that shouldn't.
5508 } else if (!Init->isValueDependent() &&
5509 !Init->isConstantInitializer(Context, false)) {
5510 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
5511 << Init->getSourceRange();
5512 VDecl->setInvalidDecl();
Douglas Gregor0c880302009-03-11 23:00:04 +00005513 }
5514 }
Steve Naroff08899ff2008-04-15 22:42:06 +00005515 } else if (VDecl->isFileVarDecl()) {
Douglas Gregord4e1fb52010-10-15 01:21:46 +00005516 if (VDecl->getStorageClassAsWritten() == SC_Extern &&
Douglas Gregorfceea362010-04-22 14:36:26 +00005517 (!getLangOptions().CPlusPlus ||
5518 !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
Steve Naroff437b4d82007-09-12 20:13:48 +00005519 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedman463e5232009-12-22 02:10:53 +00005520 if (!VDecl->isInvalidDecl()) {
5521 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
John McCalldadc5752010-08-24 06:29:42 +00005522 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00005523 MultiExprArg(*this, &Init, 1),
Eli Friedman463e5232009-12-22 02:10:53 +00005524 &DclT);
5525 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00005526 VDecl->setInvalidDecl();
Eli Friedman463e5232009-12-22 02:10:53 +00005527 return;
5528 }
5529
5530 Init = Result.takeAs<Expr>();
5531 }
Mike Stump11289f42009-09-09 15:08:12 +00005532
Anders Carlsson41e08812008-08-22 05:00:02 +00005533 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmance982572009-02-20 01:34:21 +00005534 // Don't check invalid declarations to avoid emitting useless diagnostics.
5535 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
Anders Carlsson41e08812008-08-22 05:00:02 +00005536 // C99 6.7.8p4. All file scoped initializers need to be constant.
5537 CheckForConstantInitializer(Init, DclT);
5538 }
Steve Naroff61091402007-09-12 14:07:44 +00005539 }
5540 // If the type changed, it means we had an incomplete type that was
Mike Stump11289f42009-09-09 15:08:12 +00005541 // completed by the initializer. For example:
Steve Naroff61091402007-09-12 14:07:44 +00005542 // int ary[] = { 1, 3, 5 };
5543 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb2ed9afd2007-11-29 19:09:19 +00005544 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff437b4d82007-09-12 20:13:48 +00005545 VDecl->setType(DclT);
Christopher Lamb2ed9afd2007-11-29 19:09:19 +00005546 Init->setType(DclT);
5547 }
Mike Stump11289f42009-09-09 15:08:12 +00005548
Chris Lattner88fdea82010-10-10 18:16:20 +00005549
5550 // If this variable is a local declaration with record type, make sure it
5551 // doesn't have a flexible member initialization. We only support this as a
5552 // global/static definition.
5553 if (VDecl->hasLocalStorage())
5554 if (const RecordType *RT = VDecl->getType()->getAs<RecordType>())
Douglas Gregor1f81ced2010-10-15 23:53:28 +00005555 if (RT->getDecl()->hasFlexibleArrayMember()) {
5556 // Check whether the initializer tries to initialize the flexible
5557 // array member itself to anything other than an empty initializer list.
5558 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5559 unsigned Index = std::distance(RT->getDecl()->field_begin(),
5560 RT->getDecl()->field_end()) - 1;
5561 if (Index < ILE->getNumInits() &&
5562 !(isa<InitListExpr>(ILE->getInit(Index)) &&
5563 cast<InitListExpr>(ILE->getInit(Index))->getNumInits() == 0)) {
5564 Diag(VDecl->getLocation(), diag::err_nonstatic_flexible_variable);
5565 VDecl->setInvalidDecl();
5566 }
5567 }
Chris Lattner88fdea82010-10-10 18:16:20 +00005568 }
5569
John McCallacf0ee52010-10-08 02:01:28 +00005570 // Check any implicit conversions within the expression.
5571 CheckImplicitConversions(Init, VDecl->getLocation());
John McCall31168b02011-06-15 23:02:42 +00005572
5573 if (!VDecl->isInvalidDecl())
5574 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
5575
John McCall5d413782010-12-06 08:20:24 +00005576 Init = MaybeCreateExprWithCleanups(Init);
Steve Naroff61091402007-09-12 14:07:44 +00005577 // Attach the initializer to the decl.
Douglas Gregord5058122010-02-11 01:19:42 +00005578 VDecl->setInit(Init);
Douglas Gregorbeecd582009-04-21 17:11:58 +00005579
John McCall8b7fd8f12011-01-19 11:48:09 +00005580 CheckCompleteVariableDeclaration(VDecl);
Steve Naroff61091402007-09-12 14:07:44 +00005581}
5582
John McCalleae5acb2010-03-31 02:13:20 +00005583/// ActOnInitializerError - Given that there was an error parsing an
5584/// initializer for the given declaration, try to return to some form
5585/// of sanity.
John McCall48871652010-08-21 09:40:31 +00005586void Sema::ActOnInitializerError(Decl *D) {
John McCalleae5acb2010-03-31 02:13:20 +00005587 // Our main concern here is re-establishing invariants like "a
5588 // variable's type is either dependent or complete".
John McCalleae5acb2010-03-31 02:13:20 +00005589 if (!D || D->isInvalidDecl()) return;
5590
5591 VarDecl *VD = dyn_cast<VarDecl>(D);
5592 if (!VD) return;
5593
Richard Smith30482bc2011-02-20 03:19:35 +00005594 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smithb2bc2e62011-02-21 20:05:19 +00005595 if (ParsingInitForAutoVars.count(D)) {
5596 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00005597 return;
5598 }
5599
John McCalleae5acb2010-03-31 02:13:20 +00005600 QualType Ty = VD->getType();
5601 if (Ty->isDependentType()) return;
5602
5603 // Require a complete type.
5604 if (RequireCompleteType(VD->getLocation(),
5605 Context.getBaseElementType(Ty),
5606 diag::err_typecheck_decl_incomplete_type)) {
5607 VD->setInvalidDecl();
5608 return;
5609 }
5610
5611 // Require an abstract type.
5612 if (RequireNonAbstractType(VD->getLocation(), Ty,
5613 diag::err_abstract_type_in_decl,
5614 AbstractVariableType)) {
5615 VD->setInvalidDecl();
5616 return;
5617 }
5618
5619 // Don't bother complaining about constructors or destructors,
5620 // though.
5621}
5622
John McCall48871652010-08-21 09:40:31 +00005623void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith30482bc2011-02-20 03:19:35 +00005624 bool TypeMayContainAuto) {
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00005625 // If there is no declaration, there was an error parsing it. Just ignore it.
5626 if (RealDecl == 0)
5627 return;
5628
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005629 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
5630 QualType Type = Var->getType();
Douglas Gregorbeecd582009-04-21 17:11:58 +00005631
Anders Carlssonae019932009-07-11 00:34:39 +00005632 // C++0x [dcl.spec.auto]p3
Richard Smith30482bc2011-02-20 03:19:35 +00005633 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlssonae019932009-07-11 00:34:39 +00005634 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
5635 << Var->getDeclName() << Type;
5636 Var->setInvalidDecl();
5637 return;
5638 }
Mike Stump11289f42009-09-09 15:08:12 +00005639
Douglas Gregore6565622010-02-09 07:26:29 +00005640 switch (Var->isThisDeclarationADefinition()) {
5641 case VarDecl::Definition:
5642 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
5643 break;
5644
5645 // We have an out-of-line definition of a static data member
5646 // that has an in-class initializer, so we type-check this like
5647 // a declaration.
5648 //
5649 // Fall through
5650
5651 case VarDecl::DeclarationOnly:
5652 // It's only a declaration.
5653
5654 // Block scope. C99 6.7p7: If an identifier for an object is
5655 // declared with no linkage (C99 6.2.2p6), the type for the
5656 // object shall be complete.
John McCall1c9c3fd2010-10-15 04:57:14 +00005657 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Douglas Gregore6565622010-02-09 07:26:29 +00005658 !Var->getLinkage() && !Var->isInvalidDecl() &&
5659 RequireCompleteType(Var->getLocation(), Type,
5660 diag::err_typecheck_decl_incomplete_type))
5661 Var->setInvalidDecl();
5662
5663 // Make sure that the type is not abstract.
5664 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
5665 RequireNonAbstractType(Var->getLocation(), Type,
5666 diag::err_abstract_type_in_decl,
5667 AbstractVariableType))
5668 Var->setInvalidDecl();
5669 return;
5670
5671 case VarDecl::TentativeDefinition:
5672 // File scope. C99 6.9.2p2: A declaration of an identifier for an
5673 // object that has file scope without an initializer, and without a
5674 // storage-class specifier or with the storage-class specifier "static",
5675 // constitutes a tentative definition. Note: A tentative definition with
5676 // external linkage is valid (C99 6.2.2p5).
5677 if (!Var->isInvalidDecl()) {
5678 if (const IncompleteArrayType *ArrayT
5679 = Context.getAsIncompleteArrayType(Type)) {
5680 if (RequireCompleteType(Var->getLocation(),
5681 ArrayT->getElementType(),
5682 diag::err_illegal_decl_array_incomplete_type))
5683 Var->setInvalidDecl();
John McCall8e7d6562010-08-26 03:08:43 +00005684 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregore6565622010-02-09 07:26:29 +00005685 // C99 6.9.2p3: If the declaration of an identifier for an object is
5686 // a tentative definition and has internal linkage (C99 6.2.2p3), the
5687 // declared type shall not be an incomplete type.
5688 // NOTE: code such as the following
5689 // static struct s;
5690 // struct s { int a; };
5691 // is accepted by gcc. Hence here we issue a warning instead of
5692 // an error and we do not invalidate the static declaration.
5693 // NOTE: to avoid multiple warnings, only check the first declaration.
5694 if (Var->getPreviousDeclaration() == 0)
5695 RequireCompleteType(Var->getLocation(), Type,
5696 diag::ext_typecheck_decl_incomplete_type);
5697 }
5698 }
5699
5700 // Record the tentative definition; we're done.
5701 if (!Var->isInvalidDecl())
5702 TentativeDefinitions.push_back(Var);
5703 return;
5704 }
5705
5706 // Provide a specific diagnostic for uninitialized variable
5707 // definitions with incomplete array type.
5708 if (Type->isIncompleteArrayType()) {
Sebastian Redl10600672009-11-05 19:47:47 +00005709 Diag(Var->getLocation(),
5710 diag::err_typecheck_incomplete_array_needs_initializer);
5711 Var->setInvalidDecl();
5712 return;
5713 }
5714
John McCalla755f0f2010-08-01 01:25:24 +00005715 // Provide a specific diagnostic for uninitialized variable
5716 // definitions with reference type.
5717 if (Type->isReferenceType()) {
5718 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
5719 << Var->getDeclName()
5720 << SourceRange(Var->getLocation(), Var->getLocation());
5721 Var->setInvalidDecl();
5722 return;
5723 }
Douglas Gregore6565622010-02-09 07:26:29 +00005724
5725 // Do not attempt to type-check the default initializer for a
5726 // variable with dependent type.
5727 if (Type->isDependentType())
Douglas Gregor86d142a2009-10-08 07:24:58 +00005728 return;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005729
Douglas Gregore6565622010-02-09 07:26:29 +00005730 if (Var->isInvalidDecl())
5731 return;
Douglas Gregorc99f1552009-12-03 18:33:45 +00005732
Douglas Gregore6565622010-02-09 07:26:29 +00005733 if (RequireCompleteType(Var->getLocation(),
5734 Context.getBaseElementType(Type),
5735 diag::err_typecheck_decl_incomplete_type)) {
5736 Var->setInvalidDecl();
5737 return;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00005738 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005739
Douglas Gregore6565622010-02-09 07:26:29 +00005740 // The variable can not have an abstract class type.
5741 if (RequireNonAbstractType(Var->getLocation(), Type,
5742 diag::err_abstract_type_in_decl,
5743 AbstractVariableType)) {
5744 Var->setInvalidDecl();
5745 return;
5746 }
5747
Douglas Gregor9574af62011-05-21 17:52:48 +00005748 // Check for jumps past the implicit initializer. C++0x
5749 // clarifies that this applies to a "variable with automatic
5750 // storage duration", not a "local variable".
5751 // C++0x [stmt.dcl]p3
5752 // A program that jumps from a point where a variable with automatic
5753 // storage duration is not in scope to a point where it is in scope is
5754 // ill-formed unless the variable has scalar type, class type with a
5755 // trivial default constructor and a trivial destructor, a cv-qualified
5756 // version of one of these types, or an array of one of the preceding
5757 // types and is declared without an initializer.
5758 if (getLangOptions().CPlusPlus && Var->hasLocalStorage()) {
5759 if (const RecordType *Record
5760 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Alexis Hunt466627c2011-05-11 22:50:12 +00005761 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor9574af62011-05-21 17:52:48 +00005762 if ((!getLangOptions().CPlusPlus0x && !CXXRecord->isPOD()) ||
5763 (getLangOptions().CPlusPlus0x &&
5764 (!CXXRecord->hasTrivialDefaultConstructor() ||
Douglas Gregor22ae6962011-05-27 21:28:00 +00005765 !CXXRecord->hasTrivialDestructor())))
Alexis Hunt466627c2011-05-11 22:50:12 +00005766 getCurFunction()->setHasBranchProtectedScope();
5767 }
Douglas Gregore6565622010-02-09 07:26:29 +00005768 }
Douglas Gregor9574af62011-05-21 17:52:48 +00005769
5770 // C++03 [dcl.init]p9:
5771 // If no initializer is specified for an object, and the
5772 // object is of (possibly cv-qualified) non-POD class type (or
5773 // array thereof), the object shall be default-initialized; if
5774 // the object is of const-qualified type, the underlying class
5775 // type shall have a user-declared default
5776 // constructor. Otherwise, if no initializer is specified for
5777 // a non- static object, the object and its subobjects, if
5778 // any, have an indeterminate initial value); if the object
5779 // or any of its subobjects are of const-qualified type, the
5780 // program is ill-formed.
5781 // C++0x [dcl.init]p11:
5782 // If no initializer is specified for an object, the object is
5783 // default-initialized; [...].
5784 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
5785 InitializationKind Kind
5786 = InitializationKind::CreateDefault(Var->getLocation());
5787
5788 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
5789 ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
5790 MultiExprArg(*this, 0, 0));
5791 if (Init.isInvalid())
5792 Var->setInvalidDecl();
5793 else if (Init.get())
5794 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Douglas Gregor589973b2010-03-08 02:45:10 +00005795
John McCall8b7fd8f12011-01-19 11:48:09 +00005796 CheckCompleteVariableDeclaration(Var);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005797 }
5798}
5799
Richard Smith02e85f32011-04-14 22:09:26 +00005800void Sema::ActOnCXXForRangeDecl(Decl *D) {
5801 VarDecl *VD = dyn_cast<VarDecl>(D);
5802 if (!VD) {
5803 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
5804 D->setInvalidDecl();
5805 return;
5806 }
5807
5808 VD->setCXXForRangeDecl(true);
5809
5810 // for-range-declaration cannot be given a storage class specifier.
5811 int Error = -1;
5812 switch (VD->getStorageClassAsWritten()) {
5813 case SC_None:
5814 break;
5815 case SC_Extern:
5816 Error = 0;
5817 break;
5818 case SC_Static:
5819 Error = 1;
5820 break;
5821 case SC_PrivateExtern:
5822 Error = 2;
5823 break;
5824 case SC_Auto:
5825 Error = 3;
5826 break;
5827 case SC_Register:
5828 Error = 4;
5829 break;
5830 }
5831 // FIXME: constexpr isn't allowed here.
5832 //if (DS.isConstexprSpecified())
5833 // Error = 5;
5834 if (Error != -1) {
5835 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
5836 << VD->getDeclName() << Error;
5837 D->setInvalidDecl();
5838 }
5839}
5840
John McCall8b7fd8f12011-01-19 11:48:09 +00005841void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
5842 if (var->isInvalidDecl()) return;
5843
John McCall31168b02011-06-15 23:02:42 +00005844 // In ARC, don't allow jumps past the implicit initialization of a
5845 // local retaining variable.
5846 if (getLangOptions().ObjCAutoRefCount &&
5847 var->hasLocalStorage()) {
5848 switch (var->getType().getObjCLifetime()) {
5849 case Qualifiers::OCL_None:
5850 case Qualifiers::OCL_ExplicitNone:
5851 case Qualifiers::OCL_Autoreleasing:
5852 break;
5853
5854 case Qualifiers::OCL_Weak:
5855 case Qualifiers::OCL_Strong:
5856 getCurFunction()->setHasBranchProtectedScope();
5857 break;
5858 }
5859 }
5860
John McCall8b7fd8f12011-01-19 11:48:09 +00005861 // All the following checks are C++ only.
5862 if (!getLangOptions().CPlusPlus) return;
5863
5864 QualType baseType = Context.getBaseElementType(var->getType());
5865 if (baseType->isDependentType()) return;
5866
5867 // __block variables might require us to capture a copy-initializer.
5868 if (var->hasAttr<BlocksAttr>()) {
5869 // It's currently invalid to ever have a __block variable with an
5870 // array type; should we diagnose that here?
5871
5872 // Regardless, we don't want to ignore array nesting when
5873 // constructing this copy.
5874 QualType type = var->getType();
5875
5876 if (type->isStructureOrClassType()) {
5877 SourceLocation poi = var->getLocation();
5878 Expr *varRef = new (Context) DeclRefExpr(var, type, VK_LValue, poi);
5879 ExprResult result =
5880 PerformCopyInitialization(
5881 InitializedEntity::InitializeBlock(poi, type, false),
5882 poi, Owned(varRef));
5883 if (!result.isInvalid()) {
5884 result = MaybeCreateExprWithCleanups(result);
5885 Expr *init = result.takeAs<Expr>();
5886 Context.setBlockVarCopyInits(var, init);
5887 }
5888 }
5889 }
5890
5891 // Check for global constructors.
5892 if (!var->getDeclContext()->isDependentContext() &&
5893 var->hasGlobalStorage() &&
5894 !var->isStaticLocal() &&
5895 var->getInit() &&
5896 !var->getInit()->isConstantInitializer(Context,
5897 baseType->isReferenceType()))
5898 Diag(var->getLocation(), diag::warn_global_constructor)
5899 << var->getInit()->getSourceRange();
5900
5901 // Require the destructor.
5902 if (const RecordType *recordType = baseType->getAs<RecordType>())
5903 FinalizeVarWithDestructor(var, recordType);
5904}
5905
Richard Smithb2bc2e62011-02-21 20:05:19 +00005906/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
5907/// any semantic actions necessary after any initializer has been attached.
5908void
5909Sema::FinalizeDeclaration(Decl *ThisDecl) {
5910 // Note that we are no longer parsing the initializer for this declaration.
5911 ParsingInitForAutoVars.erase(ThisDecl);
5912}
5913
John McCallba7bf592010-08-24 05:47:05 +00005914Sema::DeclGroupPtrTy
5915Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
5916 Decl **Group, unsigned NumDecls) {
Chris Lattner5bbb3c82009-03-29 16:50:03 +00005917 llvm::SmallVector<Decl*, 8> Decls;
Eli Friedman55b9ecb2009-05-29 01:49:24 +00005918
5919 if (DS.isTypeSpecOwned())
John McCallba7bf592010-08-24 05:47:05 +00005920 Decls.push_back(DS.getRepAsDecl());
Eli Friedman55b9ecb2009-05-29 01:49:24 +00005921
Richard Smith2abf6762011-02-23 00:37:57 +00005922 for (unsigned i = 0; i != NumDecls; ++i)
5923 if (Decl *D = Group[i])
5924 Decls.push_back(D);
5925
Chandler Carruth33bf3e72011-03-27 09:46:56 +00005926 return BuildDeclaratorGroup(Decls.data(), Decls.size(),
Richard Smith2abf6762011-02-23 00:37:57 +00005927 DS.getTypeSpecType() == DeclSpec::TST_auto);
5928}
5929
5930/// BuildDeclaratorGroup - convert a list of declarations into a declaration
5931/// group, performing any necessary semantic checking.
5932Sema::DeclGroupPtrTy
5933Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
5934 bool TypeMayContainAuto) {
Richard Smith30482bc2011-02-20 03:19:35 +00005935 // C++0x [dcl.spec.auto]p7:
5936 // If the type deduced for the template parameter U is not the same in each
5937 // deduction, the program is ill-formed.
5938 // FIXME: When initializer-list support is added, a distinction is needed
5939 // between the deduced type U and the deduced type which 'auto' stands for.
5940 // auto a = 0, b = { 1, 2, 3 };
5941 // is legal because the deduced type U is 'int' in both cases.
Richard Smith2abf6762011-02-23 00:37:57 +00005942 if (TypeMayContainAuto && NumDecls > 1) {
Richard Smith30482bc2011-02-20 03:19:35 +00005943 QualType Deduced;
5944 CanQualType DeducedCanon;
5945 VarDecl *DeducedDecl = 0;
5946 for (unsigned i = 0; i != NumDecls; ++i) {
5947 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
5948 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith2abf6762011-02-23 00:37:57 +00005949 // Don't reissue diagnostics when instantiating a template.
5950 if (AT && D->isInvalidDecl())
5951 break;
Richard Smith30482bc2011-02-20 03:19:35 +00005952 if (AT && AT->isDeduced()) {
5953 QualType U = AT->getDeducedType();
5954 CanQualType UCanon = Context.getCanonicalType(U);
5955 if (Deduced.isNull()) {
5956 Deduced = U;
5957 DeducedCanon = UCanon;
5958 DeducedDecl = D;
5959 } else if (DeducedCanon != UCanon) {
Richard Smith2abf6762011-02-23 00:37:57 +00005960 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
5961 diag::err_auto_different_deductions)
Richard Smith30482bc2011-02-20 03:19:35 +00005962 << Deduced << DeducedDecl->getDeclName()
5963 << U << D->getDeclName()
5964 << DeducedDecl->getInit()->getSourceRange()
5965 << D->getInit()->getSourceRange();
Richard Smith2abf6762011-02-23 00:37:57 +00005966 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00005967 break;
5968 }
5969 }
5970 }
5971 }
5972 }
5973
Richard Smith2abf6762011-02-23 00:37:57 +00005974 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls));
Chris Lattner776fac82007-06-09 00:53:06 +00005975}
Steve Naroff7e6f7c22007-08-28 03:03:08 +00005976
Chris Lattner5bbb3c82009-03-29 16:50:03 +00005977
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005978/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
5979/// to introduce parameters into function prototype scope.
John McCall48871652010-08-21 09:40:31 +00005980Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattnercf31de32008-06-26 06:49:43 +00005981 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorad590502008-12-15 23:53:10 +00005982
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005983 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
John McCall8e7d6562010-08-26 03:08:43 +00005984 VarDecl::StorageClass StorageClass = SC_None;
5985 VarDecl::StorageClass StorageClassAsWritten = SC_None;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00005986 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCall8e7d6562010-08-26 03:08:43 +00005987 StorageClass = SC_Register;
5988 StorageClassAsWritten = SC_Register;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00005989 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005990 Diag(DS.getStorageClassSpecLoc(),
5991 diag::err_invalid_storage_class_in_func_decl);
Chris Lattnercf31de32008-06-26 06:49:43 +00005992 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005993 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005994
5995 if (D.getDeclSpec().isThreadSpecified())
5996 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
5997
Eli Friedman574c7452009-04-07 19:37:57 +00005998 DiagnoseFunctionSpecifiers(D);
5999
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00006000 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00006001 QualType parmDeclType = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00006002
Douglas Gregor27b4c162010-12-23 22:44:42 +00006003 if (getLangOptions().CPlusPlus) {
6004 // Check that there are no default arguments inside the type of this
6005 // parameter.
6006 CheckExtraCXXDefaultArguments(D);
Douglas Gregor27b4c162010-12-23 22:44:42 +00006007
6008 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
6009 if (D.getCXXScopeSpec().isSet()) {
6010 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
6011 << D.getCXXScopeSpec().getRange();
6012 D.getCXXScopeSpec().clear();
6013 }
Douglas Gregord6ab8742009-05-28 23:31:59 +00006014 }
6015
Alexis Hunta56cbcc2010-11-03 01:07:06 +00006016 // Ensure we have a valid name
6017 IdentifierInfo *II = 0;
6018 if (D.hasName()) {
6019 II = D.getIdentifier();
6020 if (!II) {
6021 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
6022 << GetNameForDeclarator(D).getName().getAsString();
6023 D.setInvalidType(true);
6024 }
6025 }
6026
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00006027 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnerd9773512009-01-21 02:38:50 +00006028 if (II) {
John McCall84f02672010-03-18 06:42:38 +00006029 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
6030 ForRedeclaration);
6031 LookupName(R, S);
6032 if (R.isSingleResult()) {
6033 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnerd9773512009-01-21 02:38:50 +00006034 if (PrevDecl->isTemplateParameter()) {
6035 // Maybe we will complain about the shadowed template parameter.
6036 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
6037 // Just pretend that we didn't see the previous declaration.
6038 PrevDecl = 0;
John McCall48871652010-08-21 09:40:31 +00006039 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerd9773512009-01-21 02:38:50 +00006040 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00006041 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006042
Chris Lattnerd9773512009-01-21 02:38:50 +00006043 // Recover by removing the name
6044 II = 0;
6045 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00006046 D.setInvalidType(true);
Chris Lattnerd9773512009-01-21 02:38:50 +00006047 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006048 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00006049 }
Steve Naroff773df5c2007-08-07 22:44:21 +00006050
John McCallf7b2fb52010-01-22 00:28:27 +00006051 // Temporarily put parameter variables in the translation unit, not
6052 // the enclosing context. This prevents them from accidentally
6053 // looking like class members in C++.
Douglas Gregor940bca72010-04-12 07:48:19 +00006054 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00006055 D.getSourceRange().getBegin(),
6056 D.getIdentifierLoc(), II,
6057 parmDeclType, TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00006058 StorageClass, StorageClassAsWritten);
Mike Stump11289f42009-09-09 15:08:12 +00006059
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006060 if (D.isInvalidType())
John McCall8fb0d9d2011-05-01 22:35:37 +00006061 New->setInvalidDecl();
6062
6063 assert(S->isFunctionPrototypeScope());
6064 assert(S->getFunctionPrototypeDepth() >= 1);
6065 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
6066 S->getNextFunctionPrototypeIndex());
Douglas Gregor940bca72010-04-12 07:48:19 +00006067
Douglas Gregor91f84212008-12-11 16:49:14 +00006068 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00006069 S->AddDecl(New);
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00006070 if (II)
Douglas Gregor91f84212008-12-11 16:49:14 +00006071 IdResolver.AddDecl(New);
Nate Begemand8c41562008-02-17 21:20:31 +00006072
Douglas Gregor758a8692009-06-17 21:51:59 +00006073 ProcessDeclAttributes(S, New, D);
Mike Stumpe9efa802009-04-30 00:19:40 +00006074
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006075 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00006076 Diag(New->getLocation(), diag::err_block_on_nonlocal);
6077 }
John McCall48871652010-08-21 09:40:31 +00006078 return New;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00006079}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +00006080
John McCalla3ccba02010-06-04 11:21:44 +00006081/// \brief Synthesizes a variable for a parameter arising from a
6082/// typedef.
6083ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
6084 SourceLocation Loc,
6085 QualType T) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00006086 /* FIXME: setting StartLoc == Loc.
6087 Would it be worth to modify callers so as to provide proper source
6088 location for the unnamed parameters, embedding the parameter's type? */
6089 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCalla3ccba02010-06-04 11:21:44 +00006090 T, Context.getTrivialTypeSourceInfo(T, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00006091 SC_None, SC_None, 0);
John McCalla3ccba02010-06-04 11:21:44 +00006092 Param->setImplicit();
6093 return Param;
6094}
6095
John McCallc5990642010-08-24 09:05:15 +00006096void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
6097 ParmVarDecl * const *ParamEnd) {
John McCallc5990642010-08-24 09:05:15 +00006098 // Don't diagnose unused-parameter errors in template instantiations; we
6099 // will already have done so in the template itself.
6100 if (!ActiveTemplateInstantiations.empty())
6101 return;
6102
6103 for (; Param != ParamEnd; ++Param) {
6104 if (!(*Param)->isUsed() && (*Param)->getDeclName() &&
6105 !(*Param)->hasAttr<UnusedAttr>()) {
6106 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
6107 << (*Param)->getDeclName();
6108 }
6109 }
6110}
6111
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006112void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
6113 ParmVarDecl * const *ParamEnd,
6114 QualType ReturnTy,
6115 NamedDecl *D) {
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00006116 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006117 return;
6118
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00006119 // Warn if the return value is pass-by-value and larger than the specified
6120 // threshold.
John McCall31168b02011-06-15 23:02:42 +00006121 if (ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006122 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00006123 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006124 Diag(D->getLocation(), diag::warn_return_value_size)
6125 << D->getDeclName() << Size;
6126 }
6127
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00006128 // Warn if any parameter is pass-by-value and larger than the specified
6129 // threshold.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006130 for (; Param != ParamEnd; ++Param) {
6131 QualType T = (*Param)->getType();
John McCall31168b02011-06-15 23:02:42 +00006132 if (!T.isPODType(Context))
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006133 continue;
6134 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00006135 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006136 Diag((*Param)->getLocation(), diag::warn_parameter_size)
6137 << (*Param)->getDeclName() << Size;
6138 }
6139}
6140
Abramo Bagnaradff19302011-03-08 08:55:46 +00006141ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
6142 SourceLocation NameLoc, IdentifierInfo *Name,
6143 QualType T, TypeSourceInfo *TSInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00006144 VarDecl::StorageClass StorageClass,
6145 VarDecl::StorageClass StorageClassAsWritten) {
John McCall31168b02011-06-15 23:02:42 +00006146 // In ARC, infer a lifetime qualifier for appropriate parameter types.
6147 if (getLangOptions().ObjCAutoRefCount &&
6148 T.getObjCLifetime() == Qualifiers::OCL_None &&
6149 T->isObjCLifetimeType()) {
6150
6151 Qualifiers::ObjCLifetime lifetime;
6152
6153 // Special cases for arrays:
6154 // - if it's const, use __unsafe_unretained
6155 // - otherwise, it's an error
6156 if (T->isArrayType()) {
6157 if (!T.isConstQualified()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00006158 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
John McCall31168b02011-06-15 23:02:42 +00006159 << TSInfo->getTypeLoc().getSourceRange();
6160 }
6161 lifetime = Qualifiers::OCL_ExplicitNone;
6162 } else {
6163 lifetime = T->getObjCARCImplicitLifetime();
6164 }
6165 T = Context.getLifetimeQualifiedType(T, lifetime);
6166 }
6167
Abramo Bagnaradff19302011-03-08 08:55:46 +00006168 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor84280642011-07-12 04:42:08 +00006169 Context.getAdjustedParameterType(T),
6170 TSInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00006171 StorageClass, StorageClassAsWritten,
6172 0);
Douglas Gregor940bca72010-04-12 07:48:19 +00006173
6174 // Parameters can not be abstract class types.
6175 // For record types, this is done by the AbstractClassUsageDiagnoser once
6176 // the class has been completely parsed.
6177 if (!CurContext->isRecord() &&
6178 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
6179 AbstractParamType))
6180 New->setInvalidDecl();
6181
6182 // Parameter declarators cannot be interface types. All ObjC objects are
6183 // passed by reference.
John McCall8b07ec22010-05-15 11:32:37 +00006184 if (T->isObjCObjectType()) {
Douglas Gregor940bca72010-04-12 07:48:19 +00006185 Diag(NameLoc,
6186 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
6187 New->setInvalidDecl();
6188 }
6189
6190 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
6191 // duration shall not be qualified by an address-space qualifier."
6192 // Since all parameters have automatic store duration, they can not have
6193 // an address space.
6194 if (T.getAddressSpace() != 0) {
6195 Diag(NameLoc, diag::err_arg_with_address_space);
6196 New->setInvalidDecl();
6197 }
6198
6199 return New;
6200}
6201
Douglas Gregor170512f2009-04-01 23:51:29 +00006202void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
6203 SourceLocation LocAfterDecls) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006204 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006205
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00006206 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
6207 // for a K&R function.
6208 if (!FTI.hasPrototype) {
Douglas Gregor862ffb12009-04-02 03:14:12 +00006209 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
6210 --i;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006211 if (FTI.ArgInfo[i].Param == 0) {
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00006212 llvm::SmallString<256> Code;
6213 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar07d07852009-10-18 21:17:35 +00006214 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00006215 << ";\n";
Chris Lattner4bd8dd82008-11-19 08:23:25 +00006216 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregor170512f2009-04-01 23:51:29 +00006217 << FTI.ArgInfo[i].Ident
Douglas Gregora771f462010-03-31 17:46:05 +00006218 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregor170512f2009-04-01 23:51:29 +00006219
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00006220 // Implicitly declare the argument as type 'int' for lack of a better
6221 // type.
John McCall084e83d2011-03-24 11:26:52 +00006222 AttributeFactory attrs;
6223 DeclSpec DS(attrs);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006224 const char* PrevSpec; // unused
John McCall49bfce42009-08-03 20:12:06 +00006225 unsigned DiagID; // unused
Mike Stump11289f42009-09-09 15:08:12 +00006226 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCall49bfce42009-08-03 20:12:06 +00006227 PrevSpec, DiagID);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006228 Declarator ParamD(DS, Declarator::KNRTypeListContext);
6229 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregor9aa89042009-01-23 16:23:13 +00006230 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00006231 }
6232 }
Mike Stump11289f42009-09-09 15:08:12 +00006233 }
Douglas Gregor9aa89042009-01-23 16:23:13 +00006234}
6235
John McCall48871652010-08-21 09:40:31 +00006236Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
6237 Declarator &D) {
Douglas Gregor9aa89042009-01-23 16:23:13 +00006238 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006239 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregorad590502008-12-15 23:53:10 +00006240 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +00006241
John McCall48871652010-08-21 09:40:31 +00006242 Decl *DP = HandleDeclarator(ParentScope, D,
6243 MultiTemplateParamsArg(*this),
6244 /*IsFunctionDefinition=*/true);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00006245 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006246}
6247
Anders Carlsson31c7e882009-12-09 03:30:09 +00006248static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
6249 // Don't warn about invalid declarations.
6250 if (FD->isInvalidDecl())
6251 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00006252
Anders Carlsson31c7e882009-12-09 03:30:09 +00006253 // Or declarations that aren't global.
6254 if (!FD->isGlobal())
6255 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00006256
Anders Carlsson31c7e882009-12-09 03:30:09 +00006257 // Don't warn about C++ member functions.
6258 if (isa<CXXMethodDecl>(FD))
6259 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00006260
Anders Carlsson31c7e882009-12-09 03:30:09 +00006261 // Don't warn about 'main'.
6262 if (FD->isMain())
6263 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00006264
Anders Carlsson31c7e882009-12-09 03:30:09 +00006265 // Don't warn about inline functions.
John McCall30cd20a2011-03-22 07:16:37 +00006266 if (FD->isInlined())
Anders Carlsson31c7e882009-12-09 03:30:09 +00006267 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00006268
6269 // Don't warn about function templates.
6270 if (FD->getDescribedFunctionTemplate())
6271 return false;
6272
6273 // Don't warn about function template specializations.
6274 if (FD->isFunctionTemplateSpecialization())
6275 return false;
6276
Anders Carlsson31c7e882009-12-09 03:30:09 +00006277 bool MissingPrototype = true;
6278 for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
6279 Prev; Prev = Prev->getPreviousDeclaration()) {
6280 // Ignore any declarations that occur in function or method
6281 // scope, because they aren't visible from the header.
6282 if (Prev->getDeclContext()->isFunctionOrMethod())
6283 continue;
6284
6285 MissingPrototype = !Prev->getType()->isFunctionProtoType();
6286 break;
6287 }
6288
6289 return MissingPrototype;
6290}
6291
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00006292void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) {
6293 // Don't complain if we're in GNU89 mode and the previous definition
6294 // was an extern inline function.
6295 const FunctionDecl *Definition;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00006296 if (FD->isDefined(Definition) &&
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00006297 !canRedefineFunction(Definition, getLangOptions())) {
6298 if (getLangOptions().GNUMode && Definition->isInlineSpecified() &&
6299 Definition->getStorageClass() == SC_Extern)
6300 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
6301 << FD->getDeclName() << getLangOptions().CPlusPlus;
6302 else
6303 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
6304 Diag(Definition->getLocation(), diag::note_previous_definition);
6305 }
6306}
6307
John McCall48871652010-08-21 09:40:31 +00006308Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson561f7932009-10-29 15:46:07 +00006309 // Clear the last template instantiation error context.
6310 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
6311
Douglas Gregor17a7c122009-06-24 00:54:41 +00006312 if (!D)
6313 return D;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00006314 FunctionDecl *FD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00006315
John McCall48871652010-08-21 09:40:31 +00006316 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregorc45a40a2009-08-22 00:34:47 +00006317 FD = FunTmpl->getTemplatedDecl();
6318 else
John McCall48871652010-08-21 09:40:31 +00006319 FD = cast<FunctionDecl>(D);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00006320
Douglas Gregor9a28e842010-03-01 23:15:13 +00006321 // Enter a new function scope
6322 PushFunctionScope();
Mike Stump11289f42009-09-09 15:08:12 +00006323
Douglas Gregorcad304ba2008-10-29 15:10:40 +00006324 // See if this is a redefinition.
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00006325 if (!FD->isLateTemplateParsed())
6326 CheckForFunctionRedefinition(FD);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00006327
Douglas Gregor75a45ba2009-02-16 17:45:42 +00006328 // Builtin functions cannot be defined.
Douglas Gregor15fc9562009-09-12 00:22:50 +00006329 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor7a0febe2009-02-17 16:03:01 +00006330 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00006331 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor7a0febe2009-02-17 16:03:01 +00006332 FD->setInvalidDecl();
6333 }
Douglas Gregor75a45ba2009-02-16 17:45:42 +00006334 }
6335
Eli Friedman9ad72442009-03-04 07:30:59 +00006336 // The return type of a function definition must be complete
Douglas Gregorac1fb652009-03-24 19:52:54 +00006337 // (C99 6.9.1p3, C++ [dcl.fct]p6).
6338 QualType ResultType = FD->getResultType();
6339 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner0f94c5a2009-04-29 05:12:23 +00006340 !FD->isInvalidDecl() &&
Douglas Gregorac1fb652009-03-24 19:52:54 +00006341 RequireCompleteType(FD->getLocation(), ResultType,
6342 diag::err_func_def_incomplete_result))
Eli Friedman9ad72442009-03-04 07:30:59 +00006343 FD->setInvalidDecl();
Eli Friedman9ad72442009-03-04 07:30:59 +00006344
Douglas Gregorf1b876d2009-03-31 16:35:03 +00006345 // GNU warning -Wmissing-prototypes:
6346 // Warn if a global function is defined without a previous
6347 // prototype declaration. This warning is issued even if the
6348 // definition itself provides a prototype. The aim is to detect
6349 // global functions that fail to be declared in header files.
Anders Carlsson31c7e882009-12-09 03:30:09 +00006350 if (ShouldWarnAboutMissingPrototype(FD))
6351 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Douglas Gregorf1b876d2009-03-31 16:35:03 +00006352
Douglas Gregor67da0d92009-05-15 17:59:04 +00006353 if (FnBodyScope)
6354 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00006355
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006356 // Check the validity of our function parameters
Douglas Gregorb524d902010-11-01 18:37:59 +00006357 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
6358 /*CheckParameterNames=*/true);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006359
6360 // Introduce our parameters into the function scope
6361 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
6362 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc72e6452009-01-09 18:51:29 +00006363 Param->setOwningFunction(FD);
6364
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006365 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00006366 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00006367 CheckShadow(FnBodyScope, Param);
John McCalldf8b37c2010-03-22 09:20:08 +00006368
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00006369 PushOnScopeChains(Param, FnBodyScope);
John McCalldf8b37c2010-03-22 09:20:08 +00006370 }
Chris Lattnerf61c8a82007-01-21 19:04:43 +00006371 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006372
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00006373 // Checking attributes of current function definition
6374 // dllimport attribute.
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006375 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
6376 if (DA && (!FD->getAttr<DLLExportAttr>())) {
6377 // dllimport attribute cannot be directly applied to definition.
Francois Pichet3096d202011-03-29 10:39:17 +00006378 // Microsoft accepts dllimport for functions defined within class scope.
6379 if (!DA->isInherited() &&
6380 !(LangOpts.Microsoft && FD->getLexicalDeclContext()->isRecord())) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00006381 Diag(FD->getLocation(),
6382 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
6383 << "dllimport";
6384 FD->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +00006385 return FD;
Ted Kremeneka3cfc4d2010-02-21 05:12:53 +00006386 }
6387
6388 // Visual C++ appears to not think this is an issue, so only issue
6389 // a warning when Microsoft extensions are disabled.
6390 if (!LangOpts.Microsoft) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00006391 // If a symbol previously declared dllimport is later defined, the
6392 // attribute is ignored in subsequent references, and a warning is
6393 // emitted.
6394 Diag(FD->getLocation(),
6395 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Daniel Dunbar56df9772010-08-17 22:39:59 +00006396 << FD->getName() << "dllimport";
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00006397 }
6398 }
John McCall48871652010-08-21 09:40:31 +00006399 return FD;
Chris Lattnere168f762006-11-10 05:29:30 +00006400}
6401
Douglas Gregor6fd1b182010-05-15 06:01:05 +00006402/// \brief Given the set of return statements within a function body,
6403/// compute the variables that are subject to the named return value
6404/// optimization.
6405///
6406/// Each of the variables that is subject to the named return value
6407/// optimization will be marked as NRVO variables in the AST, and any
6408/// return statement that has a marked NRVO variable as its NRVO candidate can
6409/// use the named return value optimization.
6410///
6411/// This function applies a very simplistic algorithm for NRVO: if every return
6412/// statement in the function has the same NRVO candidate, that candidate is
6413/// the NRVO variable.
6414///
6415/// FIXME: Employ a smarter algorithm that accounts for multiple return
6416/// statements and the lifetimes of the NRVO candidates. We should be able to
6417/// find a maximal set of NRVO variables.
John McCallaab3e412010-08-25 08:40:02 +00006418static void ComputeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
6419 ReturnStmt **Returns = Scope->Returns.data();
6420
Douglas Gregor6fd1b182010-05-15 06:01:05 +00006421 const VarDecl *NRVOCandidate = 0;
John McCallaab3e412010-08-25 08:40:02 +00006422 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00006423 if (!Returns[I]->getNRVOCandidate())
6424 return;
6425
6426 if (!NRVOCandidate)
6427 NRVOCandidate = Returns[I]->getNRVOCandidate();
6428 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
6429 return;
6430 }
6431
6432 if (NRVOCandidate)
6433 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
6434}
6435
John McCallfaf5fb42010-08-26 23:41:50 +00006436Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Douglas Gregor67da0d92009-05-15 17:59:04 +00006437 return ActOnFinishFunctionBody(D, move(BodyArg), false);
6438}
6439
John McCallb268a282010-08-23 23:25:46 +00006440Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
6441 bool IsInstantiation) {
Douglas Gregorc45a40a2009-08-22 00:34:47 +00006442 FunctionDecl *FD = 0;
6443 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
6444 if (FunTmpl)
6445 FD = FunTmpl->getTemplatedDecl();
6446 else
6447 FD = dyn_cast_or_null<FunctionDecl>(dcl);
6448
Ted Kremenek0b405322010-03-23 00:13:23 +00006449 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek1767a272011-02-23 01:51:48 +00006450 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenek918fe842010-03-20 21:06:02 +00006451
Douglas Gregorc45a40a2009-08-22 00:34:47 +00006452 if (FD) {
Chris Lattner960cc522009-04-18 09:36:27 +00006453 FD->setBody(Body);
Ted Kremenek918fe842010-03-20 21:06:02 +00006454 if (FD->isMain()) {
Mike Stump8e79f992009-07-24 02:49:01 +00006455 // C and C++ allow for main to automagically return 0.
John McCallcaa19452009-07-28 01:00:58 +00006456 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
6457 FD->setHasImplicitReturnZero(true);
Ted Kremenek0b405322010-03-23 00:13:23 +00006458 WP.disableCheckFallThrough();
Douglas Gregor9824aec2011-07-11 15:24:01 +00006459 } else if (FD->hasAttr<NakedAttr>()) {
6460 // If the function is marked 'naked', don't complain about missing return
6461 // statements.
6462 WP.disableCheckFallThrough();
Ted Kremenek918fe842010-03-20 21:06:02 +00006463 }
Mike Stump11289f42009-09-09 15:08:12 +00006464
Francois Pichet3abc9b82011-05-11 02:14:46 +00006465 // MSVC permits the use of pure specifier (=0) on function definition,
6466 // defined at class scope, warn about this non standard construct.
6467 if (getLangOptions().Microsoft && FD->isPure())
6468 Diag(FD->getLocation(), diag::warn_pure_function_definition);
6469
Douglas Gregor88d292c2010-05-13 16:44:06 +00006470 if (!FD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006471 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006472 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
6473 FD->getResultType(), FD);
Douglas Gregor88d292c2010-05-13 16:44:06 +00006474
6475 // If this is a constructor, we need a vtable.
6476 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
6477 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor6fd1b182010-05-15 06:01:05 +00006478
John McCallaab3e412010-08-25 08:40:02 +00006479 ComputeNRVO(Body, getCurFunction());
Douglas Gregor88d292c2010-05-13 16:44:06 +00006480 }
6481
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00006482 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff542cd5d2008-07-25 17:57:26 +00006483 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattner1598a3a2009-02-16 19:27:54 +00006484 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattner960cc522009-04-18 09:36:27 +00006485 MD->setBody(Body);
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00006486 if (Body)
6487 MD->setEndLoc(Body->getLocEnd());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006488 if (!MD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006489 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006490 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
6491 MD->getResultType(), MD);
6492 }
Ted Kremenek5a201952009-02-07 01:47:29 +00006493 } else {
John McCall48871652010-08-21 09:40:31 +00006494 return 0;
Ted Kremenek5a201952009-02-07 01:47:29 +00006495 }
Douglas Gregor67da0d92009-05-15 17:59:04 +00006496
Chris Lattnere2473062007-05-28 06:28:18 +00006497 // Verify and clean out per-function state.
Douglas Gregor9a28e842010-03-01 23:15:13 +00006498 if (Body) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00006499 // C++ constructors that have function-try-blocks can't have return
6500 // statements in the handlers of that block. (C++ [except.handle]p14)
6501 // Verify this.
6502 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
6503 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
6504
Ted Kremenek918fe842010-03-20 21:06:02 +00006505 // Verify that that gotos and switch cases don't jump into scopes illegally.
6506 // Verify that that gotos and switch cases don't jump into scopes illegally.
John McCallaab3e412010-08-25 08:40:02 +00006507 if (getCurFunction()->NeedsScopeChecking() &&
John McCall58efb8e2010-05-20 07:13:26 +00006508 !dcl->isInvalidDecl() &&
John McCall31168b02011-06-15 23:02:42 +00006509 !hasAnyUnrecoverableErrorsInThisFunction())
Douglas Gregor9a28e842010-03-01 23:15:13 +00006510 DiagnoseInvalidJumps(Body);
Mike Stump11289f42009-09-09 15:08:12 +00006511
John McCalldeb646e2010-08-04 01:04:25 +00006512 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
6513 if (!Destructor->getParent()->isDependentType())
6514 CheckDestructor(Destructor);
6515
John McCalla6309952010-03-16 21:39:52 +00006516 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6517 Destructor->getParent());
John McCalldeb646e2010-08-04 01:04:25 +00006518 }
Douglas Gregor9a28e842010-03-01 23:15:13 +00006519
6520 // If any errors have occurred, clear out any temporaries that may have
6521 // been leftover. This ensures that these temporaries won't be picked up for
6522 // deletion in some later function.
Douglas Gregor550b98b2011-03-04 23:08:02 +00006523 if (PP.getDiagnostics().hasErrorOccurred() ||
John McCall31168b02011-06-15 23:02:42 +00006524 PP.getDiagnostics().getSuppressAllDiagnostics()) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00006525 ExprTemporaries.clear();
John McCall31168b02011-06-15 23:02:42 +00006526 ExprNeedsCleanups = false;
6527 } else if (!isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenek918fe842010-03-20 21:06:02 +00006528 // Since the body is valid, issue any analysis-based warnings that are
6529 // enabled.
Ted Kremenek1767a272011-02-23 01:51:48 +00006530 ActivePolicy = &WP;
Ted Kremenek918fe842010-03-20 21:06:02 +00006531 }
6532
Douglas Gregor9a28e842010-03-01 23:15:13 +00006533 assert(ExprTemporaries.empty() && "Leftover temporaries in function");
John McCall31168b02011-06-15 23:02:42 +00006534 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Douglas Gregor9a28e842010-03-01 23:15:13 +00006535 }
6536
John McCalle99d5f32010-03-25 22:08:03 +00006537 if (!IsInstantiation)
6538 PopDeclContext();
6539
Ted Kremenek1767a272011-02-23 01:51:48 +00006540 PopFunctionOrBlockScope(ActivePolicy, dcl);
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00006541
Douglas Gregora7e3ea32009-11-15 07:07:58 +00006542 // If any errors have occurred, clear out any temporaries that may have
6543 // been leftover. This ensures that these temporaries won't be picked up for
6544 // deletion in some later function.
John McCall31168b02011-06-15 23:02:42 +00006545 if (getDiagnostics().hasErrorOccurred()) {
Douglas Gregora7e3ea32009-11-15 07:07:58 +00006546 ExprTemporaries.clear();
John McCall31168b02011-06-15 23:02:42 +00006547 ExprNeedsCleanups = false;
6548 }
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00006549
John McCall48871652010-08-21 09:40:31 +00006550 return dcl;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +00006551}
6552
Chris Lattnerac18be92006-11-20 06:49:47 +00006553/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
6554/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump11289f42009-09-09 15:08:12 +00006555NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00006556 IdentifierInfo &II, Scope *S) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00006557 // Before we produce a declaration for an implicitly defined
6558 // function, see whether there was a locally-scoped declaration of
6559 // this name as a function or variable. If so, use that
6560 // (non-visible) declaration, and complain about it.
6561 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
6562 = LocallyScopedExternalDecls.find(&II);
6563 if (Pos != LocallyScopedExternalDecls.end()) {
6564 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
6565 Diag(Pos->second->getLocation(), diag::note_previous_declaration);
6566 return Pos->second;
6567 }
6568
Chris Lattner00e26072008-05-05 21:18:06 +00006569 // Extension in C99. Legal in C90, but warn about it.
Daniel Dunbar07d07852009-10-18 21:17:35 +00006570 if (II.getName().startswith("__builtin_"))
Douglas Gregor56fbc372009-09-28 21:14:19 +00006571 Diag(Loc, diag::warn_builtin_unknown) << &II;
6572 else if (getLangOptions().C99)
Chris Lattner4bd8dd82008-11-19 08:23:25 +00006573 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner00e26072008-05-05 21:18:06 +00006574 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +00006575 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Mike Stump11289f42009-09-09 15:08:12 +00006576
Chris Lattnerac18be92006-11-20 06:49:47 +00006577 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +00006578 const char *Dummy;
John McCall084e83d2011-03-24 11:26:52 +00006579 AttributeFactory attrFactory;
6580 DeclSpec DS(attrFactory);
John McCall49bfce42009-08-03 20:12:06 +00006581 unsigned DiagID;
6582 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00006583 (void)Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +00006584 assert(!Error && "Error setting up implicit decl!");
Chris Lattnerac18be92006-11-20 06:49:47 +00006585 Declarator D(DS, Declarator::BlockContext);
John McCall084e83d2011-03-24 11:26:52 +00006586 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
Douglas Gregor54992352011-01-26 03:43:54 +00006587 0, 0, true, SourceLocation(),
Sebastian Redl802a4532011-03-05 22:42:13 +00006588 EST_None, SourceLocation(),
6589 0, 0, 0, 0, Loc, Loc, D),
John McCall084e83d2011-03-24 11:26:52 +00006590 DS.getAttributes(),
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006591 SourceLocation());
Chris Lattnerac18be92006-11-20 06:49:47 +00006592 D.SetIdentifier(&II, Loc);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006593
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00006594 // Insert this function into translation-unit scope.
6595
6596 DeclContext *PrevDC = CurContext;
6597 CurContext = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006598
John McCall48871652010-08-21 09:40:31 +00006599 FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroff3913ea42008-04-04 14:32:09 +00006600 FD->setImplicit();
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00006601
6602 CurContext = PrevDC;
6603
Douglas Gregore711f702009-02-14 18:57:46 +00006604 AddKnownFunctionAttributes(FD);
6605
Steve Naroff3913ea42008-04-04 14:32:09 +00006606 return FD;
Chris Lattnerac18be92006-11-20 06:49:47 +00006607}
6608
Douglas Gregore711f702009-02-14 18:57:46 +00006609/// \brief Adds any function attributes that we know a priori based on
6610/// the declaration of this function.
6611///
6612/// These attributes can apply both to implicitly-declared builtins
6613/// (like __builtin___printf_chk) or to library-declared functions
6614/// like NSLog or printf.
Douglas Gregor88336832011-06-15 05:45:11 +00006615///
6616/// We need to check for duplicate attributes both here and where user-written
6617/// attributes are applied to declarations.
Douglas Gregore711f702009-02-14 18:57:46 +00006618void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
6619 if (FD->isInvalidDecl())
6620 return;
6621
6622 // If this is a built-in function, map its builtin attributes to
6623 // actual attributes.
Douglas Gregor15fc9562009-09-12 00:22:50 +00006624 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregore711f702009-02-14 18:57:46 +00006625 // Handle printf-formatting attributes.
6626 unsigned FormatIdx;
6627 bool HasVAListArg;
6628 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006629 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006630 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
6631 "printf", FormatIdx+1,
Ted Kremenek7f4945a2010-02-11 05:28:37 +00006632 HasVAListArg ? 0 : FormatIdx+2));
Douglas Gregore711f702009-02-14 18:57:46 +00006633 }
Ted Kremenek5932c352010-07-16 02:11:15 +00006634 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
6635 HasVAListArg)) {
6636 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006637 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
6638 "scanf", FormatIdx+1,
Ted Kremenek5932c352010-07-16 02:11:15 +00006639 HasVAListArg ? 0 : FormatIdx+2));
6640 }
Daniel Dunbar8eb018a2009-02-16 22:43:43 +00006641
6642 // Mark const if we don't care about errno and that is the only
6643 // thing preventing the function from being const. This allows
6644 // IRgen to use LLVM intrinsics for such functions.
6645 if (!getLangOptions().MathErrno &&
6646 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006647 if (!FD->getAttr<ConstAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006648 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Daniel Dunbar8eb018a2009-02-16 22:43:43 +00006649 }
Mike Stumpca6c8752009-07-27 19:14:18 +00006650
Douglas Gregor88336832011-06-15 05:45:11 +00006651 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006652 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
Douglas Gregor88336832011-06-15 05:45:11 +00006653 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006654 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Douglas Gregore711f702009-02-14 18:57:46 +00006655 }
6656
6657 IdentifierInfo *Name = FD->getIdentifier();
6658 if (!Name)
6659 return;
Mike Stump11289f42009-09-09 15:08:12 +00006660 if ((!getLangOptions().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +00006661 FD->getDeclContext()->isTranslationUnit()) ||
6662 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +00006663 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregore711f702009-02-14 18:57:46 +00006664 LinkageSpecDecl::lang_c)) {
6665 // Okay: this could be a libc/libm/Objective-C function we know
6666 // about.
6667 } else
6668 return;
6669
Douglas Gregorfedd4282009-04-22 20:56:09 +00006670 if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
Mike Stump82a9e442009-07-28 00:07:08 +00006671 // FIXME: NSLog and NSLogv should be target specific
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006672 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
Douglas Gregore711f702009-02-14 18:57:46 +00006673 // FIXME: We known better than our headers.
Ted Kremenek7f4945a2010-02-11 05:28:37 +00006674 const_cast<FormatAttr *>(Format)->setType(Context, "printf");
Mike Stump11289f42009-09-09 15:08:12 +00006675 } else
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006676 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
6677 "printf", 1,
Eli Friedmanf4799842009-06-10 04:01:38 +00006678 Name->isStr("NSLogv") ? 0 : 2));
Douglas Gregorfedd4282009-04-22 20:56:09 +00006679 } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump82a9e442009-07-28 00:07:08 +00006680 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump11289f42009-09-09 15:08:12 +00006681 // target-specific builtins, perhaps?
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006682 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006683 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
6684 "printf", 2,
Eli Friedmanf4799842009-06-10 04:01:38 +00006685 Name->isStr("vasprintf") ? 0 : 3));
Mike Stumpa4de80b2009-07-28 02:25:19 +00006686 }
Douglas Gregore711f702009-02-14 18:57:46 +00006687}
Chris Lattner302b4be2006-11-19 02:31:38 +00006688
John McCall703a3f82009-10-24 08:00:42 +00006689TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCallbcd03502009-12-07 02:54:59 +00006690 TypeSourceInfo *TInfo) {
Chris Lattner776fac82007-06-09 00:53:06 +00006691 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +00006692 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump11289f42009-09-09 15:08:12 +00006693
John McCallbcd03502009-12-07 02:54:59 +00006694 if (!TInfo) {
John McCall703a3f82009-10-24 08:00:42 +00006695 assert(D.isInvalidType() && "no declarator info for valid type");
John McCallbcd03502009-12-07 02:54:59 +00006696 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCall703a3f82009-10-24 08:00:42 +00006697 }
6698
Chris Lattner18b19622007-01-22 07:39:13 +00006699 // Scope manipulation handled by caller.
Chris Lattnerc5ffed42008-04-04 06:12:32 +00006700 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00006701 D.getSourceRange().getBegin(),
Chris Lattnerc5ffed42008-04-04 06:12:32 +00006702 D.getIdentifierLoc(),
Mike Stump11289f42009-09-09 15:08:12 +00006703 D.getIdentifier(),
John McCallbcd03502009-12-07 02:54:59 +00006704 TInfo);
Mike Stump11289f42009-09-09 15:08:12 +00006705
John McCall04fcd0d2011-02-01 08:20:08 +00006706 // Bail out immediately if we have an invalid declaration.
6707 if (D.isInvalidType()) {
6708 NewTD->setInvalidDecl();
6709 return NewTD;
Anders Carlsson02751152009-03-10 17:07:44 +00006710 }
6711
John McCall04fcd0d2011-02-01 08:20:08 +00006712 // C++ [dcl.typedef]p8:
6713 // If the typedef declaration defines an unnamed class (or
6714 // enum), the first typedef-name declared by the declaration
6715 // to be that class type (or enum type) is used to denote the
6716 // class type (or enum type) for linkage purposes only.
6717 // We need to check whether the type was declared in the declaration.
6718 switch (D.getDeclSpec().getTypeSpecType()) {
6719 case TST_enum:
6720 case TST_struct:
6721 case TST_union:
6722 case TST_class: {
6723 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
6724
6725 // Do nothing if the tag is not anonymous or already has an
6726 // associated typedef (from an earlier typedef in this decl group).
6727 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smithdda56e42011-04-15 14:24:37 +00006728 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCall04fcd0d2011-02-01 08:20:08 +00006729
6730 // A well-formed anonymous tag must always be a TUK_Definition.
6731 assert(tagFromDeclSpec->isThisDeclarationADefinition());
6732
6733 // The type must match the tag exactly; no qualifiers allowed.
6734 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
6735 break;
6736
6737 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smithdda56e42011-04-15 14:24:37 +00006738 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCall04fcd0d2011-02-01 08:20:08 +00006739 break;
6740 }
6741
6742 default:
6743 break;
6744 }
6745
Steve Narofff93b6722007-08-28 20:14:24 +00006746 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +00006747}
6748
Douglas Gregord9034f02009-05-14 16:41:31 +00006749
6750/// \brief Determine whether a tag with a given kind is acceptable
6751/// as a redeclaration of the given tag declaration.
6752///
6753/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00006754bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieucaa33d32011-06-10 03:11:26 +00006755 TagTypeKind NewTag, bool isDefinition,
Douglas Gregord9034f02009-05-14 16:41:31 +00006756 SourceLocation NewTagLoc,
6757 const IdentifierInfo &Name) {
6758 // C++ [dcl.type.elab]p3:
6759 // The class-key or enum keyword present in the
6760 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara6150c882010-05-11 21:36:43 +00006761 // declaration to which the name in the elaborated-type-specifier
Douglas Gregord9034f02009-05-14 16:41:31 +00006762 // refers. This rule also applies to the form of
6763 // elaborated-type-specifier that declares a class-name or
6764 // friend class since it can be construed as referring to the
6765 // definition of the class. Thus, in any
6766 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara6150c882010-05-11 21:36:43 +00006767 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregord9034f02009-05-14 16:41:31 +00006768 // used to refer to a union (clause 9), and either the class or
6769 // struct class-key shall be used to refer to a class (clause 9)
6770 // declared using the class or struct class-key.
Abramo Bagnara6150c882010-05-11 21:36:43 +00006771 TagTypeKind OldTag = Previous->getTagKind();
Richard Trieucaa33d32011-06-10 03:11:26 +00006772 if (!isDefinition || (NewTag != TTK_Class && NewTag != TTK_Struct))
6773 if (OldTag == NewTag)
6774 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006775
Abramo Bagnara6150c882010-05-11 21:36:43 +00006776 if ((OldTag == TTK_Struct || OldTag == TTK_Class) &&
6777 (NewTag == TTK_Struct || NewTag == TTK_Class)) {
Douglas Gregord9034f02009-05-14 16:41:31 +00006778 // Warn about the struct/class tag mismatch.
6779 bool isTemplate = false;
6780 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
6781 isTemplate = Record->getDescribedClassTemplate();
6782
Richard Trieucaa33d32011-06-10 03:11:26 +00006783 if (!ActiveTemplateInstantiations.empty()) {
6784 // In a template instantiation, do not offer fix-its for tag mismatches
6785 // since they usually mess up the template instead of fixing the problem.
6786 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
6787 << (NewTag == TTK_Class) << isTemplate << &Name;
6788 return true;
6789 }
6790
6791 if (isDefinition) {
6792 // On definitions, check previous tags and issue a fix-it for each
6793 // one that doesn't match the current tag.
6794 if (Previous->getDefinition()) {
6795 // Don't suggest fix-its for redefinitions.
6796 return true;
6797 }
6798
6799 bool previousMismatch = false;
6800 for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
6801 E(Previous->redecls_end()); I != E; ++I) {
6802 if (I->getTagKind() != NewTag) {
6803 if (!previousMismatch) {
6804 previousMismatch = true;
6805 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
6806 << (NewTag == TTK_Class) << isTemplate << &Name;
6807 }
6808 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
6809 << (NewTag == TTK_Class)
6810 << FixItHint::CreateReplacement(I->getInnerLocStart(),
6811 NewTag == TTK_Class?
6812 "class" : "struct");
6813 }
6814 }
6815 return true;
6816 }
6817
6818 // Check for a previous definition. If current tag and definition
6819 // are same type, do nothing. If no definition, but disagree with
6820 // with previous tag type, give a warning, but no fix-it.
6821 const TagDecl *Redecl = Previous->getDefinition() ?
6822 Previous->getDefinition() : Previous;
6823 if (Redecl->getTagKind() == NewTag) {
6824 return true;
6825 }
6826
Douglas Gregord9034f02009-05-14 16:41:31 +00006827 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Abramo Bagnara6150c882010-05-11 21:36:43 +00006828 << (NewTag == TTK_Class)
Richard Trieucaa33d32011-06-10 03:11:26 +00006829 << isTemplate << &Name;
6830 Diag(Redecl->getLocation(), diag::note_previous_use);
6831
6832 // If there is a previous defintion, suggest a fix-it.
6833 if (Previous->getDefinition()) {
6834 Diag(NewTagLoc, diag::note_struct_class_suggestion)
6835 << (Redecl->getTagKind() == TTK_Class)
6836 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
6837 Redecl->getTagKind() == TTK_Class? "class" : "struct");
6838 }
6839
Douglas Gregord9034f02009-05-14 16:41:31 +00006840 return true;
6841 }
6842 return false;
6843}
6844
Steve Naroff30d242c2007-09-15 18:49:24 +00006845/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +00006846/// former case, Name will be non-null. In the later case, Name will be null.
John McCall9bb74a52009-07-31 02:45:11 +00006847/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Chris Lattner1300fb92007-01-23 23:42:53 +00006848/// reference/declaration/definition of a tag.
John McCall48871652010-08-21 09:40:31 +00006849Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor009f6992010-09-16 23:58:57 +00006850 SourceLocation KWLoc, CXXScopeSpec &SS,
6851 IdentifierInfo *Name, SourceLocation NameLoc,
6852 AttributeList *Attr, AccessSpecifier AS,
6853 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00006854 bool &OwnedDecl, bool &IsDependent,
6855 bool ScopedEnum, bool ScopedEnumUsesClassTag,
Douglas Gregor0bf31402010-10-08 23:50:27 +00006856 TypeResult UnderlyingType) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006857 // If this is not a definition, it must have a name.
John McCall9bb74a52009-07-31 02:45:11 +00006858 assert((Name != 0 || TUK == TUK_Definition) &&
Chris Lattner7b9ace62007-01-23 20:11:08 +00006859 "Nameless record must be a definition!");
John McCallace48cd2010-10-19 01:40:49 +00006860 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregorded2d7b2009-02-04 19:02:06 +00006861
Douglas Gregord6ab8742009-05-28 23:31:59 +00006862 OwnedDecl = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +00006863 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00006864
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006865 // FIXME: Check explicit specializations more carefully.
6866 bool isExplicitSpecialization = false;
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006867 bool Invalid = false;
John McCallace48cd2010-10-19 01:40:49 +00006868
6869 // We only need to do this matching if we have template parameters
6870 // or a scope specifier, which also conveniently avoids this work
6871 // for non-C++ cases.
Abramo Bagnara60804e12011-03-18 15:16:37 +00006872 if (TemplateParameterLists.size() > 0 ||
John McCallace48cd2010-10-19 01:40:49 +00006873 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Douglas Gregore93e46c2009-07-22 23:48:44 +00006874 if (TemplateParameterList *TemplateParams
Douglas Gregor972fe532011-05-10 18:27:06 +00006875 = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS,
John McCallc9739e32010-10-16 07:23:36 +00006876 TemplateParameterLists.get(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00006877 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00006878 TUK == TUK_Friend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006879 isExplicitSpecialization,
6880 Invalid)) {
Douglas Gregor3dad8422009-09-26 06:47:28 +00006881 if (TemplateParams->size() > 0) {
Douglas Gregore93e46c2009-07-22 23:48:44 +00006882 // This is a declaration or definition of a class template (which may
6883 // be a member of another template).
Abramo Bagnara60804e12011-03-18 15:16:37 +00006884
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006885 if (Invalid)
John McCall48871652010-08-21 09:40:31 +00006886 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00006887
Douglas Gregore93e46c2009-07-22 23:48:44 +00006888 OwnedDecl = false;
John McCall9bb74a52009-07-31 02:45:11 +00006889 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +00006890 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00006891 TemplateParams, AS,
Abramo Bagnara60804e12011-03-18 15:16:37 +00006892 TemplateParameterLists.size() - 1,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00006893 (TemplateParameterList**) TemplateParameterLists.release());
Douglas Gregore93e46c2009-07-22 23:48:44 +00006894 return Result.get();
6895 } else {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006896 // The "template<>" header is extraneous.
6897 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara6150c882010-05-11 21:36:43 +00006898 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006899 isExplicitSpecialization = true;
Douglas Gregore93e46c2009-07-22 23:48:44 +00006900 }
Mike Stump11289f42009-09-09 15:08:12 +00006901 }
6902 }
6903
Douglas Gregor0bf31402010-10-08 23:50:27 +00006904 // Figure out the underlying type if this a enum declaration. We need to do
6905 // this early, because it's needed to detect if this is an incompatible
6906 // redeclaration.
6907 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
6908
6909 if (Kind == TTK_Enum) {
6910 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
6911 // No underlying type explicitly specified, or we failed to parse the
6912 // type, default to int.
6913 EnumUnderlying = Context.IntTy.getTypePtr();
6914 else if (UnderlyingType.get()) {
6915 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
6916 // integral type; any cv-qualification is ignored.
6917 TypeSourceInfo *TI = 0;
6918 QualType T = GetTypeFromParser(UnderlyingType.get(), &TI);
6919 EnumUnderlying = TI;
6920
6921 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
6922
6923 if (!T->isDependentType() && !T->isIntegralType(Context)) {
6924 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
6925 << T;
6926 // Recover by falling back to int.
6927 EnumUnderlying = Context.IntTy.getTypePtr();
6928 }
Douglas Gregor2b988fd2010-12-16 00:24:44 +00006929
6930 if (DiagnoseUnexpandedParameterPack(UnderlyingLoc, TI,
6931 UPPC_FixedUnderlyingType))
6932 EnumUnderlying = Context.IntTy.getTypePtr();
6933
Francois Picheta3108062010-10-18 15:01:13 +00006934 } else if (getLangOptions().Microsoft)
6935 // Microsoft enums are always of int type.
6936 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006937 }
6938
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00006939 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00006940 DeclContext *DC = CurContext;
Douglas Gregor87f54062009-09-15 22:30:29 +00006941 bool isStdBadAlloc = false;
Douglas Gregordee1be82009-01-17 00:42:38 +00006942
Chandler Carrutha419dbb2010-03-01 21:17:36 +00006943 RedeclarationKind Redecl = ForRedeclaration;
6944 if (TUK == TUK_Friend || TUK == TUK_Reference)
6945 Redecl = NotForRedeclaration;
John McCall1f82f242009-11-18 22:49:29 +00006946
6947 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
John McCall6538c932009-10-10 05:48:19 +00006948
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00006949 if (Name && SS.isNotEmpty()) {
6950 // We have a nested-name tag ('struct foo::bar').
6951
6952 // Check for invalid 'foo::'.
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00006953 if (SS.isInvalid()) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00006954 Name = 0;
6955 goto CreateNewDecl;
6956 }
6957
John McCall7f41d982009-09-11 04:59:25 +00006958 // If this is a friend or a reference to a class in a dependent
6959 // context, don't try to make a decl for it.
6960 if (TUK == TUK_Friend || TUK == TUK_Reference) {
6961 DC = computeDeclContext(SS, false);
6962 if (!DC) {
6963 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +00006964 return 0;
John McCall7f41d982009-09-11 04:59:25 +00006965 }
John McCall0b66eb32010-05-01 00:40:08 +00006966 } else {
6967 DC = computeDeclContext(SS, true);
6968 if (!DC) {
6969 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
6970 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00006971 return 0;
John McCall0b66eb32010-05-01 00:40:08 +00006972 }
John McCall7f41d982009-09-11 04:59:25 +00006973 }
6974
John McCall0b66eb32010-05-01 00:40:08 +00006975 if (RequireCompleteDeclContext(SS, DC))
John McCall48871652010-08-21 09:40:31 +00006976 return 0;
Douglas Gregor2ec748c2009-05-14 00:28:11 +00006977
Douglas Gregor8761da52009-02-03 00:34:39 +00006978 SearchDC = DC;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00006979 // Look-up name inside 'foo::'.
John McCall1f82f242009-11-18 22:49:29 +00006980 LookupQualifiedName(Previous, DC);
John McCall6538c932009-10-10 05:48:19 +00006981
John McCall1f82f242009-11-18 22:49:29 +00006982 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006983 return 0;
John McCall6538c932009-10-10 05:48:19 +00006984
John McCall1f82f242009-11-18 22:49:29 +00006985 if (Previous.empty()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00006986 // Name lookup did not find anything. However, if the
6987 // nested-name-specifier refers to the current instantiation,
6988 // and that current instantiation has any dependent base
6989 // classes, we might find something at instantiation time: treat
6990 // this as a dependent elaborated-type-specifier.
John McCallace48cd2010-10-19 01:40:49 +00006991 // But this only makes any sense for reference-like lookups.
6992 if (Previous.wasNotFoundInCurrentInstantiation() &&
6993 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00006994 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +00006995 return 0;
Douglas Gregord2e6a452010-01-14 17:47:39 +00006996 }
6997
6998 // A tag 'foo::bar' must already exist.
Douglas Gregorf5af3582010-03-31 23:17:41 +00006999 Diag(NameLoc, diag::err_not_tag_in_scope)
7000 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00007001 Name = 0;
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007002 Invalid = true;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00007003 goto CreateNewDecl;
7004 }
Chris Lattnerd9773512009-01-21 02:38:50 +00007005 } else if (Name) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00007006 // If this is a named struct, check to see if there was a previous forward
7007 // declaration or definition.
Douglas Gregor889ceb72009-02-03 19:21:40 +00007008 // FIXME: We're looking into outer scopes here, even when we
7009 // shouldn't be. Doing so can result in ambiguities that we
7010 // shouldn't be diagnosing.
John McCall1f82f242009-11-18 22:49:29 +00007011 LookupName(Previous, S);
7012
Douglas Gregor5d1d9e32011-05-09 21:46:33 +00007013 if (Previous.isAmbiguous() &&
7014 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregored8a29b2011-05-04 00:25:33 +00007015 LookupResult::Filter F = Previous.makeFilter();
7016 while (F.hasNext()) {
7017 NamedDecl *ND = F.next();
7018 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
7019 F.erase();
7020 }
7021 F.done();
Douglas Gregored8a29b2011-05-04 00:25:33 +00007022 }
7023
John McCall1f82f242009-11-18 22:49:29 +00007024 // Note: there used to be some attempt at recovery here.
7025 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00007026 return 0;
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007027
John McCall9bb74a52009-07-31 02:45:11 +00007028 if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007029 // FIXME: This makes sure that we ignore the contexts associated
7030 // with C structs, unions, and enums when looking for a matching
7031 // tag declaration or definition. See the similar lookup tweak
Douglas Gregored8f2882009-01-30 01:04:22 +00007032 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00007033 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
7034 SearchDC = SearchDC->getParent();
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007035 }
Douglas Gregor009f6992010-09-16 23:58:57 +00007036 } else if (S->isFunctionPrototypeScope()) {
7037 // If this is an enum declaration in function prototype scope, set its
7038 // initial context to the translation unit.
7039 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00007040 }
7041
John McCall1f82f242009-11-18 22:49:29 +00007042 if (Previous.isSingleResult() &&
7043 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00007044 // Maybe we will complain about the shadowed template parameter.
John McCall1f82f242009-11-18 22:49:29 +00007045 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor5101c242008-12-05 18:15:24 +00007046 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00007047 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00007048 }
7049
Douglas Gregor87f54062009-09-15 22:30:29 +00007050 if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007051 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor87f54062009-09-15 22:30:29 +00007052 // This is a declaration of or a reference to "std::bad_alloc".
7053 isStdBadAlloc = true;
7054
John McCall1f82f242009-11-18 22:49:29 +00007055 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor87f54062009-09-15 22:30:29 +00007056 // std::bad_alloc has been implicitly declared (but made invisible to
7057 // name lookup). Fill in this implicit declaration as the previous
7058 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007059 Previous.addDecl(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +00007060 }
7061 }
John McCall1f82f242009-11-18 22:49:29 +00007062
John McCalle9eaf8e2010-03-25 21:28:06 +00007063 // If we didn't find a previous declaration, and this is a reference
7064 // (or friend reference), move to the correct scope. In C++, we
7065 // also need to do a redeclaration lookup there, just in case
7066 // there's a shadow friend decl.
7067 if (Name && Previous.empty() &&
7068 (TUK == TUK_Reference || TUK == TUK_Friend)) {
7069 if (Invalid) goto CreateNewDecl;
7070 assert(SS.isEmpty());
7071
7072 if (TUK == TUK_Reference) {
7073 // C++ [basic.scope.pdecl]p5:
7074 // -- for an elaborated-type-specifier of the form
7075 //
7076 // class-key identifier
7077 //
7078 // if the elaborated-type-specifier is used in the
7079 // decl-specifier-seq or parameter-declaration-clause of a
7080 // function defined in namespace scope, the identifier is
7081 // declared as a class-name in the namespace that contains
7082 // the declaration; otherwise, except as a friend
7083 // declaration, the identifier is declared in the smallest
7084 // non-class, non-function-prototype scope that contains the
7085 // declaration.
7086 //
7087 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
7088 // C structs and unions.
7089 //
7090 // It is an error in C++ to declare (rather than define) an enum
7091 // type, including via an elaborated type specifier. We'll
7092 // diagnose that later; for now, declare the enum in the same
7093 // scope as we would have picked for any other tag type.
7094 //
7095 // GNU C also supports this behavior as part of its incomplete
7096 // enum types extension, while GNU C++ does not.
7097 //
7098 // Find the context where we'll be declaring the tag.
7099 // FIXME: We would like to maintain the current DeclContext as the
7100 // lexical context,
Rafael Espindola9e976dc2011-01-20 02:26:24 +00007101 while (SearchDC->isRecord() || SearchDC->isTransparentContext())
John McCalle9eaf8e2010-03-25 21:28:06 +00007102 SearchDC = SearchDC->getParent();
7103
7104 // Find the scope where we'll be declaring the tag.
7105 while (S->isClassScope() ||
7106 (getLangOptions().CPlusPlus &&
7107 S->isFunctionPrototypeScope()) ||
7108 ((S->getFlags() & Scope::DeclScope) == 0) ||
7109 (S->getEntity() &&
7110 ((DeclContext *)S->getEntity())->isTransparentContext()))
7111 S = S->getParent();
7112 } else {
7113 assert(TUK == TUK_Friend);
7114 // C++ [namespace.memdef]p3:
7115 // If a friend declaration in a non-local class first declares a
7116 // class or function, the friend class or function is a member of
7117 // the innermost enclosing namespace.
7118 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCalle9eaf8e2010-03-25 21:28:06 +00007119 }
7120
John McCalle87beb22010-04-23 18:46:30 +00007121 // In C++, we need to do a redeclaration lookup to properly
7122 // diagnose some problems.
John McCalle9eaf8e2010-03-25 21:28:06 +00007123 if (getLangOptions().CPlusPlus) {
7124 Previous.setRedeclarationKind(ForRedeclaration);
7125 LookupQualifiedName(Previous, SearchDC);
7126 }
7127 }
7128
John McCall1f82f242009-11-18 22:49:29 +00007129 if (!Previous.empty()) {
Douglas Gregorce40e2e2010-04-12 16:00:01 +00007130 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
John McCalle87beb22010-04-23 18:46:30 +00007131
7132 // It's okay to have a tag decl in the same scope as a typedef
7133 // which hides a tag decl in the same scope. Finding this
7134 // insanity with a redeclaration lookup can only actually happen
7135 // in C++.
7136 //
7137 // This is also okay for elaborated-type-specifiers, which is
7138 // technically forbidden by the current standard but which is
7139 // okay according to the likely resolution of an open issue;
7140 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
7141 if (getLangOptions().CPlusPlus) {
Richard Smithdda56e42011-04-15 14:24:37 +00007142 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCalle87beb22010-04-23 18:46:30 +00007143 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
7144 TagDecl *Tag = TT->getDecl();
7145 if (Tag->getDeclName() == Name &&
Sebastian Redl50c68252010-08-31 00:36:30 +00007146 Tag->getDeclContext()->getRedeclContext()
7147 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCalle87beb22010-04-23 18:46:30 +00007148 PrevDecl = Tag;
7149 Previous.clear();
7150 Previous.addDecl(Tag);
Douglas Gregorfcee9462010-08-27 22:55:10 +00007151 Previous.resolveKind();
John McCalle87beb22010-04-23 18:46:30 +00007152 }
7153 }
7154 }
7155 }
7156
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007157 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +00007158 // If this is a use of a previous tag, or if the tag is already declared
7159 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007160 // rementions the tag), reuse the decl.
John McCall07e91c02009-08-06 02:15:43 +00007161 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Douglas Gregordb446112011-03-07 16:54:27 +00007162 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +00007163 // Make sure that this wasn't declared as an enum and now used as a
7164 // struct or something similar.
Richard Trieucaa33d32011-06-10 03:11:26 +00007165 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
7166 TUK == TUK_Definition, KWLoc,
7167 *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00007168 bool SafeToContinue
Abramo Bagnara6150c882010-05-11 21:36:43 +00007169 = (PrevTagDecl->getTagKind() != TTK_Enum &&
7170 Kind != TTK_Enum);
Douglas Gregor170512f2009-04-01 23:51:29 +00007171 if (SafeToContinue)
Mike Stump11289f42009-09-09 15:08:12 +00007172 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00007173 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00007174 << FixItHint::CreateReplacement(SourceRange(KWLoc),
7175 PrevTagDecl->getKindName());
Douglas Gregor170512f2009-04-01 23:51:29 +00007176 else
7177 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall1f82f242009-11-18 22:49:29 +00007178 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00007179
Mike Stump11289f42009-09-09 15:08:12 +00007180 if (SafeToContinue)
Douglas Gregor170512f2009-04-01 23:51:29 +00007181 Kind = PrevTagDecl->getTagKind();
7182 else {
7183 // Recover by making this an anonymous redefinition.
7184 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00007185 Previous.clear();
Douglas Gregor170512f2009-04-01 23:51:29 +00007186 Invalid = true;
7187 }
7188 }
7189
Douglas Gregor0bf31402010-10-08 23:50:27 +00007190 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
7191 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
7192
7193 // All conflicts with previous declarations are recovered by
7194 // returning the previous declaration.
7195 if (ScopedEnum != PrevEnum->isScoped()) {
7196 Diag(KWLoc, diag::err_enum_redeclare_scoped_mismatch)
7197 << PrevEnum->isScoped();
7198 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
7199 return PrevTagDecl;
7200 }
7201 else if (EnumUnderlying && PrevEnum->isFixed()) {
7202 QualType T;
7203 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
7204 T = TI->getType();
7205 else
7206 T = QualType(EnumUnderlying.get<const Type*>(), 0);
7207
7208 if (!Context.hasSameUnqualifiedType(T, PrevEnum->getIntegerType())) {
Douglas Gregor1a099ba2010-12-01 16:10:38 +00007209 Diag(NameLoc.isValid() ? NameLoc : KWLoc,
7210 diag::err_enum_redeclare_type_mismatch)
7211 << T
7212 << PrevEnum->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007213 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
7214 return PrevTagDecl;
7215 }
7216 }
7217 else if (!EnumUnderlying.isNull() != PrevEnum->isFixed()) {
7218 Diag(KWLoc, diag::err_enum_redeclare_fixed_mismatch)
7219 << PrevEnum->isFixed();
7220 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
7221 return PrevTagDecl;
7222 }
7223 }
7224
Douglas Gregor170512f2009-04-01 23:51:29 +00007225 if (!Invalid) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007226 // If this is a use, just return the declaration we found.
Chris Lattner9ff58d72008-07-03 03:30:58 +00007227
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007228 // FIXME: In the future, return a variant or some other clue
7229 // for the consumer of this Decl to know it doesn't own it.
7230 // For our current ASTs this shouldn't be a problem, but will
7231 // need to be changed with DeclGroups.
Francois Pichete37eeba2011-06-01 04:14:20 +00007232 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
7233 getLangOptions().Microsoft)) || TUK == TUK_Friend)
John McCall48871652010-08-21 09:40:31 +00007234 return PrevTagDecl;
Douglas Gregorded2d7b2009-02-04 19:02:06 +00007235
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007236 // Diagnose attempts to redefine a tag.
John McCall9bb74a52009-07-31 02:45:11 +00007237 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007238 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00007239 // If we're defining a specialization and the previous definition
7240 // is from an implicit instantiation, don't emit an error
7241 // here; we'll catch this in the general case below.
7242 if (!isExplicitSpecialization ||
7243 !isa<CXXRecordDecl>(Def) ||
7244 cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
7245 == TSK_ExplicitSpecialization) {
7246 Diag(NameLoc, diag::err_redefinition) << Name;
7247 Diag(Def->getLocation(), diag::note_previous_definition);
7248 // If this is a redefinition, recover by making this
7249 // struct be anonymous, which will make any later
7250 // references get the previous definition.
7251 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00007252 Previous.clear();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007253 Invalid = true;
7254 }
Douglas Gregordee1be82009-01-17 00:42:38 +00007255 } else {
7256 // If the type is currently being defined, complain
7257 // about a nested redefinition.
John McCall424cec92011-01-19 06:33:43 +00007258 const TagType *Tag
7259 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregordee1be82009-01-17 00:42:38 +00007260 if (Tag->isBeingDefined()) {
7261 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump11289f42009-09-09 15:08:12 +00007262 Diag(PrevTagDecl->getLocation(),
Douglas Gregordee1be82009-01-17 00:42:38 +00007263 diag::note_previous_definition);
7264 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00007265 Previous.clear();
Douglas Gregordee1be82009-01-17 00:42:38 +00007266 Invalid = true;
7267 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007268 }
Douglas Gregordee1be82009-01-17 00:42:38 +00007269
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007270 // Okay, this is definition of a previously declared or referenced
7271 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregordee1be82009-01-17 00:42:38 +00007272 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007273 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007274 // If we get here we have (another) forward declaration or we
John McCall07e91c02009-08-06 02:15:43 +00007275 // have a definition. Just create a new decl.
7276
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007277 } else {
7278 // If we get here, this is a definition of a new tag type in a nested
Mike Stump11289f42009-09-09 15:08:12 +00007279 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007280 // new decl/type. We set PrevDecl to NULL so that the entities
7281 // have distinct types.
John McCall1f82f242009-11-18 22:49:29 +00007282 Previous.clear();
Chris Lattner7b9ace62007-01-23 20:11:08 +00007283 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007284 // If we get here, we're going to create a new Decl. If PrevDecl
7285 // is non-NULL, it's a definition of the tag declared by
7286 // PrevDecl. If it's NULL, we have a new definition.
John McCalle87beb22010-04-23 18:46:30 +00007287
7288
7289 // Otherwise, PrevDecl is not a tag, but was found with tag
7290 // lookup. This is only actually possible in C++, where a few
7291 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007292 } else {
John McCalle87beb22010-04-23 18:46:30 +00007293 assert(getLangOptions().CPlusPlus);
7294
7295 // Use a better diagnostic if an elaborated-type-specifier
7296 // found the wrong kind of type on the first
7297 // (non-redeclaration) lookup.
7298 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
7299 !Previous.isForRedeclaration()) {
7300 unsigned Kind = 0;
7301 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +00007302 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
7303 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +00007304 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
7305 Diag(PrevDecl->getLocation(), diag::note_declared_at);
7306 Invalid = true;
7307
7308 // Otherwise, only diagnose if the declaration is in scope.
Douglas Gregordb446112011-03-07 16:54:27 +00007309 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
7310 isExplicitSpecialization)) {
John McCalle87beb22010-04-23 18:46:30 +00007311 // do nothing
7312
7313 // Diagnose implicit declarations introduced by elaborated types.
7314 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
7315 unsigned Kind = 0;
7316 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +00007317 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
7318 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +00007319 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
7320 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
7321 Invalid = true;
7322
7323 // Otherwise it's a declaration. Call out a particularly common
7324 // case here.
Richard Smithdda56e42011-04-15 14:24:37 +00007325 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
7326 unsigned Kind = 0;
7327 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCalle87beb22010-04-23 18:46:30 +00007328 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smithdda56e42011-04-15 14:24:37 +00007329 << Name << Kind << TND->getUnderlyingType();
John McCalle87beb22010-04-23 18:46:30 +00007330 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
7331 Invalid = true;
7332
7333 // Otherwise, diagnose.
7334 } else {
7335 // The tag name clashes with something else in the target scope,
7336 // issue an error and recover by making this tag be anonymous.
Chris Lattner4bd8dd82008-11-19 08:23:25 +00007337 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner0369c572008-11-23 23:12:31 +00007338 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +00007339 Name = 0;
Douglas Gregordee1be82009-01-17 00:42:38 +00007340 Invalid = true;
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +00007341 }
John McCalle87beb22010-04-23 18:46:30 +00007342
7343 // The existing declaration isn't relevant to us; we're in a
7344 // new scope, so clear out the previous declaration.
7345 Previous.clear();
Chris Lattner8799cf22007-01-23 01:57:16 +00007346 }
Chris Lattner18b19622007-01-22 07:39:13 +00007347 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00007348
Chris Lattner438e5012008-12-17 07:13:27 +00007349CreateNewDecl:
Mike Stump11289f42009-09-09 15:08:12 +00007350
John McCall1f82f242009-11-18 22:49:29 +00007351 TagDecl *PrevDecl = 0;
7352 if (Previous.isSingleResult())
7353 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
7354
Chris Lattnerbf0b7982007-01-23 04:27:41 +00007355 // If there is an identifier, use the location of the identifier as the
7356 // location of the decl, otherwise use the location of the struct/union
7357 // keyword.
7358 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump11289f42009-09-09 15:08:12 +00007359
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007360 // Otherwise, create a new declaration. If there is a previous
7361 // declaration of the same entity, the two will be linked via
7362 // PrevDecl.
Chris Lattner7b9ace62007-01-23 20:11:08 +00007363 TagDecl *New;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00007364
Douglas Gregor0bf31402010-10-08 23:50:27 +00007365 bool IsForwardReference = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +00007366 if (Kind == TTK_Enum) {
Chris Lattner776fac82007-06-09 00:53:06 +00007367 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
7368 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007369 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor0bf31402010-10-08 23:50:27 +00007370 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00007371 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Chris Lattner5f521502007-01-25 06:27:24 +00007372 // If this is an undefined enum, warn.
Douglas Gregorc9ea2d52010-06-22 14:26:35 +00007373 if (TUK != TUK_Definition && !Invalid) {
7374 TagDecl *Def;
Douglas Gregor0bf31402010-10-08 23:50:27 +00007375 if (getLangOptions().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) {
7376 // C++0x: 7.2p2: opaque-enum-declaration.
7377 // Conflicts are diagnosed above. Do nothing.
7378 }
7379 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorc9ea2d52010-06-22 14:26:35 +00007380 Diag(Loc, diag::ext_forward_ref_enum_def)
7381 << New;
7382 Diag(Def->getLocation(), diag::note_previous_definition);
7383 } else {
Francois Pichet488b4a72010-09-12 05:06:55 +00007384 unsigned DiagID = diag::ext_forward_ref_enum;
7385 if (getLangOptions().Microsoft)
7386 DiagID = diag::ext_ms_forward_ref_enum;
7387 else if (getLangOptions().CPlusPlus)
7388 DiagID = diag::err_forward_ref_enum;
7389 Diag(Loc, DiagID);
Douglas Gregor0bf31402010-10-08 23:50:27 +00007390
7391 // If this is a forward-declared reference to an enumeration, make a
7392 // note of it; we won't actually be introducing the declaration into
7393 // the declaration context.
7394 if (TUK == TUK_Reference)
7395 IsForwardReference = true;
Douglas Gregorc9ea2d52010-06-22 14:26:35 +00007396 }
Douglas Gregord45b93b2009-03-06 18:34:03 +00007397 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00007398
7399 if (EnumUnderlying) {
7400 EnumDecl *ED = cast<EnumDecl>(New);
7401 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
7402 ED->setIntegerTypeSourceInfo(TI);
7403 else
7404 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
7405 ED->setPromotionType(ED->getIntegerType());
7406 }
7407
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00007408 } else {
7409 // struct/union/class
7410
Chris Lattner776fac82007-06-09 00:53:06 +00007411 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
7412 // struct X { int A; } D; D should chain to X.
Douglas Gregor87f54062009-09-15 22:30:29 +00007413 if (getLangOptions().CPlusPlus) {
Ted Kremenek6ddf53e2008-09-05 17:39:33 +00007414 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007415 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007416 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007417
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007418 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor87f54062009-09-15 22:30:29 +00007419 StdBadAlloc = cast<CXXRecordDecl>(New);
7420 } else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007421 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007422 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007423 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007424
John McCall3e11ebe2010-03-15 10:12:16 +00007425 // Maybe add qualifier info.
7426 if (SS.isNotEmpty()) {
Fariborz Jahanian862fac92010-05-14 21:35:02 +00007427 if (SS.isSet()) {
Douglas Gregor14454802011-02-25 02:25:35 +00007428 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara60804e12011-03-18 15:16:37 +00007429 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00007430 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00007431 TemplateParameterLists.size(),
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007432 (TemplateParameterList**) TemplateParameterLists.release());
7433 }
Fariborz Jahanian862fac92010-05-14 21:35:02 +00007434 }
7435 else
7436 Invalid = true;
John McCall3e11ebe2010-03-15 10:12:16 +00007437 }
7438
Daniel Dunbar8804f2e2010-05-27 01:53:40 +00007439 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
7440 // Add alignment attributes if necessary; these attributes are checked when
7441 // the ASTContext lays out the structure.
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007442 //
7443 // It is important for implementing the correct semantics that this
7444 // happen here (in act on tag decl). The #pragma pack stack is
7445 // maintained as a result of parser callbacks which can occur at
7446 // many points during the parsing of a struct declaration (because
7447 // the #pragma tokens are effectively skipped over during the
7448 // parsing of the struct).
Daniel Dunbar8804f2e2010-05-27 01:53:40 +00007449 AddAlignmentAttributesForRecord(RD);
Fariborz Jahanian6b4e26b2011-04-26 17:54:40 +00007450
7451 AddMsStructLayoutForRecord(RD);
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007452 }
7453
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007454 // If this is a specialization of a member class (of a class template),
7455 // check the specialization.
John McCall1f82f242009-11-18 22:49:29 +00007456 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007457 Invalid = true;
Daniel Dunbar8804f2e2010-05-27 01:53:40 +00007458
Douglas Gregordee1be82009-01-17 00:42:38 +00007459 if (Invalid)
7460 New->setInvalidDecl();
7461
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007462 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00007463 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007464
Douglas Gregordee1be82009-01-17 00:42:38 +00007465 // If we're declaring or defining a tag in function prototype scope
7466 // in C, note that this type can only be used within the function.
Douglas Gregor658b9552009-01-09 22:42:13 +00007467 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
7468 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
7469
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007470 // Set the lexical context. If the tag has a C++ scope specifier, the
7471 // lexical context will be different from the semantic context.
Douglas Gregor8761da52009-02-03 00:34:39 +00007472 New->setLexicalDeclContext(CurContext);
Douglas Gregordee1be82009-01-17 00:42:38 +00007473
John McCallaa74a0c2009-08-28 07:59:38 +00007474 // Mark this as a friend decl if applicable.
Francois Pichete37eeba2011-06-01 04:14:20 +00007475 // In Microsoft mode, a friend declaration also acts as a forward
7476 // declaration so we always pass true to setObjectOfFriendDecl to make
7477 // the tag name visible.
John McCallaa74a0c2009-08-28 07:59:38 +00007478 if (TUK == TUK_Friend)
Francois Pichete37eeba2011-06-01 04:14:20 +00007479 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() ||
7480 getLangOptions().Microsoft);
John McCallaa74a0c2009-08-28 07:59:38 +00007481
Anders Carlsson5558ca12009-03-26 01:19:02 +00007482 // Set the access specifier.
John McCalle9eaf8e2010-03-25 21:28:06 +00007483 if (!Invalid && SearchDC->isRecord())
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007484 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor6c2adff2009-03-25 22:00:53 +00007485
John McCall9bb74a52009-07-31 02:45:11 +00007486 if (TUK == TUK_Definition)
Douglas Gregordee1be82009-01-17 00:42:38 +00007487 New->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00007488
Chris Lattner18b19622007-01-22 07:39:13 +00007489 // If this has an identifier, add it to the scope stack.
John McCall2dc078f2009-09-02 00:55:30 +00007490 if (TUK == TUK_Friend) {
John McCallf8bd8612009-09-02 19:32:14 +00007491 // We might be replacing an existing declaration in the lookup tables;
7492 // if so, borrow its access specifier.
7493 if (PrevDecl)
7494 New->setAccess(PrevDecl->getAccess());
7495
Sebastian Redl50c68252010-08-31 00:36:30 +00007496 DeclContext *DC = New->getDeclContext()->getRedeclContext();
John McCalle9eaf8e2010-03-25 21:28:06 +00007497 DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
7498 if (Name) // can be null along some error paths
John McCall2dc078f2009-09-02 00:55:30 +00007499 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
7500 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCall2dc078f2009-09-02 00:55:30 +00007501 } else if (Name) {
Douglas Gregor45a33ec2009-01-12 18:45:55 +00007502 S = getNonFieldDeclScope(S);
Douglas Gregor0bf31402010-10-08 23:50:27 +00007503 PushOnScopeChains(New, S, !IsForwardReference);
7504 if (IsForwardReference)
7505 SearchDC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
7506
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00007507 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007508 CurContext->addDecl(New);
Chris Lattner18b19622007-01-22 07:39:13 +00007509 }
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00007510
Douglas Gregor27821ce2009-07-07 16:35:42 +00007511 // If this is the C FILE type, notify the AST context.
7512 if (IdentifierInfo *II = New->getIdentifier())
7513 if (!New->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00007514 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor27821ce2009-07-07 16:35:42 +00007515 II->isStr("FILE"))
7516 Context.setFILEDecl(New);
Mike Stump11289f42009-09-09 15:08:12 +00007517
Douglas Gregord6ab8742009-05-28 23:31:59 +00007518 OwnedDecl = true;
John McCall48871652010-08-21 09:40:31 +00007519 return New;
Chris Lattner18b19622007-01-22 07:39:13 +00007520}
Chris Lattner1300fb92007-01-23 23:42:53 +00007521
John McCall48871652010-08-21 09:40:31 +00007522void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00007523 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00007524 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregorba41d012010-04-24 16:38:41 +00007525
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007526 // Enter the tag context.
7527 PushDeclContext(S, Tag);
John McCall1c7e6ec2009-12-20 07:58:13 +00007528}
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007529
John McCall48871652010-08-21 09:40:31 +00007530void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson30f29442011-03-25 14:31:08 +00007531 SourceLocation FinalLoc,
John McCall1c7e6ec2009-12-20 07:58:13 +00007532 SourceLocation LBraceLoc) {
7533 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00007534 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007535
John McCall1c7e6ec2009-12-20 07:58:13 +00007536 FieldCollector->StartClass();
7537
7538 if (!Record->getIdentifier())
7539 return;
7540
Anders Carlsson30f29442011-03-25 14:31:08 +00007541 if (FinalLoc.isValid())
7542 Record->addAttr(new (Context) FinalAttr(FinalLoc, Context));
Anders Carlssonfc1eef42011-01-22 17:51:53 +00007543
John McCall1c7e6ec2009-12-20 07:58:13 +00007544 // C++ [class]p2:
7545 // [...] The class-name is also inserted into the scope of the
7546 // class itself; this is known as the injected-class-name. For
7547 // purposes of access checking, the injected-class-name is treated
7548 // as if it were a public member name.
7549 CXXRecordDecl *InjectedClassName
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007550 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
7551 Record->getLocStart(), Record->getLocation(),
John McCall1c7e6ec2009-12-20 07:58:13 +00007552 Record->getIdentifier(),
Argyrios Kyrtzidis470c4542010-10-14 20:14:21 +00007553 /*PrevDecl=*/0,
7554 /*DelayTypeCreation=*/true);
7555 Context.getTypeDeclType(InjectedClassName, Record);
John McCall1c7e6ec2009-12-20 07:58:13 +00007556 InjectedClassName->setImplicit();
7557 InjectedClassName->setAccess(AS_public);
7558 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
7559 InjectedClassName->setDescribedClassTemplate(Template);
7560 PushOnScopeChains(InjectedClassName, S);
7561 assert(InjectedClassName->isInjectedClassName() &&
7562 "Broken injected-class-name");
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007563}
7564
John McCall48871652010-08-21 09:40:31 +00007565void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +00007566 SourceLocation RBraceLoc) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00007567 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00007568 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +00007569 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007570
7571 if (isa<CXXRecordDecl>(Tag))
7572 FieldCollector->FinishClass();
7573
7574 // Exit this scope of this tag's definition.
7575 PopDeclContext();
Douglas Gregor859f0ae2010-01-06 17:00:51 +00007576
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007577 // Notify the consumer that we've defined a tag.
7578 Consumer.HandleTagDeclDefinition(Tag);
7579}
Chris Lattner535b8302008-06-21 19:39:06 +00007580
John McCall48871652010-08-21 09:40:31 +00007581void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCall2ff380a2010-03-17 00:38:33 +00007582 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00007583 TagDecl *Tag = cast<TagDecl>(TagD);
John McCall2ff380a2010-03-17 00:38:33 +00007584 Tag->setInvalidDecl();
7585
John McCall71ba5f22010-03-17 19:25:57 +00007586 // We're undoing ActOnTagStartDefinition here, not
7587 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
7588 // the FieldCollector.
John McCall2ff380a2010-03-17 00:38:33 +00007589
7590 PopDeclContext();
7591}
7592
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007593// Note that FieldName may be null for anonymous bitfields.
Mike Stump11289f42009-09-09 15:08:12 +00007594bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Eli Friedmanc96d4962009-08-15 21:55:26 +00007595 QualType FieldTy, const Expr *BitWidth,
7596 bool *ZeroWidth) {
7597 // Default to true; that shouldn't confuse checks for emptiness
7598 if (ZeroWidth)
7599 *ZeroWidth = true;
7600
Chris Lattner73bf7b42009-03-05 22:45:59 +00007601 // C99 6.7.2.1p4 - verify the field type.
Chris Lattnerd26760a2009-03-05 23:01:03 +00007602 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregorb90df602010-06-16 00:17:44 +00007603 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner73bf7b42009-03-05 22:45:59 +00007604 // Handle incomplete types with specific error.
Douglas Gregor81457422009-03-10 21:58:27 +00007605 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
7606 return true;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007607 if (FieldName)
7608 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
7609 << FieldName << FieldTy << BitWidth->getSourceRange();
7610 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
7611 << FieldTy << BitWidth->getSourceRange();
Douglas Gregora02a72a2010-12-15 23:18:36 +00007612 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
7613 UPPC_BitFieldWidth))
7614 return true;
Douglas Gregor1efa4372009-03-11 18:59:21 +00007615
7616 // If the bit-width is type- or value-dependent, don't try to check
7617 // it now.
7618 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
7619 return false;
7620
Anders Carlsson5df391e2008-12-06 20:33:04 +00007621 llvm::APSInt Value;
7622 if (VerifyIntegerConstantExpression(BitWidth, &Value))
7623 return true;
7624
Eli Friedmanc96d4962009-08-15 21:55:26 +00007625 if (Value != 0 && ZeroWidth)
7626 *ZeroWidth = false;
7627
Chris Lattner81ed6802008-12-12 04:56:04 +00007628 // Zero-width bitfield is ok for anonymous field.
7629 if (Value == 0 && FieldName)
7630 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00007631
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007632 if (Value.isSigned() && Value.isNegative()) {
7633 if (FieldName)
Mike Stump11289f42009-09-09 15:08:12 +00007634 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007635 << FieldName << Value.toString(10);
7636 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
7637 << Value.toString(10);
7638 }
Anders Carlsson5df391e2008-12-06 20:33:04 +00007639
Douglas Gregor1efa4372009-03-11 18:59:21 +00007640 if (!FieldTy->isDependentType()) {
7641 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007642 if (Value.getZExtValue() > TypeSize) {
Anders Carlssond5635fe2010-04-16 15:16:32 +00007643 if (!getLangOptions().CPlusPlus) {
7644 if (FieldName)
7645 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
7646 << FieldName << (unsigned)Value.getZExtValue()
7647 << (unsigned)TypeSize;
7648
7649 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
7650 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
7651 }
7652
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007653 if (FieldName)
Anders Carlssond5635fe2010-04-16 15:16:32 +00007654 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
7655 << FieldName << (unsigned)Value.getZExtValue()
7656 << (unsigned)TypeSize;
7657 else
7658 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
7659 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007660 }
Douglas Gregor1efa4372009-03-11 18:59:21 +00007661 }
Anders Carlsson5df391e2008-12-06 20:33:04 +00007662
7663 return false;
7664}
7665
Richard Smith938f40b2011-06-11 17:19:42 +00007666/// ActOnField - Each field of a C struct/union is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +00007667/// to create a FieldDecl object for it.
Richard Smith938f40b2011-06-11 17:19:42 +00007668Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
7669 Declarator &D, ExprTy *BitfieldWidth) {
John McCall48871652010-08-21 09:40:31 +00007670 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattner83f095c2009-03-28 19:18:32 +00007671 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smith938f40b2011-06-11 17:19:42 +00007672 /*HasInit=*/false, AS_public);
John McCall48871652010-08-21 09:40:31 +00007673 return Res;
Chris Lattner73bf7b42009-03-05 22:45:59 +00007674}
7675
7676/// HandleField - Analyze a field of a C struct or a C++ data member.
7677///
7678FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
7679 SourceLocation DeclStart,
Richard Smith938f40b2011-06-11 17:19:42 +00007680 Declarator &D, Expr *BitWidth, bool HasInit,
Douglas Gregor4261e4c2009-03-11 20:50:30 +00007681 AccessSpecifier AS) {
Chris Lattner1300fb92007-01-23 23:42:53 +00007682 IdentifierInfo *II = D.getIdentifier();
Chris Lattner1300fb92007-01-23 23:42:53 +00007683 SourceLocation Loc = DeclStart;
7684 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +00007685
John McCall8cb7bdf2010-06-04 23:28:52 +00007686 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
7687 QualType T = TInfo->getType();
Douglas Gregora02a72a2010-12-15 23:18:36 +00007688 if (getLangOptions().CPlusPlus) {
Douglas Gregor1efa4372009-03-11 18:59:21 +00007689 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00007690
Douglas Gregora02a72a2010-12-15 23:18:36 +00007691 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
7692 UPPC_DataMemberType)) {
7693 D.setInvalidType();
7694 T = Context.IntTy;
7695 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
7696 }
7697 }
7698
Eli Friedman574c7452009-04-07 19:37:57 +00007699 DiagnoseFunctionSpecifiers(D);
7700
Eli Friedmand5c0eed2009-04-19 20:27:55 +00007701 if (D.getDeclSpec().isThreadSpecified())
7702 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
Douglas Gregor2c7d9292010-08-30 14:32:14 +00007703
7704 // Check to see if this name was declared as a member previously
7705 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
7706 LookupName(Previous, S);
7707 assert((Previous.empty() || Previous.isOverloadedResult() ||
7708 Previous.isSingleResult())
7709 && "Lookup of member name should be either overloaded, single or null");
Eli Friedmand5c0eed2009-04-19 20:27:55 +00007710
Douglas Gregor2c7d9292010-08-30 14:32:14 +00007711 // If the name is overloaded then get any declaration else get the single result
7712 NamedDecl *PrevDecl = Previous.isOverloadedResult() ?
7713 Previous.getRepresentativeDecl() : Previous.getAsSingle<NamedDecl>();
Douglas Gregorf187420f2009-06-17 23:37:01 +00007714
7715 if (PrevDecl && PrevDecl->isTemplateParameter()) {
7716 // Maybe we will complain about the shadowed template parameter.
7717 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
7718 // Just pretend that we didn't see the previous declaration.
7719 PrevDecl = 0;
7720 }
7721
Douglas Gregor1efa4372009-03-11 18:59:21 +00007722 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
7723 PrevDecl = 0;
7724
Steve Naroff5ec6ff72009-07-14 14:58:18 +00007725 bool Mutable
7726 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
7727 SourceLocation TSSL = D.getSourceRange().getBegin();
7728 FieldDecl *NewFD
Richard Smith938f40b2011-06-11 17:19:42 +00007729 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, HasInit,
7730 TSSL, AS, PrevDecl, &D);
Rafael Espindola568586f2010-03-21 22:56:43 +00007731
7732 if (NewFD->isInvalidDecl())
7733 Record->setInvalidDecl();
7734
Douglas Gregor1efa4372009-03-11 18:59:21 +00007735 if (NewFD->isInvalidDecl() && PrevDecl) {
7736 // Don't introduce NewFD into scope; there's already something
7737 // with the same name in the same scope.
7738 } else if (II) {
7739 PushOnScopeChains(NewFD, S);
7740 } else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007741 Record->addDecl(NewFD);
Douglas Gregor1efa4372009-03-11 18:59:21 +00007742
7743 return NewFD;
7744}
7745
7746/// \brief Build a new FieldDecl and check its well-formedness.
7747///
7748/// This routine builds a new FieldDecl given the fields name, type,
7749/// record, etc. \p PrevDecl should refer to any previous declaration
7750/// with the same name and in the same scope as the field to be
7751/// created.
7752///
7753/// \returns a new FieldDecl.
7754///
Mike Stump11289f42009-09-09 15:08:12 +00007755/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00007756FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCallbcd03502009-12-07 02:54:59 +00007757 TypeSourceInfo *TInfo,
Douglas Gregor1efa4372009-03-11 18:59:21 +00007758 RecordDecl *Record, SourceLocation Loc,
Richard Smith938f40b2011-06-11 17:19:42 +00007759 bool Mutable, Expr *BitWidth, bool HasInit,
Steve Naroff5ec6ff72009-07-14 14:58:18 +00007760 SourceLocation TSSL,
Douglas Gregor4261e4c2009-03-11 20:50:30 +00007761 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor1efa4372009-03-11 18:59:21 +00007762 Declarator *D) {
7763 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Narofff93b6722007-08-28 20:14:24 +00007764 bool InvalidDecl = false;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007765 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redlbaad4e72009-01-05 20:52:13 +00007766
Douglas Gregor1efa4372009-03-11 18:59:21 +00007767 // If we receive a broken type, recover by assuming 'int' and
7768 // marking this declaration as invalid.
7769 if (T.isNull()) {
7770 InvalidDecl = true;
7771 T = Context.IntTy;
7772 }
7773
Eli Friedmand0e8de22009-12-07 00:22:08 +00007774 QualType EltTy = Context.getBaseElementType(T);
7775 if (!EltTy->isDependentType() &&
John McCall2677e102010-08-16 23:42:35 +00007776 RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
7777 // Fields of incomplete type force their record to be invalid.
7778 Record->setInvalidDecl();
Eli Friedmand0e8de22009-12-07 00:22:08 +00007779 InvalidDecl = true;
John McCall2677e102010-08-16 23:42:35 +00007780 }
Eli Friedmand0e8de22009-12-07 00:22:08 +00007781
Steve Naroff8eeeb132007-05-08 21:09:37 +00007782 // C99 6.7.2.1p8: A member of a structure or union may have any type other
7783 // than a variably modified type.
Eli Friedmand0e8de22009-12-07 00:22:08 +00007784 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00007785 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00007786 llvm::APSInt Oversized;
Eli Friedmana3b1d032009-02-21 00:44:51 +00007787 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00007788 SizeIsNegative,
7789 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00007790 if (!FixedTy.isNull()) {
7791 Diag(Loc, diag::warn_illegal_constant_array_size);
7792 T = FixedTy;
7793 } else {
7794 if (SizeIsNegative)
7795 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00007796 else if (Oversized.getBoolValue())
7797 Diag(Loc, diag::err_array_too_large)
7798 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00007799 else
7800 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00007801 InvalidDecl = true;
7802 }
Steve Naroff8eeeb132007-05-08 21:09:37 +00007803 }
Mike Stump11289f42009-09-09 15:08:12 +00007804
Anders Carlsson576cc6f2009-03-22 20:18:17 +00007805 // Fields can not have abstract class types
Eli Friedmand0e8de22009-12-07 00:22:08 +00007806 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
7807 diag::err_abstract_type_in_decl,
7808 AbstractFieldType))
Anders Carlsson576cc6f2009-03-22 20:18:17 +00007809 InvalidDecl = true;
Mike Stump11289f42009-09-09 15:08:12 +00007810
Eli Friedmanc96d4962009-08-15 21:55:26 +00007811 bool ZeroWidth = false;
Douglas Gregor1efa4372009-03-11 18:59:21 +00007812 // If this is declared as a bit-field, check the bit-field.
Eli Friedmand0e8de22009-12-07 00:22:08 +00007813 if (!InvalidDecl && BitWidth &&
7814 VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
Douglas Gregor1efa4372009-03-11 18:59:21 +00007815 InvalidDecl = true;
Douglas Gregor1efa4372009-03-11 18:59:21 +00007816 BitWidth = 0;
Eli Friedmanc96d4962009-08-15 21:55:26 +00007817 ZeroWidth = false;
Anders Carlsson5df391e2008-12-06 20:33:04 +00007818 }
Mike Stump11289f42009-09-09 15:08:12 +00007819
John McCallb1cd7da2010-06-04 08:34:12 +00007820 // Check that 'mutable' is consistent with the type of the declaration.
7821 if (!InvalidDecl && Mutable) {
7822 unsigned DiagID = 0;
7823 if (T->isReferenceType())
7824 DiagID = diag::err_mutable_reference;
7825 else if (T.isConstQualified())
7826 DiagID = diag::err_mutable_const;
7827
7828 if (DiagID) {
7829 SourceLocation ErrLoc = Loc;
7830 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
7831 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
7832 Diag(ErrLoc, DiagID);
7833 Mutable = false;
7834 InvalidDecl = true;
7835 }
7836 }
7837
Abramo Bagnaradff19302011-03-08 08:55:46 +00007838 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00007839 BitWidth, Mutable, HasInit);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007840 if (InvalidDecl)
7841 NewFD->setInvalidDecl();
Douglas Gregor91f84212008-12-11 16:49:14 +00007842
Douglas Gregor1efa4372009-03-11 18:59:21 +00007843 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
7844 Diag(Loc, diag::err_duplicate_member) << II;
7845 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
7846 NewFD->setInvalidDecl();
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007847 }
7848
John McCall67da35c2010-02-04 22:26:26 +00007849 if (!InvalidDecl && getLangOptions().CPlusPlus) {
Anders Carlsson2ceb3472010-11-07 19:13:55 +00007850 if (Record->isUnion()) {
7851 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
7852 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
7853 if (RDecl->getDefinition()) {
7854 // C++ [class.union]p1: An object of a class with a non-trivial
7855 // constructor, a non-trivial copy constructor, a non-trivial
7856 // destructor, or a non-trivial copy assignment operator
7857 // cannot be a member of a union, nor can an array of such
7858 // objects.
Alexis Hunt97ab5542011-05-16 22:41:40 +00007859 if (!getLangOptions().CPlusPlus0x && CheckNontrivialField(NewFD))
Anders Carlsson2ceb3472010-11-07 19:13:55 +00007860 NewFD->setInvalidDecl();
7861 }
7862 }
7863
7864 // C++ [class.union]p1: If a union contains a member of reference type,
7865 // the program is ill-formed.
7866 if (EltTy->isReferenceType()) {
7867 Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
7868 << NewFD->getDeclName() << EltTy;
7869 NewFD->setInvalidDecl();
Douglas Gregor8a273912009-07-22 18:25:24 +00007870 }
7871 }
7872 }
7873
Douglas Gregor1efa4372009-03-11 18:59:21 +00007874 // FIXME: We need to pass in the attributes given an AST
7875 // representation, not a parser representation.
7876 if (D)
Douglas Gregor758a8692009-06-17 21:51:59 +00007877 // FIXME: What to pass instead of TUScope?
7878 ProcessDeclAttributes(TUScope, NewFD, *D);
Douglas Gregor1efa4372009-03-11 18:59:21 +00007879
John McCall31168b02011-06-15 23:02:42 +00007880 // In auto-retain/release, infer strong retension for fields of
7881 // retainable type.
7882 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
7883 NewFD->setInvalidDecl();
7884
Fariborz Jahaniand29fecd2009-02-19 00:22:47 +00007885 if (T.isObjCGCWeak())
Fariborz Jahaniand35c7922009-02-18 18:14:41 +00007886 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlsson28e71082008-02-16 00:29:18 +00007887
Douglas Gregor4261e4c2009-03-11 20:50:30 +00007888 NewFD->setAccess(AS);
Steve Narofff93b6722007-08-28 20:14:24 +00007889 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +00007890}
7891
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00007892bool Sema::CheckNontrivialField(FieldDecl *FD) {
7893 assert(FD);
7894 assert(getLangOptions().CPlusPlus && "valid check only for C++");
7895
7896 if (FD->isInvalidDecl())
7897 return true;
7898
7899 QualType EltTy = Context.getBaseElementType(FD->getType());
7900 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
7901 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
7902 if (RDecl->getDefinition()) {
7903 // We check for copy constructors before constructors
7904 // because otherwise we'll never get complaints about
7905 // copy constructors.
7906
7907 CXXSpecialMember member = CXXInvalid;
7908 if (!RDecl->hasTrivialCopyConstructor())
7909 member = CXXCopyConstructor;
Alexis Huntf479f1b2011-05-09 18:22:59 +00007910 else if (!RDecl->hasTrivialDefaultConstructor())
Alexis Hunt80f00ff2011-05-10 19:08:14 +00007911 member = CXXDefaultConstructor;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00007912 else if (!RDecl->hasTrivialCopyAssignment())
7913 member = CXXCopyAssignment;
7914 else if (!RDecl->hasTrivialDestructor())
7915 member = CXXDestructor;
7916
7917 if (member != CXXInvalid) {
John McCall31168b02011-06-15 23:02:42 +00007918 if (getLangOptions().ObjCAutoRefCount && RDecl->hasObjectMember()) {
7919 // Objective-C++ ARC: it is an error to have a non-trivial field of
7920 // a union. However, system headers in Objective-C programs
7921 // occasionally have Objective-C lifetime objects within unions,
7922 // and rather than cause the program to fail, we make those
7923 // members unavailable.
7924 SourceLocation Loc = FD->getLocation();
7925 if (getSourceManager().isInSystemHeader(Loc)) {
7926 if (!FD->hasAttr<UnavailableAttr>())
7927 FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00007928 "this system field has retaining ownership"));
John McCall31168b02011-06-15 23:02:42 +00007929 return false;
7930 }
7931 }
7932
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00007933 Diag(FD->getLocation(), diag::err_illegal_union_or_anon_struct_member)
7934 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
7935 DiagnoseNontrivial(RT, member);
7936 return true;
7937 }
7938 }
7939 }
7940
7941 return false;
7942}
7943
Douglas Gregor8a273912009-07-22 18:25:24 +00007944/// DiagnoseNontrivial - Given that a class has a non-trivial
7945/// special member, figure out why.
7946void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
7947 QualType QT(T, 0U);
7948 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
7949
7950 // Check whether the member was user-declared.
7951 switch (member) {
Douglas Gregorfceea362010-04-22 14:36:26 +00007952 case CXXInvalid:
7953 break;
7954
Alexis Hunt80f00ff2011-05-10 19:08:14 +00007955 case CXXDefaultConstructor:
Douglas Gregor8a273912009-07-22 18:25:24 +00007956 if (RD->hasUserDeclaredConstructor()) {
7957 typedef CXXRecordDecl::ctor_iterator ctor_iter;
Sebastian Redle24b1622009-10-25 22:31:45 +00007958 for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
7959 const FunctionDecl *body = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007960 ci->hasBody(body);
Anders Carlssonb7229932010-04-20 23:32:58 +00007961 if (!body || !cast<CXXConstructorDecl>(body)->isImplicitlyDefined()) {
Douglas Gregor8a273912009-07-22 18:25:24 +00007962 SourceLocation CtorLoc = ci->getLocation();
7963 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
7964 return;
7965 }
Sebastian Redle24b1622009-10-25 22:31:45 +00007966 }
Douglas Gregor8a273912009-07-22 18:25:24 +00007967
7968 assert(0 && "found no user-declared constructors");
7969 return;
7970 }
7971 break;
7972
7973 case CXXCopyConstructor:
7974 if (RD->hasUserDeclaredCopyConstructor()) {
7975 SourceLocation CtorLoc =
Alexis Huntfcaeae42011-05-25 20:50:04 +00007976 RD->getCopyConstructor(0)->getLocation();
7977 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
7978 return;
7979 }
7980 break;
7981
7982 case CXXMoveConstructor:
7983 if (RD->hasUserDeclaredMoveConstructor()) {
7984 SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation();
Douglas Gregor8a273912009-07-22 18:25:24 +00007985 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
7986 return;
7987 }
7988 break;
7989
7990 case CXXCopyAssignment:
7991 if (RD->hasUserDeclaredCopyAssignment()) {
7992 // FIXME: this should use the location of the copy
7993 // assignment, not the type.
7994 SourceLocation TyLoc = RD->getSourceRange().getBegin();
7995 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
7996 return;
7997 }
7998 break;
7999
Alexis Huntfcaeae42011-05-25 20:50:04 +00008000 case CXXMoveAssignment:
8001 if (RD->hasUserDeclaredMoveAssignment()) {
8002 SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation();
8003 Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member;
8004 return;
8005 }
8006 break;
8007
Douglas Gregor8a273912009-07-22 18:25:24 +00008008 case CXXDestructor:
8009 if (RD->hasUserDeclaredDestructor()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00008010 SourceLocation DtorLoc = LookupDestructor(RD)->getLocation();
Douglas Gregor8a273912009-07-22 18:25:24 +00008011 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
8012 return;
8013 }
8014 break;
8015 }
8016
8017 typedef CXXRecordDecl::base_class_iterator base_iter;
8018
8019 // Virtual bases and members inhibit trivial copying/construction,
8020 // but not trivial destruction.
8021 if (member != CXXDestructor) {
8022 // Check for virtual bases. vbases includes indirect virtual bases,
8023 // so we just iterate through the direct bases.
8024 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
8025 if (bi->isVirtual()) {
8026 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
8027 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
8028 return;
8029 }
8030
8031 // Check for virtual methods.
8032 typedef CXXRecordDecl::method_iterator meth_iter;
8033 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
8034 ++mi) {
8035 if (mi->isVirtual()) {
8036 SourceLocation MLoc = mi->getSourceRange().getBegin();
8037 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
8038 return;
8039 }
8040 }
8041 }
Mike Stump11289f42009-09-09 15:08:12 +00008042
Douglas Gregor8a273912009-07-22 18:25:24 +00008043 bool (CXXRecordDecl::*hasTrivial)() const;
8044 switch (member) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008045 case CXXDefaultConstructor:
Alexis Huntf479f1b2011-05-09 18:22:59 +00008046 hasTrivial = &CXXRecordDecl::hasTrivialDefaultConstructor; break;
Douglas Gregor8a273912009-07-22 18:25:24 +00008047 case CXXCopyConstructor:
8048 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
8049 case CXXCopyAssignment:
8050 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
8051 case CXXDestructor:
8052 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
8053 default:
8054 assert(0 && "unexpected special member"); return;
8055 }
8056
8057 // Check for nontrivial bases (and recurse).
8058 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008059 const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
Sebastian Redl1054fae2009-10-25 17:03:50 +00008060 assert(BaseRT && "Don't know how to handle dependent bases");
Douglas Gregor8a273912009-07-22 18:25:24 +00008061 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
8062 if (!(BaseRecTy->*hasTrivial)()) {
8063 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
8064 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
8065 DiagnoseNontrivial(BaseRT, member);
8066 return;
8067 }
8068 }
Mike Stump11289f42009-09-09 15:08:12 +00008069
Douglas Gregor8a273912009-07-22 18:25:24 +00008070 // Check for nontrivial members (and recurse).
8071 typedef RecordDecl::field_iterator field_iter;
8072 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
8073 ++fi) {
Douglas Gregor79f83ed2009-07-23 23:49:00 +00008074 QualType EltTy = Context.getBaseElementType((*fi)->getType());
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008075 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
Douglas Gregor8a273912009-07-22 18:25:24 +00008076 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
8077
8078 if (!(EltRD->*hasTrivial)()) {
8079 SourceLocation FLoc = (*fi)->getLocation();
8080 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
8081 DiagnoseNontrivial(EltRT, member);
8082 return;
8083 }
8084 }
John McCall31168b02011-06-15 23:02:42 +00008085
8086 if (EltTy->isObjCLifetimeType()) {
8087 switch (EltTy.getObjCLifetime()) {
8088 case Qualifiers::OCL_None:
8089 case Qualifiers::OCL_ExplicitNone:
8090 break;
8091
8092 case Qualifiers::OCL_Autoreleasing:
8093 case Qualifiers::OCL_Weak:
8094 case Qualifiers::OCL_Strong:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008095 Diag((*fi)->getLocation(), diag::note_nontrivial_objc_ownership)
John McCall31168b02011-06-15 23:02:42 +00008096 << QT << EltTy.getObjCLifetime();
8097 return;
8098 }
8099 }
Douglas Gregor8a273912009-07-22 18:25:24 +00008100 }
8101
8102 assert(0 && "found no explanation for non-trivial member");
8103}
8104
Mike Stump11289f42009-09-09 15:08:12 +00008105/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00008106/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00008107static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00008108TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +00008109 switch (ivarVisibility) {
Chris Lattner79ef8432008-10-12 00:28:42 +00008110 default: assert(0 && "Unknown visitibility kind");
8111 case tok::objc_private: return ObjCIvarDecl::Private;
8112 case tok::objc_public: return ObjCIvarDecl::Public;
8113 case tok::objc_protected: return ObjCIvarDecl::Protected;
8114 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroff2e688fd2007-09-14 23:09:53 +00008115 }
8116}
8117
Mike Stump11289f42009-09-09 15:08:12 +00008118/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian96376742008-04-11 16:55:42 +00008119/// in order to create an IvarDecl object for it.
John McCall48871652010-08-21 09:40:31 +00008120Decl *Sema::ActOnIvar(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00008121 SourceLocation DeclStart,
John McCall48871652010-08-21 09:40:31 +00008122 Decl *IntfDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00008123 Declarator &D, ExprTy *BitfieldWidth,
8124 tok::ObjCKeywordKind Visibility) {
Mike Stump11289f42009-09-09 15:08:12 +00008125
Fariborz Jahaniande615832008-04-10 23:32:45 +00008126 IdentifierInfo *II = D.getIdentifier();
8127 Expr *BitWidth = (Expr*)BitfieldWidth;
8128 SourceLocation Loc = DeclStart;
8129 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +00008130
Fariborz Jahaniande615832008-04-10 23:32:45 +00008131 // FIXME: Unnamed fields can be handled in various different ways, for
8132 // example, unnamed unions inject all members into the struct namespace!
Mike Stump11289f42009-09-09 15:08:12 +00008133
John McCall8cb7bdf2010-06-04 23:28:52 +00008134 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8135 QualType T = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00008136
Fariborz Jahaniande615832008-04-10 23:32:45 +00008137 if (BitWidth) {
Steve Naroff17b2f5d2009-02-20 17:57:11 +00008138 // 6.7.2.1p3, 6.7.2.1p4
Chris Lattner73bf7b42009-03-05 22:45:59 +00008139 if (VerifyBitField(Loc, II, T, BitWidth)) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008140 D.setInvalidType();
Chris Lattner73bf7b42009-03-05 22:45:59 +00008141 BitWidth = 0;
8142 }
Fariborz Jahaniande615832008-04-10 23:32:45 +00008143 } else {
8144 // Not a bitfield.
Mike Stump11289f42009-09-09 15:08:12 +00008145
Fariborz Jahaniande615832008-04-10 23:32:45 +00008146 // validate II.
Mike Stump11289f42009-09-09 15:08:12 +00008147
Fariborz Jahaniande615832008-04-10 23:32:45 +00008148 }
Fariborz Jahanian0103d672010-04-26 22:07:03 +00008149 if (T->isReferenceType()) {
8150 Diag(Loc, diag::err_ivar_reference_type);
8151 D.setInvalidType();
8152 }
Fariborz Jahaniande615832008-04-10 23:32:45 +00008153 // C99 6.7.2.1p8: A member of a structure or union may have any type other
8154 // than a variably modified type.
Fariborz Jahanian0103d672010-04-26 22:07:03 +00008155 else if (T->isVariablyModifiedType()) {
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +00008156 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008157 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +00008158 }
Mike Stump11289f42009-09-09 15:08:12 +00008159
Ted Kremenek73295fa2008-07-23 18:04:17 +00008160 // Get the visibility (access control) for this ivar.
Mike Stump11289f42009-09-09 15:08:12 +00008161 ObjCIvarDecl::AccessControl ac =
Ted Kremenek73295fa2008-07-23 18:04:17 +00008162 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
8163 : ObjCIvarDecl::None;
Fariborz Jahanian68453832009-06-05 18:16:35 +00008164 // Must set ivar's DeclContext to its enclosing interface.
John McCall48871652010-08-21 09:40:31 +00008165 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(IntfDecl);
Daniel Dunbar229385c2010-04-02 18:29:09 +00008166 ObjCContainerDecl *EnclosingContext;
Mike Stump11289f42009-09-09 15:08:12 +00008167 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian68453832009-06-05 18:16:35 +00008168 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +00008169 if (!LangOpts.ObjCNonFragileABI2) {
Fariborz Jahanian68453832009-06-05 18:16:35 +00008170 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +00008171 EnclosingContext = IMPDecl->getClassInterface();
8172 assert(EnclosingContext && "Implementation has no class interface!");
8173 }
8174 else
8175 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00008176 } else {
8177 if (ObjCCategoryDecl *CDecl =
8178 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
8179 if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) {
8180 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCall48871652010-08-21 09:40:31 +00008181 return 0;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00008182 }
8183 }
Daniel Dunbar229385c2010-04-02 18:29:09 +00008184 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00008185 }
Mike Stump11289f42009-09-09 15:08:12 +00008186
Ted Kremenek73295fa2008-07-23 18:04:17 +00008187 // Construct the decl.
Abramo Bagnaradff19302011-03-08 08:55:46 +00008188 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
8189 DeclStart, Loc, II, T,
John McCallbcd03502009-12-07 02:54:59 +00008190 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump11289f42009-09-09 15:08:12 +00008191
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008192 if (II) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00008193 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall5cebab12009-11-18 07:57:50 +00008194 ForRedeclaration);
Fariborz Jahanian68453832009-06-05 18:16:35 +00008195 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008196 && !isa<TagDecl>(PrevDecl)) {
8197 Diag(Loc, diag::err_duplicate_member) << II;
8198 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
8199 NewID->setInvalidDecl();
8200 }
8201 }
8202
Ted Kremenek73295fa2008-07-23 18:04:17 +00008203 // Process attributes attached to the ivar.
Douglas Gregor758a8692009-06-17 21:51:59 +00008204 ProcessDeclAttributes(S, NewID, D);
Mike Stump11289f42009-09-09 15:08:12 +00008205
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008206 if (D.isInvalidType())
Fariborz Jahaniande615832008-04-10 23:32:45 +00008207 NewID->setInvalidDecl();
Ted Kremenek73295fa2008-07-23 18:04:17 +00008208
John McCall31168b02011-06-15 23:02:42 +00008209 // In ARC, infer 'retaining' for ivars of retainable type.
8210 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
8211 NewID->setInvalidDecl();
8212
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008213 if (II) {
8214 // FIXME: When interfaces are DeclContexts, we'll need to add
8215 // these to the interface.
John McCall48871652010-08-21 09:40:31 +00008216 S->AddDecl(NewID);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008217 IdResolver.AddDecl(NewID);
8218 }
8219
John McCall48871652010-08-21 09:40:31 +00008220 return NewID;
Fariborz Jahaniande615832008-04-10 23:32:45 +00008221}
8222
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00008223/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
8224/// class and class extensions. For every class @interface and class
8225/// extension @interface, if the last ivar is a bitfield of any type,
8226/// then add an implicit `char :0` ivar to the end of that interface.
8227void Sema::ActOnLastBitfield(SourceLocation DeclLoc, Decl *EnclosingDecl,
8228 llvm::SmallVectorImpl<Decl *> &AllIvarDecls) {
8229 if (!LangOpts.ObjCNonFragileABI2 || AllIvarDecls.empty())
8230 return;
8231
8232 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
8233 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
8234
8235 if (!Ivar->isBitField())
8236 return;
8237 uint64_t BitFieldSize =
8238 Ivar->getBitWidth()->EvaluateAsInt(Context).getZExtValue();
8239 if (BitFieldSize == 0)
8240 return;
8241 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl);
8242 if (!ID) {
8243 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
8244 if (!CD->IsClassExtension())
8245 return;
8246 }
8247 // No need to add this to end of @implementation.
8248 else
8249 return;
8250 }
8251 // All conditions are met. Add a new bitfield to the tail end of ivars.
8252 llvm::APInt Zero(Context.getTypeSize(Context.CharTy), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00008253 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.CharTy, DeclLoc);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00008254
8255 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(EnclosingDecl),
Abramo Bagnaradff19302011-03-08 08:55:46 +00008256 DeclLoc, DeclLoc, 0,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00008257 Context.CharTy,
8258 Context.CreateTypeSourceInfo(Context.CharTy),
8259 ObjCIvarDecl::Private, BW,
8260 true);
8261 AllIvarDecls.push_back(Ivar);
8262}
8263
Fariborz Jahanian343f7092007-09-29 00:54:24 +00008264void Sema::ActOnFields(Scope* S,
John McCall48871652010-08-21 09:40:31 +00008265 SourceLocation RecLoc, Decl *EnclosingDecl,
8266 Decl **Fields, unsigned NumFields,
Daniel Dunbar15619c72008-10-03 02:03:53 +00008267 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar325601a2008-10-03 17:33:35 +00008268 AttributeList *Attr) {
Steve Naroffdb47ee22007-09-14 22:20:54 +00008269 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump11289f42009-09-09 15:08:12 +00008270
Chris Lattnerd13b8b52009-02-23 22:00:08 +00008271 // If the decl this is being inserted into is invalid, then it may be a
8272 // redeclaration or some other bogus case. Don't try to add fields to it.
8273 if (EnclosingDecl->isInvalidDecl()) {
8274 // FIXME: Deallocate fields?
8275 return;
8276 }
8277
Mike Stump11289f42009-09-09 15:08:12 +00008278
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00008279 // Verify that all the fields are okay.
Chris Lattner82625602007-01-24 02:26:21 +00008280 unsigned NumNamedMembers = 0;
Chris Lattner23b7eb62007-06-15 23:05:46 +00008281 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorf4d33272009-01-07 19:46:03 +00008282
Chris Lattnerd13b8b52009-02-23 22:00:08 +00008283 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
John McCall31168b02011-06-15 23:02:42 +00008284 bool ARCErrReported = false;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00008285 for (unsigned i = 0; i != NumFields; ++i) {
John McCall48871652010-08-21 09:40:31 +00008286 FieldDecl *FD = cast<FieldDecl>(Fields[i]);
Mike Stump11289f42009-09-09 15:08:12 +00008287
Chris Lattner720a0542007-01-25 00:44:24 +00008288 // Get the type for the field.
John McCall424cec92011-01-19 06:33:43 +00008289 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorf4d33272009-01-07 19:46:03 +00008290
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008291 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00008292 // Remember all fields written by the user.
8293 RecFields.push_back(FD);
8294 }
Mike Stump11289f42009-09-09 15:08:12 +00008295
Chris Lattner73bf7b42009-03-05 22:45:59 +00008296 // If the field is already invalid for some reason, don't emit more
8297 // diagnostics about it.
Eli Friedmand0e8de22009-12-07 00:22:08 +00008298 if (FD->isInvalidDecl()) {
8299 EnclosingDecl->setInvalidDecl();
Chris Lattner73bf7b42009-03-05 22:45:59 +00008300 continue;
Eli Friedmand0e8de22009-12-07 00:22:08 +00008301 }
Mike Stump11289f42009-09-09 15:08:12 +00008302
Douglas Gregorac1fb652009-03-24 19:52:54 +00008303 // C99 6.7.2.1p2:
8304 // A structure or union shall not contain a member with
8305 // incomplete or function type (hence, a structure shall not
8306 // contain an instance of itself, but may contain a pointer to
8307 // an instance of itself), except that the last member of a
8308 // structure with more than one named member may have incomplete
8309 // array type; such a structure (and any union containing,
8310 // possibly recursively, a member that is such a structure)
8311 // shall not be a member of a structure or an element of an
8312 // array.
Chris Lattner0fd893e2007-07-31 21:33:24 +00008313 if (FDTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00008314 // Field declared as a function.
Chris Lattner651d42d2008-11-20 06:38:18 +00008315 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00008316 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +00008317 FD->setInvalidDecl();
8318 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00008319 continue;
Francois Pichetf657b632010-09-15 00:14:08 +00008320 } else if (FDTy->isIncompleteArrayType() && Record &&
8321 ((i == NumFields - 1 && !Record->isUnion()) ||
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00008322 ((getLangOptions().Microsoft || getLangOptions().CPlusPlus) &&
Francois Pichetf657b632010-09-15 00:14:08 +00008323 (i == NumFields - 1 || Record->isUnion())))) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00008324 // Flexible array member.
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00008325 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichetf657b632010-09-15 00:14:08 +00008326 // It will accept flexible array in union and also
Anders Carlsson0ea10472010-10-17 23:36:12 +00008327 // as the sole element of a struct/class.
Francois Pichetf657b632010-09-15 00:14:08 +00008328 if (getLangOptions().Microsoft) {
8329 if (Record->isUnion())
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00008330 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
Francois Pichetf657b632010-09-15 00:14:08 +00008331 << FD->getDeclName();
8332 else if (NumFields == 1)
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00008333 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
Francois Pichetf657b632010-09-15 00:14:08 +00008334 << FD->getDeclName() << Record->getTagKind();
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00008335 } else if (getLangOptions().CPlusPlus) {
8336 if (Record->isUnion())
8337 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
8338 << FD->getDeclName();
8339 else if (NumFields == 1)
8340 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
8341 << FD->getDeclName() << Record->getTagKind();
8342 } else if (NumNamedMembers < 1) {
Chris Lattner651d42d2008-11-20 06:38:18 +00008343 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00008344 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +00008345 FD->setInvalidDecl();
8346 EnclosingDecl->setInvalidDecl();
Chris Lattner82625602007-01-24 02:26:21 +00008347 continue;
8348 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00008349 if (!FD->getType()->isDependentType() &&
John McCall31168b02011-06-15 23:02:42 +00008350 !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00008351 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
Fariborz Jahanianb0e28472010-05-26 20:46:24 +00008352 << FD->getDeclName() << FD->getType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00008353 FD->setInvalidDecl();
8354 EnclosingDecl->setInvalidDecl();
8355 continue;
8356 }
Chris Lattner720a0542007-01-25 00:44:24 +00008357 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00008358 if (Record)
8359 Record->setHasFlexibleArrayMember(true);
Douglas Gregorac1fb652009-03-24 19:52:54 +00008360 } else if (!FDTy->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00008361 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregorac1fb652009-03-24 19:52:54 +00008362 diag::err_field_incomplete)) {
8363 // Incomplete type
8364 FD->setInvalidDecl();
8365 EnclosingDecl->setInvalidDecl();
8366 continue;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008367 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Chris Lattner720a0542007-01-25 00:44:24 +00008368 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
8369 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00008370 if (Record && Record->isUnion()) {
Chris Lattner41943152007-01-25 04:52:46 +00008371 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00008372 } else {
8373 // If this is a struct/class and this is not the last element, reject
8374 // it. Note that GCC supports variable sized arrays in the middle of
8375 // structures.
Douglas Gregor3e06dbf2009-03-06 23:41:27 +00008376 if (i != NumFields-1)
8377 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattnerb28fe9e2009-04-25 18:52:45 +00008378 << FD->getDeclName() << FD->getType();
Douglas Gregor3e06dbf2009-03-06 23:41:27 +00008379 else {
8380 // We support flexible arrays at the end of structs in
8381 // other structs as an extension.
8382 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
8383 << FD->getDeclName();
8384 if (Record)
8385 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00008386 }
Chris Lattner720a0542007-01-25 00:44:24 +00008387 }
8388 }
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00008389 if (Record && FDTTy->getDecl()->hasObjectMember())
8390 Record->setHasObjectMember(true);
John McCall8b07ec22010-05-15 11:32:37 +00008391 } else if (FDTy->isObjCObjectType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00008392 /// A field cannot be an Objective-c object
Steve Naroff32606412009-02-20 22:59:16 +00008393 Diag(FD->getLocation(), diag::err_statically_allocated_object);
Fariborz Jahanianecfe4f12007-10-12 22:10:42 +00008394 FD->setInvalidDecl();
8395 EnclosingDecl->setInvalidDecl();
8396 continue;
John McCall31168b02011-06-15 23:02:42 +00008397 }
8398 else if (!getLangOptions().CPlusPlus) {
8399 if (getLangOptions().ObjCAutoRefCount && Record && !ARCErrReported) {
8400 // It's an error in ARC if a field has lifetime.
8401 // We don't want to report this in a system header, though,
8402 // so we just make the field unavailable.
8403 // FIXME: that's really not sufficient; we need to make the type
8404 // itself invalid to, say, initialize or copy.
8405 QualType T = FD->getType();
8406 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
8407 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
8408 SourceLocation loc = FD->getLocation();
8409 if (getSourceManager().isInSystemHeader(loc)) {
8410 if (!FD->hasAttr<UnavailableAttr>()) {
8411 FD->addAttr(new (Context) UnavailableAttr(loc, Context,
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008412 "this system field has retaining ownership"));
John McCall31168b02011-06-15 23:02:42 +00008413 }
8414 } else {
8415 Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct);
8416 }
8417 ARCErrReported = true;
8418 }
8419 }
8420 else if (getLangOptions().ObjC1 &&
Mike Stump12b8ce12009-08-04 21:02:39 +00008421 getLangOptions().getGCMode() != LangOptions::NonGC &&
John McCall31168b02011-06-15 23:02:42 +00008422 Record && !Record->hasObjectMember()) {
8423 if (FD->getType()->isObjCObjectPointerType() ||
8424 FD->getType().isObjCGCStrong())
8425 Record->setHasObjectMember(true);
8426 else if (Context.getAsArrayType(FD->getType())) {
8427 QualType BaseType = Context.getBaseElementType(FD->getType());
8428 if (BaseType->isRecordType() &&
8429 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
8430 Record->setHasObjectMember(true);
8431 else if (BaseType->isObjCObjectPointerType() ||
8432 BaseType.isObjCGCStrong())
8433 Record->setHasObjectMember(true);
8434 }
8435 }
Fariborz Jahanian021510e2010-06-15 22:44:06 +00008436 }
Chris Lattner82625602007-01-24 02:26:21 +00008437 // Keep track of the number of named members.
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008438 if (FD->getIdentifier())
Chris Lattner82625602007-01-24 02:26:21 +00008439 ++NumNamedMembers;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00008440 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00008441
Chris Lattner82625602007-01-24 02:26:21 +00008442 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +00008443 if (Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00008444 bool Completed = false;
8445 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
8446 if (!CXXRecord->isInvalidDecl()) {
8447 // Set access bits correctly on the directly-declared conversions.
8448 UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions();
8449 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end();
8450 I != E; ++I)
8451 Convs->setAccess(I, (*I)->getAccess());
8452
8453 if (!CXXRecord->isDependentType()) {
John McCall31168b02011-06-15 23:02:42 +00008454 // Objective-C Automatic Reference Counting:
8455 // If a class has a non-static data member of Objective-C pointer
8456 // type (or array thereof), it is a non-POD type and its
8457 // default constructor (if any), copy constructor, copy assignment
8458 // operator, and destructor are non-trivial.
8459 //
8460 // This rule is also handled by CXXRecordDecl::completeDefinition().
8461 // However, here we check whether this particular class is only
8462 // non-POD because of the presence of an Objective-C pointer member.
8463 // If so, objects of this type cannot be shared between code compiled
8464 // with instant objects and code compiled with manual retain/release.
8465 if (getLangOptions().ObjCAutoRefCount &&
8466 CXXRecord->hasObjectMember() &&
8467 CXXRecord->getLinkage() == ExternalLinkage) {
8468 if (CXXRecord->isPOD()) {
8469 Diag(CXXRecord->getLocation(),
8470 diag::warn_arc_non_pod_class_with_object_member)
8471 << CXXRecord;
8472 } else {
8473 // FIXME: Fix-Its would be nice here, but finding a good location
8474 // for them is going to be tricky.
8475 if (CXXRecord->hasTrivialCopyConstructor())
8476 Diag(CXXRecord->getLocation(),
8477 diag::warn_arc_trivial_member_function_with_object_member)
8478 << CXXRecord << 0;
8479 if (CXXRecord->hasTrivialCopyAssignment())
8480 Diag(CXXRecord->getLocation(),
8481 diag::warn_arc_trivial_member_function_with_object_member)
8482 << CXXRecord << 1;
8483 if (CXXRecord->hasTrivialDestructor())
8484 Diag(CXXRecord->getLocation(),
8485 diag::warn_arc_trivial_member_function_with_object_member)
8486 << CXXRecord << 2;
8487 }
8488 }
8489
Sebastian Redl623ea822011-05-19 05:13:44 +00008490 // Adjust user-defined destructor exception spec.
8491 if (getLangOptions().CPlusPlus0x &&
8492 CXXRecord->hasUserDeclaredDestructor())
8493 AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor());
8494
Douglas Gregor8fb95122010-09-29 00:15:42 +00008495 // Add any implicitly-declared members to this class.
8496 AddImplicitlyDeclaredMembersToClass(CXXRecord);
8497
8498 // If we have virtual base classes, we may end up finding multiple
8499 // final overriders for a given virtual function. Check for this
8500 // problem now.
8501 if (CXXRecord->getNumVBases()) {
8502 CXXFinalOverriderMap FinalOverriders;
8503 CXXRecord->getFinalOverriders(FinalOverriders);
8504
8505 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
8506 MEnd = FinalOverriders.end();
8507 M != MEnd; ++M) {
8508 for (OverridingMethods::iterator SO = M->second.begin(),
8509 SOEnd = M->second.end();
8510 SO != SOEnd; ++SO) {
8511 assert(SO->second.size() > 0 &&
8512 "Virtual function without overridding functions?");
8513 if (SO->second.size() == 1)
8514 continue;
8515
8516 // C++ [class.virtual]p2:
8517 // In a derived class, if a virtual member function of a base
8518 // class subobject has more than one final overrider the
8519 // program is ill-formed.
8520 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
8521 << (NamedDecl *)M->first << Record;
8522 Diag(M->first->getLocation(),
8523 diag::note_overridden_virtual_function);
8524 for (OverridingMethods::overriding_iterator
8525 OM = SO->second.begin(),
8526 OMEnd = SO->second.end();
8527 OM != OMEnd; ++OM)
8528 Diag(OM->Method->getLocation(), diag::note_final_overrider)
8529 << (NamedDecl *)M->first << OM->Method->getParent();
8530
8531 Record->setInvalidDecl();
8532 }
8533 }
8534 CXXRecord->completeDefinition(&FinalOverriders);
8535 Completed = true;
8536 }
8537 }
8538 }
8539 }
8540
8541 if (!Completed)
8542 Record->completeDefinition();
Sebastian Redl623ea822011-05-19 05:13:44 +00008543
8544 // Now that the record is complete, do any delayed exception spec checks
8545 // we were missing.
Richard Smith938f40b2011-06-11 17:19:42 +00008546 while (!DelayedDestructorExceptionSpecChecks.empty()) {
Sebastian Redl623ea822011-05-19 05:13:44 +00008547 const CXXDestructorDecl *Dtor =
8548 DelayedDestructorExceptionSpecChecks.back().first;
Richard Smith938f40b2011-06-11 17:19:42 +00008549 if (Dtor->getParent() != Record)
8550 break;
8551
8552 assert(!Dtor->getParent()->isDependentType() &&
8553 "Should not ever add destructors of templates into the list.");
8554 CheckOverridingFunctionExceptionSpec(Dtor,
8555 DelayedDestructorExceptionSpecChecks.back().second);
8556 DelayedDestructorExceptionSpecChecks.pop_back();
Sebastian Redl623ea822011-05-19 05:13:44 +00008557 }
8558
Chris Lattner622c1932008-02-06 00:51:33 +00008559 } else {
Jay Foad7d0479f2009-05-21 09:52:38 +00008560 ObjCIvarDecl **ClsFields =
8561 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian02225532008-12-13 20:28:25 +00008562 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattner22298722009-02-20 21:35:13 +00008563 ID->setLocEnd(RBrac);
Fariborz Jahanian68453832009-06-05 18:16:35 +00008564 // Add ivar's to class's DeclContext.
8565 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
8566 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008567 ID->addDecl(ClsFields[i]);
Fariborz Jahanian68453832009-06-05 18:16:35 +00008568 }
Fariborz Jahaniana599c132008-12-16 01:08:35 +00008569 // Must enforce the rule that ivars in the base classes may not be
8570 // duplicates.
Fariborz Jahanian545643c2010-02-23 23:41:11 +00008571 if (ID->getSuperClass())
8572 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump11289f42009-09-09 15:08:12 +00008573 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattnerd13b8b52009-02-23 22:00:08 +00008574 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00008575 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian68453832009-06-05 18:16:35 +00008576 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
8577 // Ivar declared in @implementation never belongs to the implementation.
8578 // Only it is in implementation's lexical context.
Douglas Gregor5f662052009-04-23 03:23:08 +00008579 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian95b60762007-10-31 18:48:14 +00008580 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +00008581 } else if (ObjCCategoryDecl *CDecl =
8582 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00008583 // case of ivars in class extension; all other cases have been
8584 // reported as errors elsewhere.
8585 // FIXME. Class extension does not have a LocEnd field.
8586 // CDecl->setLocEnd(RBrac);
8587 // Add ivar's to class extension's DeclContext.
8588 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
8589 ClsFields[i]->setLexicalDeclContext(CDecl);
8590 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +00008591 }
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +00008592 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +00008593 }
Daniel Dunbar325601a2008-10-03 17:33:35 +00008594
8595 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00008596 ProcessDeclAttributeList(S, Record, Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00008597
8598 // If there's a #pragma GCC visibility in scope, and this isn't a subclass,
8599 // set the visibility of this record.
8600 if (Record && !Record->getDeclContext()->isRecord())
8601 AddPushedVisibilityAttribute(Record);
Chris Lattner1300fb92007-01-23 23:42:53 +00008602}
8603
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008604/// \brief Determine whether the given integral value is representable within
8605/// the given type T.
8606static bool isRepresentableIntegerValue(ASTContext &Context,
8607 llvm::APSInt &Value,
8608 QualType T) {
Douglas Gregor6972a622010-06-16 00:35:25 +00008609 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregorc1cf8142010-04-15 15:53:31 +00008610 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008611
Douglas Gregor0bf31402010-10-08 23:50:27 +00008612 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00008613 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor0bf31402010-10-08 23:50:27 +00008614 --BitWidth;
8615 return Value.getActiveBits() <= BitWidth;
8616 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008617 return Value.getMinSignedBits() <= BitWidth;
8618}
8619
8620// \brief Given an integral type, return the next larger integral type
8621// (or a NULL type of no such type exists).
8622static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
8623 // FIXME: Int128/UInt128 support, which also needs to be introduced into
8624 // enum checking below.
Douglas Gregor6972a622010-06-16 00:35:25 +00008625 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008626 const unsigned NumTypes = 4;
8627 QualType SignedIntegralTypes[NumTypes] = {
8628 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
8629 };
8630 QualType UnsignedIntegralTypes[NumTypes] = {
8631 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
8632 Context.UnsignedLongLongTy
8633 };
8634
8635 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00008636 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
8637 : UnsignedIntegralTypes;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008638 for (unsigned I = 0; I != NumTypes; ++I)
8639 if (Context.getTypeSize(Types[I]) > BitWidth)
8640 return Types[I];
8641
8642 return QualType();
8643}
8644
Douglas Gregor954f6b272009-03-17 19:05:46 +00008645EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
8646 EnumConstantDecl *LastEnumConst,
8647 SourceLocation IdLoc,
8648 IdentifierInfo *Id,
John McCallb268a282010-08-23 23:25:46 +00008649 Expr *Val) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008650 unsigned IntWidth = Context.Target.getIntWidth();
8651 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor954f6b272009-03-17 19:05:46 +00008652 QualType EltTy;
Douglas Gregor2b988fd2010-12-16 00:24:44 +00008653
8654 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
8655 Val = 0;
8656
Douglas Gregorb2186fe2009-11-06 00:03:12 +00008657 if (Val) {
Douglas Gregordc70c3a2010-03-02 17:53:14 +00008658 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregorb2186fe2009-11-06 00:03:12 +00008659 EltTy = Context.DependentTy;
8660 else {
Douglas Gregorb2186fe2009-11-06 00:03:12 +00008661 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
8662 SourceLocation ExpLoc;
Douglas Gregordc70c3a2010-03-02 17:53:14 +00008663 if (!Val->isValueDependent() &&
8664 VerifyIntegerConstantExpression(Val, &EnumVal)) {
Douglas Gregorb2186fe2009-11-06 00:03:12 +00008665 Val = 0;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008666 } else {
8667 if (!getLangOptions().CPlusPlus) {
8668 // C99 6.7.2.2p2:
8669 // The expression that defines the value of an enumeration constant
8670 // shall be an integer constant expression that has a value
8671 // representable as an int.
8672
8673 // Complain if the value is not representable in an int.
8674 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
8675 Diag(IdLoc, diag::ext_enum_value_not_int)
8676 << EnumVal.toString(10) << Val->getSourceRange()
Douglas Gregorc0b8c812010-02-17 22:40:11 +00008677 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008678 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
8679 // Force the type of the expression to 'int'.
John Wiegley01296292011-04-08 18:41:53 +00008680 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008681 }
8682 }
8683
Douglas Gregor0bf31402010-10-08 23:50:27 +00008684 if (Enum->isFixed()) {
8685 EltTy = Enum->getIntegerType();
8686
8687 // C++0x [dcl.enum]p5:
8688 // ... if the initializing value of an enumerator cannot be
8689 // represented by the underlying type, the program is ill-formed.
Francois Picheta3108062010-10-18 15:01:13 +00008690 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
8691 if (getLangOptions().Microsoft) {
8692 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
John Wiegley01296292011-04-08 18:41:53 +00008693 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Francois Picheta3108062010-10-18 15:01:13 +00008694 } else
8695 Diag(IdLoc, diag::err_enumerator_too_large)
8696 << EltTy;
8697 } else
John Wiegley01296292011-04-08 18:41:53 +00008698 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008699 }
8700 else {
8701 // C++0x [dcl.enum]p5:
8702 // If the underlying type is not fixed, the type of each enumerator
8703 // is the type of its initializing value:
8704 // - If an initializer is specified for an enumerator, the
8705 // initializing value has the same type as the expression.
8706 EltTy = Val->getType();
8707 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +00008708 }
Douglas Gregor954f6b272009-03-17 19:05:46 +00008709 }
8710 }
Mike Stump11289f42009-09-09 15:08:12 +00008711
Douglas Gregor954f6b272009-03-17 19:05:46 +00008712 if (!Val) {
Eli Friedmand0e60972009-12-11 01:34:50 +00008713 if (Enum->isDependentType())
8714 EltTy = Context.DependentTy;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008715 else if (!LastEnumConst) {
8716 // C++0x [dcl.enum]p5:
8717 // If the underlying type is not fixed, the type of each enumerator
8718 // is the type of its initializing value:
8719 // - If no initializer is specified for the first enumerator, the
8720 // initializing value has an unspecified integral type.
8721 //
8722 // GCC uses 'int' for its unspecified integral type, as does
8723 // C99 6.7.2.2p3.
Douglas Gregor0bf31402010-10-08 23:50:27 +00008724 if (Enum->isFixed()) {
8725 EltTy = Enum->getIntegerType();
8726 }
8727 else {
8728 EltTy = Context.IntTy;
8729 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008730 } else {
Douglas Gregor954f6b272009-03-17 19:05:46 +00008731 // Assign the last value + 1.
8732 EnumVal = LastEnumConst->getInitVal();
8733 ++EnumVal;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008734 EltTy = LastEnumConst->getType();
Douglas Gregor954f6b272009-03-17 19:05:46 +00008735
8736 // Check for overflow on increment.
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008737 if (EnumVal < LastEnumConst->getInitVal()) {
8738 // C++0x [dcl.enum]p5:
8739 // If the underlying type is not fixed, the type of each enumerator
8740 // is the type of its initializing value:
8741 //
8742 // - Otherwise the type of the initializing value is the same as
8743 // the type of the initializing value of the preceding enumerator
8744 // unless the incremented value is not representable in that type,
8745 // in which case the type is an unspecified integral type
8746 // sufficient to contain the incremented value. If no such type
8747 // exists, the program is ill-formed.
8748 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor0bf31402010-10-08 23:50:27 +00008749 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008750 // There is no integral type larger enough to represent this
8751 // value. Complain, then allow the value to wrap around.
8752 EnumVal = LastEnumConst->getInitVal();
Jay Foad6d4db0c2010-12-07 08:25:34 +00008753 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor0bf31402010-10-08 23:50:27 +00008754 ++EnumVal;
8755 if (Enum->isFixed())
8756 // When the underlying type is fixed, this is ill-formed.
8757 Diag(IdLoc, diag::err_enumerator_wrapped)
8758 << EnumVal.toString(10)
8759 << EltTy;
8760 else
8761 Diag(IdLoc, diag::warn_enumerator_too_large)
8762 << EnumVal.toString(10);
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008763 } else {
8764 EltTy = T;
8765 }
8766
8767 // Retrieve the last enumerator's value, extent that type to the
8768 // type that is supposed to be large enough to represent the incremented
8769 // value, then increment.
8770 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00008771 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad6d4db0c2010-12-07 08:25:34 +00008772 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008773 ++EnumVal;
8774
8775 // If we're not in C++, diagnose the overflow of enumerator values,
8776 // which in C99 means that the enumerator value is not representable in
8777 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
8778 // permits enumerator values that are representable in some larger
8779 // integral type.
8780 if (!getLangOptions().CPlusPlus && !T.isNull())
8781 Diag(IdLoc, diag::warn_enum_value_overflow);
8782 } else if (!getLangOptions().CPlusPlus &&
8783 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
8784 // Enforce C99 6.7.2.2p2 even when we compute the next value.
8785 Diag(IdLoc, diag::ext_enum_value_not_int)
8786 << EnumVal.toString(10) << 1;
8787 }
Douglas Gregor954f6b272009-03-17 19:05:46 +00008788 }
8789 }
Mike Stump11289f42009-09-09 15:08:12 +00008790
Douglas Gregordc70c3a2010-03-02 17:53:14 +00008791 if (!EltTy->isDependentType()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008792 // Make the enumerator value match the signedness and size of the
8793 // enumerator's type.
Jay Foad6d4db0c2010-12-07 08:25:34 +00008794 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00008795 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008796 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +00008797
Douglas Gregor954f6b272009-03-17 19:05:46 +00008798 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump11289f42009-09-09 15:08:12 +00008799 Val, EnumVal);
Douglas Gregor954f6b272009-03-17 19:05:46 +00008800}
8801
8802
John McCall811a0f52010-10-22 23:36:17 +00008803Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
8804 SourceLocation IdLoc, IdentifierInfo *Id,
8805 AttributeList *Attr,
8806 SourceLocation EqualLoc, ExprTy *val) {
John McCall48871652010-08-21 09:40:31 +00008807 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Chris Lattner4ef40012007-06-11 01:28:17 +00008808 EnumConstantDecl *LastEnumConst =
John McCall48871652010-08-21 09:40:31 +00008809 cast_or_null<EnumConstantDecl>(lastEnumConst);
Chris Lattner4ef40012007-06-11 01:28:17 +00008810 Expr *Val = static_cast<Expr*>(val);
Chris Lattner8116d1b2007-01-25 22:38:29 +00008811
Chris Lattner1a76a3c2007-08-26 06:24:45 +00008812 // The scope passed in may not be a decl scope. Zip up the scope tree until
8813 // we find one that is.
Douglas Gregor45a33ec2009-01-12 18:45:55 +00008814 S = getNonFieldDeclScope(S);
Mike Stump11289f42009-09-09 15:08:12 +00008815
Chris Lattner8116d1b2007-01-25 22:38:29 +00008816 // Verify that there isn't already something declared with this name in this
8817 // scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00008818 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregor5204248f2010-01-19 06:06:57 +00008819 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +00008820 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00008821 // Maybe we will complain about the shadowed template parameter.
8822 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
8823 // Just pretend that we didn't see the previous declaration.
8824 PrevDecl = 0;
8825 }
8826
8827 if (PrevDecl) {
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +00008828 // When in C++, we may get a TagDecl with the same name; in this case the
8829 // enum constant will 'hide' the tag.
8830 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
8831 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis5b144d52008-09-09 21:18:04 +00008832 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +00008833 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner4bd8dd82008-11-19 08:23:25 +00008834 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner8116d1b2007-01-25 22:38:29 +00008835 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +00008836 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner0369c572008-11-23 23:12:31 +00008837 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00008838 return 0;
Chris Lattner8116d1b2007-01-25 22:38:29 +00008839 }
8840 }
Chris Lattner4ef40012007-06-11 01:28:17 +00008841
Douglas Gregor36c22a22010-10-15 13:21:21 +00008842 // C++ [class.mem]p13:
8843 // If T is the name of a class, then each of the following shall have a
8844 // name different from T:
8845 // - every enumerator of every member of class T that is an enumerated
8846 // type
8847 if (CXXRecordDecl *Record
8848 = dyn_cast<CXXRecordDecl>(
8849 TheEnumDecl->getDeclContext()->getRedeclContext()))
8850 if (Record->getIdentifier() && Record->getIdentifier() == Id)
8851 Diag(IdLoc, diag::err_member_name_of_class) << Id;
8852
John McCall811a0f52010-10-22 23:36:17 +00008853 EnumConstantDecl *New =
8854 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner0515e4b2007-08-27 21:16:18 +00008855
John McCall553c0792010-01-23 00:46:32 +00008856 if (New) {
John McCall811a0f52010-10-22 23:36:17 +00008857 // Process attributes.
8858 if (Attr) ProcessDeclAttributeList(S, New, Attr);
8859
8860 // Register this decl in the current scope stack.
John McCall553c0792010-01-23 00:46:32 +00008861 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor954f6b272009-03-17 19:05:46 +00008862 PushOnScopeChains(New, S);
John McCall553c0792010-01-23 00:46:32 +00008863 }
Douglas Gregor2f521192008-12-17 02:04:30 +00008864
John McCall48871652010-08-21 09:40:31 +00008865 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +00008866}
8867
Mike Stump6814d1c2009-05-16 07:06:02 +00008868void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCall48871652010-08-21 09:40:31 +00008869 SourceLocation RBraceLoc, Decl *EnumDeclX,
8870 Decl **Elements, unsigned NumElements,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008871 Scope *S, AttributeList *Attr) {
John McCall48871652010-08-21 09:40:31 +00008872 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor07665a62009-01-05 19:45:36 +00008873 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008874
8875 if (Attr)
8876 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump11289f42009-09-09 15:08:12 +00008877
Eli Friedmand0e60972009-12-11 01:34:50 +00008878 if (Enum->isDependentType()) {
8879 for (unsigned i = 0; i != NumElements; ++i) {
8880 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +00008881 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmand0e60972009-12-11 01:34:50 +00008882 if (!ECD) continue;
8883
8884 ECD->setType(EnumType);
8885 }
8886
John McCall9aa35be2010-05-06 08:49:23 +00008887 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmand0e60972009-12-11 01:34:50 +00008888 return;
8889 }
8890
Chris Lattner67933c02007-08-28 05:10:31 +00008891 // TODO: If the result value doesn't fit in an int, it must be a long or long
8892 // long value. ISO C does not support this, but GCC does as an extension,
8893 // emit a warning.
Chris Lattner37e05872008-03-05 18:54:05 +00008894 unsigned IntWidth = Context.Target.getIntWidth();
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008895 unsigned CharWidth = Context.Target.getCharWidth();
8896 unsigned ShortWidth = Context.Target.getShortWidth();
Mike Stump11289f42009-09-09 15:08:12 +00008897
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008898 // Verify that all the values are okay, compute the size of the values, and
8899 // reverse the list.
8900 unsigned NumNegativeBits = 0;
8901 unsigned NumPositiveBits = 0;
Mike Stump11289f42009-09-09 15:08:12 +00008902
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008903 // Keep track of whether all elements have type int.
8904 bool AllElementsInt = true;
Mike Stump11289f42009-09-09 15:08:12 +00008905
Chris Lattnerc1915e22007-01-25 07:29:02 +00008906 for (unsigned i = 0; i != NumElements; ++i) {
8907 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +00008908 cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerc1915e22007-01-25 07:29:02 +00008909 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump11289f42009-09-09 15:08:12 +00008910
Chris Lattnerbf478cb2007-08-28 05:27:00 +00008911 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump11289f42009-09-09 15:08:12 +00008912
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008913 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +00008914 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +00008915 NumPositiveBits = std::max(NumPositiveBits,
8916 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008917 else
Chris Lattner49f980c2008-01-14 21:47:29 +00008918 NumNegativeBits = std::max(NumNegativeBits,
8919 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +00008920
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008921 // Keep track of whether every enum element has type int (very commmon).
8922 if (AllElementsInt)
Mike Stump11289f42009-09-09 15:08:12 +00008923 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattnerc1915e22007-01-25 07:29:02 +00008924 }
Mike Stump11289f42009-09-09 15:08:12 +00008925
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008926 // Figure out the type that should be used for this enum.
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008927 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +00008928 unsigned BestWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008929
John McCall56774992009-12-09 09:09:27 +00008930 // C++0x N3000 [conv.prom]p3:
8931 // An rvalue of an unscoped enumeration type whose underlying
8932 // type is not fixed can be converted to an rvalue of the first
8933 // of the following types that can represent all the values of
8934 // the enumeration: int, unsigned int, long int, unsigned long
8935 // int, long long int, or unsigned long long int.
8936 // C99 6.4.4.3p2:
8937 // An identifier declared as an enumeration constant has type int.
8938 // The C99 rule is modified by a gcc extension
8939 QualType BestPromotionType;
8940
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008941 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
Argyrios Kyrtzidis74825bc2010-10-08 00:25:19 +00008942 // -fshort-enums is the equivalent to specifying the packed attribute on all
8943 // enum definitions.
8944 if (LangOpts.ShortEnums)
8945 Packed = true;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008946
Douglas Gregor0bf31402010-10-08 23:50:27 +00008947 if (Enum->isFixed()) {
8948 BestType = BestPromotionType = Enum->getIntegerType();
Duncan Sands38b918c2010-10-12 14:07:59 +00008949 // We don't need to set BestWidth, because BestType is going to be the type
8950 // of the enumerators, but we do anyway because otherwise some compilers
8951 // warn that it might be used uninitialized.
8952 BestWidth = CharWidth;
Douglas Gregor0bf31402010-10-08 23:50:27 +00008953 }
8954 else if (NumNegativeBits) {
Mike Stump11289f42009-09-09 15:08:12 +00008955 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008956 // int/long/longlong) that fits.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008957 // If it's packed, check also if it fits a char or a short.
8958 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall56774992009-12-09 09:09:27 +00008959 BestType = Context.SignedCharTy;
8960 BestWidth = CharWidth;
Mike Stump11289f42009-09-09 15:08:12 +00008961 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008962 NumPositiveBits < ShortWidth) {
John McCall56774992009-12-09 09:09:27 +00008963 BestType = Context.ShortTy;
8964 BestWidth = ShortWidth;
8965 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008966 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00008967 BestWidth = IntWidth;
8968 } else {
Chris Lattner37e05872008-03-05 18:54:05 +00008969 BestWidth = Context.Target.getLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +00008970
John McCall56774992009-12-09 09:09:27 +00008971 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008972 BestType = Context.LongTy;
John McCall56774992009-12-09 09:09:27 +00008973 } else {
Chris Lattner37e05872008-03-05 18:54:05 +00008974 BestWidth = Context.Target.getLongLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +00008975
Chris Lattner3a370bf2007-08-29 17:31:48 +00008976 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008977 Diag(Enum->getLocation(), diag::warn_enum_too_large);
8978 BestType = Context.LongLongTy;
8979 }
8980 }
John McCall56774992009-12-09 09:09:27 +00008981 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008982 } else {
Douglas Gregora71cc152010-02-02 20:10:50 +00008983 // If there is no negative value, figure out the smallest type that fits
8984 // all of the enumerator values.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008985 // If it's packed, check also if it fits a char or a short.
8986 if (Packed && NumPositiveBits <= CharWidth) {
John McCall56774992009-12-09 09:09:27 +00008987 BestType = Context.UnsignedCharTy;
8988 BestPromotionType = Context.IntTy;
8989 BestWidth = CharWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008990 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall56774992009-12-09 09:09:27 +00008991 BestType = Context.UnsignedShortTy;
8992 BestPromotionType = Context.IntTy;
8993 BestWidth = ShortWidth;
8994 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008995 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00008996 BestWidth = IntWidth;
Douglas Gregora71cc152010-02-02 20:10:50 +00008997 BestPromotionType
8998 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
8999 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00009000 } else if (NumPositiveBits <=
Chris Lattner37e05872008-03-05 18:54:05 +00009001 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00009002 BestType = Context.UnsignedLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +00009003 BestPromotionType
9004 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
9005 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner37e05872008-03-05 18:54:05 +00009006 } else {
9007 BestWidth = Context.Target.getLongLongWidth();
Chris Lattner3a370bf2007-08-29 17:31:48 +00009008 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +00009009 "How could an initializer get larger than ULL?");
9010 BestType = Context.UnsignedLongLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +00009011 BestPromotionType
9012 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
9013 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerb8a501c2007-08-28 06:15:15 +00009014 }
9015 }
Mike Stump11289f42009-09-09 15:08:12 +00009016
Chris Lattner3a370bf2007-08-29 17:31:48 +00009017 // Loop over all of the enumerator constants, changing their types to match
9018 // the type of the enum if needed.
9019 for (unsigned i = 0; i != NumElements; ++i) {
John McCall48871652010-08-21 09:40:31 +00009020 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattner3a370bf2007-08-29 17:31:48 +00009021 if (!ECD) continue; // Already issued a diagnostic.
9022
9023 // Standard C says the enumerators have int type, but we allow, as an
9024 // extension, the enumerators to be larger than int size. If each
9025 // enumerator value fits in an int, type it as an int, otherwise type it the
9026 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
9027 // that X has type 'int', not 'unsigned'.
Chris Lattner3a370bf2007-08-29 17:31:48 +00009028
9029 // Determine whether the value fits into an int.
9030 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattner3a370bf2007-08-29 17:31:48 +00009031
9032 // If it fits into an integer type, force it. Otherwise force it to match
9033 // the enum decl type.
9034 QualType NewTy;
9035 unsigned NewWidth;
9036 bool NewSign;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00009037 if (!getLangOptions().CPlusPlus &&
9038 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattner3a370bf2007-08-29 17:31:48 +00009039 NewTy = Context.IntTy;
9040 NewWidth = IntWidth;
9041 NewSign = true;
9042 } else if (ECD->getType() == BestType) {
9043 // Already the right type!
Douglas Gregor1d248c52008-12-12 02:00:36 +00009044 if (getLangOptions().CPlusPlus)
9045 // C++ [dcl.enum]p4: Following the closing brace of an
9046 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +00009047 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +00009048 ECD->setType(EnumType);
Chris Lattner3a370bf2007-08-29 17:31:48 +00009049 continue;
9050 } else {
9051 NewTy = BestType;
9052 NewWidth = BestWidth;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00009053 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattner3a370bf2007-08-29 17:31:48 +00009054 }
9055
9056 // Adjust the APSInt value.
Jay Foad6d4db0c2010-12-07 08:25:34 +00009057 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattner3a370bf2007-08-29 17:31:48 +00009058 InitVal.setIsSigned(NewSign);
9059 ECD->setInitVal(InitVal);
Mike Stump11289f42009-09-09 15:08:12 +00009060
Chris Lattner3a370bf2007-08-29 17:31:48 +00009061 // Adjust the Expr initializer and type.
Abramo Bagnara77815432010-12-17 15:49:53 +00009062 if (ECD->getInitExpr() &&
Nick Lewycky0bdf13e2011-07-02 02:05:12 +00009063 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallcf142162010-08-07 06:22:56 +00009064 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCalle3027922010-08-25 11:45:40 +00009065 CK_IntegralCast,
John McCallcf142162010-08-07 06:22:56 +00009066 ECD->getInitExpr(),
9067 /*base paths*/ 0,
John McCall2536c6d2010-08-25 10:28:54 +00009068 VK_RValue));
Douglas Gregor1d248c52008-12-12 02:00:36 +00009069 if (getLangOptions().CPlusPlus)
9070 // C++ [dcl.enum]p4: Following the closing brace of an
9071 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +00009072 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +00009073 ECD->setType(EnumType);
9074 else
9075 ECD->setType(NewTy);
Chris Lattner3a370bf2007-08-29 17:31:48 +00009076 }
Mike Stump11289f42009-09-09 15:08:12 +00009077
John McCall9aa35be2010-05-06 08:49:23 +00009078 Enum->completeDefinition(BestType, BestPromotionType,
9079 NumPositiveBits, NumNegativeBits);
Chris Lattnerc1915e22007-01-25 07:29:02 +00009080}
Chris Lattner1300fb92007-01-23 23:42:53 +00009081
Abramo Bagnara348823a2011-03-03 14:20:18 +00009082Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
9083 SourceLocation StartLoc,
9084 SourceLocation EndLoc) {
John McCallb268a282010-08-23 23:25:46 +00009085 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redlc675bab2008-12-13 16:23:55 +00009086
Douglas Gregor278f52e2009-05-30 00:08:05 +00009087 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara348823a2011-03-03 14:20:18 +00009088 AsmString, StartLoc,
9089 EndLoc);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009090 CurContext->addDecl(New);
John McCall48871652010-08-21 09:40:31 +00009091 return New;
Anders Carlsson5c6c0592008-02-08 00:33:21 +00009092}
Eli Friedman5ed51982009-06-05 02:44:36 +00009093
9094void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
9095 SourceLocation PragmaLoc,
9096 SourceLocation NameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00009097 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedman5ed51982009-06-05 02:44:36 +00009098
Eli Friedman5ed51982009-06-05 02:44:36 +00009099 if (PrevDecl) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00009100 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
Ryan Flynn7d470f32009-07-30 03:15:39 +00009101 } else {
9102 (void)WeakUndeclaredIdentifiers.insert(
9103 std::pair<IdentifierInfo*,WeakInfo>
9104 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedman5ed51982009-06-05 02:44:36 +00009105 }
Eli Friedman5ed51982009-06-05 02:44:36 +00009106}
9107
9108void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
9109 IdentifierInfo* AliasName,
9110 SourceLocation PragmaLoc,
9111 SourceLocation NameLoc,
9112 SourceLocation AliasNameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00009113 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
9114 LookupOrdinaryName);
Ryan Flynn7d470f32009-07-30 03:15:39 +00009115 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedman5ed51982009-06-05 02:44:36 +00009116
Eli Friedman5ed51982009-06-05 02:44:36 +00009117 if (PrevDecl) {
Ryan Flynn7d470f32009-07-30 03:15:39 +00009118 if (!PrevDecl->hasAttr<AliasAttr>())
9119 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynnd963a492009-07-31 02:52:19 +00009120 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynn7d470f32009-07-30 03:15:39 +00009121 } else {
9122 (void)WeakUndeclaredIdentifiers.insert(
9123 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedman5ed51982009-06-05 02:44:36 +00009124 }
Eli Friedman5ed51982009-06-05 02:44:36 +00009125}