blob: 2779faeb15cfafcf256bf662322f0222c594bb7d [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
John McCall48871652010-08-21 09:40:31 +000048Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr) {
49 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
Chris Lattner5bbb3c82009-03-29 16:50:03 +000050}
51
Douglas Gregorec6e1892009-02-04 19:16:12 +000052/// \brief If the identifier refers to a type name within this scope,
53/// return the declaration of that type.
54///
55/// This routine performs ordinary name lookup of the identifier II
56/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor9817f4a2009-02-09 15:09:02 +000057/// determine whether the name refers to a type. If so, returns an
58/// opaque pointer (actually a QualType) corresponding to that
59/// type. Otherwise, returns NULL.
Douglas Gregorec6e1892009-02-04 19:16:12 +000060///
61/// If name lookup results in an ambiguity, this routine will complain
62/// and then return NULL.
John McCallba7bf592010-08-24 05:47:05 +000063ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
64 Scope *S, CXXScopeSpec *SS,
Fariborz Jahanian87967422011-02-08 18:05:59 +000065 bool isClassName, bool HasTrailingDot,
Douglas Gregor844cb502011-03-01 18:12:44 +000066 ParsedType ObjectTypePtr,
67 bool WantNontrivialTypeSourceInfo) {
Douglas Gregora25d65d2009-11-20 22:03:38 +000068 // Determine where we will perform name lookup.
69 DeclContext *LookupCtx = 0;
70 if (ObjectTypePtr) {
John McCallba7bf592010-08-24 05:47:05 +000071 QualType ObjectType = ObjectTypePtr.get();
Douglas Gregora25d65d2009-11-20 22:03:38 +000072 if (ObjectType->isRecordType())
73 LookupCtx = computeDeclContext(ObjectType);
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +000074 } else if (SS && SS->isNotEmpty()) {
Douglas Gregora25d65d2009-11-20 22:03:38 +000075 LookupCtx = computeDeclContext(*SS, false);
76
77 if (!LookupCtx) {
78 if (isDependentScopeSpecifier(*SS)) {
79 // C++ [temp.res]p3:
80 // A qualified-id that refers to a type and in which the
81 // nested-name-specifier depends on a template-parameter (14.6.2)
82 // shall be prefixed by the keyword typename to indicate that the
83 // qualified-id denotes a type, forming an
84 // elaborated-type-specifier (7.1.5.3).
85 //
86 // We therefore do not perform any name lookup if the result would
87 // refer to a member of an unknown specialization.
88 if (!isClassName)
John McCallba7bf592010-08-24 05:47:05 +000089 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +000090
John McCallc392f372010-06-11 00:33:02 +000091 // We know from the grammar that this name refers to a type,
92 // so build a dependent node to describe the type.
Douglas Gregor844cb502011-03-01 18:12:44 +000093 if (WantNontrivialTypeSourceInfo)
94 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
95
96 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
John McCallba7bf592010-08-24 05:47:05 +000097 QualType T =
Douglas Gregor844cb502011-03-01 18:12:44 +000098 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000099 II, NameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +0000100
101 return ParsedType::make(T);
Douglas Gregora25d65d2009-11-20 22:03:38 +0000102 }
103
John McCallba7bf592010-08-24 05:47:05 +0000104 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000105 }
106
John McCall0b66eb32010-05-01 00:40:08 +0000107 if (!LookupCtx->isDependentContext() &&
108 RequireCompleteDeclContext(*SS, LookupCtx))
John McCallba7bf592010-08-24 05:47:05 +0000109 return ParsedType();
Douglas Gregor5e0962f2009-08-26 18:27:52 +0000110 }
Eli Friedman9025ec22009-12-21 01:42:38 +0000111
112 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
113 // lookup for class-names.
114 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
115 LookupOrdinaryName;
116 LookupResult Result(*this, &II, NameLoc, Kind);
Douglas Gregora25d65d2009-11-20 22:03:38 +0000117 if (LookupCtx) {
118 // Perform "qualified" name lookup into the declaration context we
119 // computed, which is either the type of the base of a member access
120 // expression or the declaration context associated with a prior
121 // nested-name-specifier.
122 LookupQualifiedName(Result, LookupCtx);
Douglas Gregorc9f9b862009-05-11 19:58:34 +0000123
Douglas Gregora25d65d2009-11-20 22:03:38 +0000124 if (ObjectTypePtr && Result.empty()) {
125 // C++ [basic.lookup.classref]p3:
126 // If the unqualified-id is ~type-name, the type-name is looked up
127 // in the context of the entire postfix-expression. If the type T of
128 // the object expression is of a class type C, the type-name is also
129 // looked up in the scope of class C. At least one of the lookups shall
130 // find a name that refers to (possibly cv-qualified) T.
131 LookupName(Result, S);
132 }
133 } else {
134 // Perform unqualified name lookup.
135 LookupName(Result, S);
136 }
137
Chris Lattnera3778332009-02-16 22:07:16 +0000138 NamedDecl *IIDecl = 0;
John McCall27b18f82009-11-17 02:14:36 +0000139 switch (Result.getResultKind()) {
Chris Lattnera3778332009-02-16 22:07:16 +0000140 case LookupResult::NotFound:
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000141 case LookupResult::NotFoundInCurrentInstantiation:
Chris Lattnera3778332009-02-16 22:07:16 +0000142 case LookupResult::FoundOverloaded:
John McCalle61f2ba2009-11-18 02:36:19 +0000143 case LookupResult::FoundUnresolvedValue:
John McCall58cc69d2010-01-27 01:50:18 +0000144 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000145 return ParsedType();
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000146
Chris Lattnere40853a2009-10-25 22:09:09 +0000147 case LookupResult::Ambiguous:
John McCall6538c932009-10-10 05:48:19 +0000148 // Recover from type-hiding ambiguities by hiding the type. We'll
149 // do the lookup again when looking for an object, and we can
150 // diagnose the error then. If we don't do this, then the error
151 // about hiding the type will be immediately followed by an error
152 // that only makes sense if the identifier was treated like a type.
John McCall27b18f82009-11-17 02:14:36 +0000153 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
154 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000155 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000156 }
John McCall6538c932009-10-10 05:48:19 +0000157
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000158 // Look to see if we have a type anywhere in the list of results.
159 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
160 Res != ResEnd; ++Res) {
161 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
Mike Stump11289f42009-09-09 15:08:12 +0000162 if (!IIDecl ||
163 (*Res)->getLocation().getRawEncoding() <
Douglas Gregor712a3512009-04-13 15:14:38 +0000164 IIDecl->getLocation().getRawEncoding())
165 IIDecl = *Res;
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000166 }
167 }
168
169 if (!IIDecl) {
170 // None of the entities we found is a type, so there is no way
171 // to even assume that the result is a type. In this case, don't
172 // complain about the ambiguity. The parser will either try to
173 // perform this lookup again (e.g., as an object name), which
174 // will produce the ambiguity, or will complain that it expected
175 // a type name.
John McCall27b18f82009-11-17 02:14:36 +0000176 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000177 return ParsedType();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000178 }
179
180 // We found a type within the ambiguous lookup; diagnose the
181 // ambiguity and then return that type. This might be the right
182 // answer, or it might not be, but it suppresses any attempt to
183 // perform the name lookup again.
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000184 break;
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000185
Chris Lattnera3778332009-02-16 22:07:16 +0000186 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +0000187 IIDecl = Result.getFoundDecl();
Chris Lattnera3778332009-02-16 22:07:16 +0000188 break;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000189 }
190
Chris Lattner17e15f12009-10-25 17:16:46 +0000191 assert(IIDecl && "Didn't find decl");
John McCall28a6aea2009-11-04 02:18:39 +0000192
Chris Lattner17e15f12009-10-25 17:16:46 +0000193 QualType T;
194 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
John McCall28a6aea2009-11-04 02:18:39 +0000195 DiagnoseUseOfDecl(IIDecl, NameLoc);
John McCall27b18f82009-11-17 02:14:36 +0000196
Chris Lattner17e15f12009-10-25 17:16:46 +0000197 if (T.isNull())
198 T = Context.getTypeDeclType(TD);
199
Douglas Gregor844cb502011-03-01 18:12:44 +0000200 if (SS && SS->isNotEmpty()) {
201 if (WantNontrivialTypeSourceInfo) {
202 // Construct a type with type-source information.
203 TypeLocBuilder Builder;
204 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
205
206 T = getElaboratedType(ETK_None, *SS, T);
207 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
208 ElabTL.setKeywordLoc(SourceLocation());
209 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
210 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
211 } else {
212 T = getElaboratedType(ETK_None, *SS, T);
213 }
214 }
Chris Lattner17e15f12009-10-25 17:16:46 +0000215 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
Fariborz Jahanian08891f52011-03-08 19:12:46 +0000216 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
Fariborz Jahanian87967422011-02-08 18:05:59 +0000217 if (!HasTrailingDot)
218 T = Context.getObjCInterfaceType(IDecl);
219 }
220
221 if (T.isNull()) {
John McCall27b18f82009-11-17 02:14:36 +0000222 // If it's not plausibly a type, suppress diagnostics.
223 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000224 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000225 }
John McCallba7bf592010-08-24 05:47:05 +0000226 return ParsedType::make(T);
Chris Lattnere168f762006-11-10 05:29:30 +0000227}
228
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000229/// isTagName() - This method is called *for error recovery purposes only*
230/// to determine if the specified name is a valid tag name ("struct foo"). If
231/// so, this returns the TST for the tag corresponding to it (TST_enum,
232/// TST_union, TST_struct, TST_class). This is used to diagnose cases in C
233/// where the user forgot to specify the tag.
234DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
235 // Do a tag name lookup in this scope.
John McCall27b18f82009-11-17 02:14:36 +0000236 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
237 LookupName(R, S, false);
238 R.suppressDiagnostics();
239 if (R.getResultKind() == LookupResult::Found)
John McCall67c00872009-12-02 08:25:40 +0000240 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000241 switch (TD->getTagKind()) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000242 default: return DeclSpec::TST_unspecified;
243 case TTK_Struct: return DeclSpec::TST_struct;
244 case TTK_Union: return DeclSpec::TST_union;
245 case TTK_Class: return DeclSpec::TST_class;
246 case TTK_Enum: return DeclSpec::TST_enum;
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000247 }
248 }
Mike Stump11289f42009-09-09 15:08:12 +0000249
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000250 return DeclSpec::TST_unspecified;
251}
252
Francois Pichet48c946e2011-04-13 02:38:49 +0000253/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
254/// if a CXXScopeSpec's type is equal to the type of one of the base classes
255/// then downgrade the missing typename error to a warning.
256/// This is needed for MSVC compatibility; Example:
257/// @code
258/// template<class T> class A {
259/// public:
260/// typedef int TYPE;
261/// };
262/// template<class T> class B : public A<T> {
263/// public:
264/// A<T>::TYPE a; // no typename required because A<T> is a base class.
265/// };
266/// @endcode
267bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS) {
268 if (CurContext->isRecord()) {
Francois Pichetefc283c2011-04-13 02:44:57 +0000269 const Type *Ty = SS->getScopeRep()->getAsType();
Francois Pichet48c946e2011-04-13 02:38:49 +0000270
271 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
272 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
273 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
274 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
275 return true;
276 }
277 return false;
278}
279
Douglas Gregor15e56022009-10-13 23:27:22 +0000280bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
281 SourceLocation IILoc,
282 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000283 CXXScopeSpec *SS,
John McCallba7bf592010-08-24 05:47:05 +0000284 ParsedType &SuggestedType) {
Douglas Gregor15e56022009-10-13 23:27:22 +0000285 // We don't have anything to suggest (yet).
John McCallba7bf592010-08-24 05:47:05 +0000286 SuggestedType = ParsedType();
Douglas Gregor15e56022009-10-13 23:27:22 +0000287
Douglas Gregor2d435302009-12-30 17:04:44 +0000288 // There may have been a typo in the name of the type. Look up typo
289 // results, in case we have something that we can suggest.
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000290 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(&II, IILoc),
291 LookupOrdinaryName, S, SS, NULL,
292 false, CTC_Type)) {
293 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
294 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
Douglas Gregor2d435302009-12-30 17:04:44 +0000295
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000296 if (Corrected.isKeyword()) {
297 // We corrected to a keyword.
298 // FIXME: Actually recover with the keyword we suggest, and emit a fix-it.
299 Diag(IILoc, diag::err_unknown_typename_suggest)
300 << &II << CorrectedQuotedStr;
301 return true;
302 } else {
303 NamedDecl *Result = Corrected.getCorrectionDecl();
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000304 if ((isa<TypeDecl>(Result) || isa<ObjCInterfaceDecl>(Result)) &&
305 !Result->isInvalidDecl()) {
306 // We found a similarly-named type or interface; suggest that.
307 if (!SS || !SS->isSet())
308 Diag(IILoc, diag::err_unknown_typename_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000309 << &II << CorrectedQuotedStr
310 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000311 else if (DeclContext *DC = computeDeclContext(*SS, false))
312 Diag(IILoc, diag::err_unknown_nested_typename_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000313 << &II << DC << CorrectedQuotedStr << SS->getRange()
314 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000315 else
316 llvm_unreachable("could not have corrected a typo here");
Douglas Gregor2d435302009-12-30 17:04:44 +0000317
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000318 Diag(Result->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000319 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000320
Douglas Gregor844cb502011-03-01 18:12:44 +0000321 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS,
322 false, false, ParsedType(),
323 /*NonTrivialTypeSourceInfo=*/true);
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000324 return true;
325 }
Douglas Gregor2d435302009-12-30 17:04:44 +0000326 }
327 }
328
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000329 if (getLangOptions().CPlusPlus) {
330 // See if II is a class template that the user forgot to pass arguments to.
331 UnqualifiedId Name;
332 Name.setIdentifier(&II, IILoc);
333 CXXScopeSpec EmptySS;
334 TemplateTy TemplateResult;
Douglas Gregor786123d2010-05-21 23:18:07 +0000335 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000336 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
John McCallba7bf592010-08-24 05:47:05 +0000337 Name, ParsedType(), true, TemplateResult,
Douglas Gregor786123d2010-05-21 23:18:07 +0000338 MemberOfUnknownSpecialization) == TNK_Type_template) {
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000339 TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
340 Diag(IILoc, diag::err_template_missing_args) << TplName;
341 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
342 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
343 << TplDecl->getTemplateParameters()->getSourceRange();
344 }
345 return true;
346 }
347 }
348
Douglas Gregor15e56022009-10-13 23:27:22 +0000349 // FIXME: Should we move the logic that tries to recover from a missing tag
350 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
351
Douglas Gregor2d435302009-12-30 17:04:44 +0000352 if (!SS || (!SS->isSet() && !SS->isInvalid()))
Douglas Gregor15e56022009-10-13 23:27:22 +0000353 Diag(IILoc, diag::err_unknown_typename) << &II;
354 else if (DeclContext *DC = computeDeclContext(*SS, false))
355 Diag(IILoc, diag::err_typename_nested_not_found)
356 << &II << DC << SS->getRange();
357 else if (isDependentScopeSpecifier(*SS)) {
Francois Pichet48c946e2011-04-13 02:38:49 +0000358 unsigned DiagID = diag::err_typename_missing;
359 if (getLangOptions().Microsoft && isMicrosoftMissingTypename(SS))
Francois Pichet93921652011-04-22 08:25:24 +0000360 DiagID = diag::warn_typename_missing;
Francois Pichet48c946e2011-04-13 02:38:49 +0000361
362 Diag(SS->getRange().getBegin(), DiagID)
Daniel Dunbar07d07852009-10-18 21:17:35 +0000363 << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
Douglas Gregor15e56022009-10-13 23:27:22 +0000364 << SourceRange(SS->getRange().getBegin(), IILoc)
Douglas Gregora771f462010-03-31 17:46:05 +0000365 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
Douglas Gregorf7d77712010-06-16 22:31:08 +0000366 SuggestedType = ActOnTypenameType(S, SourceLocation(), *SS, II, IILoc).get();
Douglas Gregor15e56022009-10-13 23:27:22 +0000367 } else {
368 assert(SS && SS->isInvalid() &&
369 "Invalid scope specifier has already been diagnosed");
370 }
371
372 return true;
373}
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000374
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000375/// \brief Determine whether the given result set contains either a type name
376/// or
377static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
378 bool CheckTemplate = R.getSema().getLangOptions().CPlusPlus &&
379 NextToken.is(tok::less);
380
381 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
382 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
383 return true;
384
385 if (CheckTemplate && isa<TemplateDecl>(*I))
386 return true;
387 }
388
389 return false;
390}
391
392Sema::NameClassification Sema::ClassifyName(Scope *S,
393 CXXScopeSpec &SS,
394 IdentifierInfo *&Name,
395 SourceLocation NameLoc,
396 const Token &NextToken) {
397 DeclarationNameInfo NameInfo(Name, NameLoc);
398 ObjCMethodDecl *CurMethod = getCurMethodDecl();
399
400 if (NextToken.is(tok::coloncolon)) {
401 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
402 QualType(), false, SS, 0, false);
403
404 }
405
406 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
407 LookupParsedName(Result, S, &SS, !CurMethod);
408
409 // Perform lookup for Objective-C instance variables (including automatically
410 // synthesized instance variables), if we're in an Objective-C method.
411 // FIXME: This lookup really, really needs to be folded in to the normal
412 // unqualified lookup mechanism.
413 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
414 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
Douglas Gregorb90f5182011-04-25 15:05:41 +0000415 if (E.get() || E.isInvalid())
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000416 return E;
417
418 // Synthesize ivars lazily.
419 if (getLangOptions().ObjCDefaultSynthProperties &&
420 getLangOptions().ObjCNonFragileABI2) {
421 if (SynthesizeProvisionalIvar(Result, Name, NameLoc)) {
422 if (const ObjCPropertyDecl *Property =
423 canSynthesizeProvisionalIvar(Name)) {
424 Diag(NameLoc, diag::warn_synthesized_ivar_access) << Name;
425 Diag(Property->getLocation(), diag::note_property_declare);
426 }
427
428 // FIXME: This is strange. Shouldn't we just take the ivar returned
429 // from SynthesizeProvisionalIvar and continue with that?
Douglas Gregorb90f5182011-04-25 15:05:41 +0000430 E = LookupInObjCMethod(Result, S, Name, true);
431 if (E.get() || E.isInvalid())
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000432 return E;
433 }
434 }
435 }
436
437 bool SecondTry = false;
438 bool IsFilteredTemplateName = false;
439
440Corrected:
441 switch (Result.getResultKind()) {
442 case LookupResult::NotFound:
443 // If an unqualified-id is followed by a '(', then we have a function
444 // call.
445 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
446 // In C++, this is an ADL-only call.
447 // FIXME: Reference?
448 if (getLangOptions().CPlusPlus)
449 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
450
451 // C90 6.3.2.2:
452 // If the expression that precedes the parenthesized argument list in a
453 // function call consists solely of an identifier, and if no
454 // declaration is visible for this identifier, the identifier is
455 // implicitly declared exactly as if, in the innermost block containing
456 // the function call, the declaration
457 //
458 // extern int identifier ();
459 //
460 // appeared.
461 //
462 // We also allow this in C99 as an extension.
463 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
464 Result.addDecl(D);
465 Result.resolveKind();
466 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
467 }
468 }
469
470 // In C, we first see whether there is a tag type by the same name, in
471 // which case it's likely that the user just forget to write "enum",
472 // "struct", or "union".
473 if (!getLangOptions().CPlusPlus && !SecondTry) {
474 Result.clear(LookupTagName);
475 LookupParsedName(Result, S, &SS);
476 if (TagDecl *Tag = Result.getAsSingle<TagDecl>()) {
477 const char *TagName = 0;
478 const char *FixItTagName = 0;
479 switch (Tag->getTagKind()) {
480 case TTK_Class:
481 TagName = "class";
482 FixItTagName = "class ";
483 break;
484
485 case TTK_Enum:
486 TagName = "enum";
487 FixItTagName = "enum ";
488 break;
489
490 case TTK_Struct:
491 TagName = "struct";
492 FixItTagName = "struct ";
493 break;
494
495 case TTK_Union:
496 TagName = "union";
497 FixItTagName = "union ";
498 break;
499 }
500
501 Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
502 << Name << TagName << getLangOptions().CPlusPlus
503 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
504 break;
505 }
506
507 Result.clear(LookupOrdinaryName);
508 }
509
510 // Perform typo correction to determine if there is another name that is
511 // close to this name.
512 if (!SecondTry) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000513 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
514 Result.getLookupKind(), S, &SS)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000515 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
516 unsigned QualifiedDiag = diag::err_no_member_suggest;
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000517 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
518 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
Douglas Gregor5e16c162011-04-27 03:47:06 +0000519
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000520 NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000521 NamedDecl *UnderlyingFirstDecl
522 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
Douglas Gregor5e16c162011-04-27 03:47:06 +0000523 if (getLangOptions().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000524 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000525 UnqualifiedDiag = diag::err_no_template_suggest;
526 QualifiedDiag = diag::err_no_member_template_suggest;
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000527 } else if (UnderlyingFirstDecl &&
528 (isa<TypeDecl>(UnderlyingFirstDecl) ||
529 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
530 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000531 UnqualifiedDiag = diag::err_unknown_typename_suggest;
532 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
533 }
534
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000535 if (Corrected.getCorrectionSpecifier())
536 SS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), SourceRange(NameLoc));
537
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000538 if (SS.isEmpty())
Douglas Gregor5e16c162011-04-27 03:47:06 +0000539 Diag(NameLoc, UnqualifiedDiag)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000540 << Name << CorrectedQuotedStr
541 << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000542 else
Douglas Gregor5e16c162011-04-27 03:47:06 +0000543 Diag(NameLoc, QualifiedDiag)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000544 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000545 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000546 << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000547
548 // Update the name, so that the caller has the new name.
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000549 Name = Corrected.getCorrectionAsIdentifierInfo();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000550
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000551 // Also update the LookupResult...
552 // FIXME: This should probably go away at some point
553 Result.clear();
554 Result.setLookupName(Corrected.getCorrection());
555 if (FirstDecl) Result.addDecl(FirstDecl);
556
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000557 // Typo correction corrected to a keyword.
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000558 if (Corrected.isKeyword())
559 return Corrected.getCorrectionAsIdentifierInfo();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000560
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000561 Diag(FirstDecl->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000562 << CorrectedQuotedStr;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000563
564 // If we found an Objective-C instance variable, let
565 // LookupInObjCMethod build the appropriate expression to
566 // reference the ivar.
567 // FIXME: This is a gross hack.
568 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
569 Result.clear();
570 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
571 return move(E);
572 }
573
574 goto Corrected;
575 }
576 }
577
578 // We failed to correct; just fall through and let the parser deal with it.
579 Result.suppressDiagnostics();
580 return NameClassification::Unknown();
581
582 case LookupResult::NotFoundInCurrentInstantiation:
583 // We performed name lookup into the current instantiation, and there were
584 // dependent bases, so we treat this result the same way as any other
585 // dependent nested-name-specifier.
586
587 // C++ [temp.res]p2:
588 // A name used in a template declaration or definition and that is
589 // dependent on a template-parameter is assumed not to name a type
590 // unless the applicable name lookup finds a type name or the name is
591 // qualified by the keyword typename.
592 //
593 // FIXME: If the next token is '<', we might want to ask the parser to
594 // perform some heroics to see if we actually have a
595 // template-argument-list, which would indicate a missing 'template'
596 // keyword here.
597 return BuildDependentDeclRefExpr(SS, NameInfo, /*TemplateArgs=*/0);
598
599 case LookupResult::Found:
600 case LookupResult::FoundOverloaded:
601 case LookupResult::FoundUnresolvedValue:
602 break;
603
604 case LookupResult::Ambiguous:
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000605 if (getLangOptions().CPlusPlus && NextToken.is(tok::less) &&
606 hasAnyAcceptableTemplateNames(Result)) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000607 // C++ [temp.local]p3:
608 // A lookup that finds an injected-class-name (10.2) can result in an
609 // ambiguity in certain cases (for example, if it is found in more than
610 // one base class). If all of the injected-class-names that are found
611 // refer to specializations of the same class template, and if the name
612 // is followed by a template-argument-list, the reference refers to the
613 // class template itself and not a specialization thereof, and is not
614 // ambiguous.
615 //
616 // This filtering can make an ambiguous result into an unambiguous one,
617 // so try again after filtering out template names.
618 FilterAcceptableTemplateNames(Result);
619 if (!Result.isAmbiguous()) {
620 IsFilteredTemplateName = true;
621 break;
622 }
623 }
624
625 // Diagnose the ambiguity and return an error.
626 return NameClassification::Error();
627 }
628
629 if (getLangOptions().CPlusPlus && NextToken.is(tok::less) &&
630 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
631 // C++ [temp.names]p3:
632 // After name lookup (3.4) finds that a name is a template-name or that
633 // an operator-function-id or a literal- operator-id refers to a set of
634 // overloaded functions any member of which is a function template if
635 // this is followed by a <, the < is always taken as the delimiter of a
636 // template-argument-list and never as the less-than operator.
637 if (!IsFilteredTemplateName)
638 FilterAcceptableTemplateNames(Result);
639
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000640 if (!Result.empty()) {
641 bool IsFunctionTemplate;
642 TemplateName Template;
643 if (Result.end() - Result.begin() > 1) {
644 IsFunctionTemplate = true;
645 Template = Context.getOverloadedTemplateName(Result.begin(),
646 Result.end());
647 } else {
648 TemplateDecl *TD
649 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
650 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
651
652 if (SS.isSet() && !SS.isInvalid())
653 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000654 /*TemplateKeyword=*/false,
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000655 TD);
656 else
657 Template = TemplateName(TD);
658 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000659
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000660 if (IsFunctionTemplate) {
661 // Function templates always go through overload resolution, at which
662 // point we'll perform the various checks (e.g., accessibility) we need
663 // to based on which function we selected.
664 Result.suppressDiagnostics();
665
666 return NameClassification::FunctionTemplate(Template);
667 }
668
669 return NameClassification::TypeTemplate(Template);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000670 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000671 }
672
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000673 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000674 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
675 DiagnoseUseOfDecl(Type, NameLoc);
676 QualType T = Context.getTypeDeclType(Type);
677 return ParsedType::make(T);
678 }
679
680 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
681 if (!Class) {
682 // FIXME: It's unfortunate that we don't have a Type node for handling this.
683 if (ObjCCompatibleAliasDecl *Alias
684 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
685 Class = Alias->getClassInterface();
686 }
687
688 if (Class) {
689 DiagnoseUseOfDecl(Class, NameLoc);
690
691 if (NextToken.is(tok::period)) {
692 // Interface. <something> is parsed as a property reference expression.
693 // Just return "unknown" as a fall-through for now.
694 Result.suppressDiagnostics();
695 return NameClassification::Unknown();
696 }
697
698 QualType T = Context.getObjCInterfaceType(Class);
699 return ParsedType::make(T);
700 }
701
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000702 if (!Result.empty() && (*Result.begin())->isCXXClassMember())
703 return BuildPossibleImplicitMemberExpr(SS, Result, 0);
704
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000705 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
706 return BuildDeclarationNameExpr(SS, Result, ADL);
707}
708
John McCall5ed6e8f2009-08-18 00:00:49 +0000709// Determines the context to return to after temporarily entering a
710// context. This depends in an unnecessarily complicated way on the
711// exact ordering of callbacks from the parser.
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000712DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000713
John McCall5ed6e8f2009-08-18 00:00:49 +0000714 // Functions defined inline within classes aren't parsed until we've
715 // finished parsing the top-level class, so the top-level class is
716 // the context we'll need to return to.
717 if (isa<FunctionDecl>(DC)) {
718 DC = DC->getLexicalParent();
719
720 // A function not defined within a class will always return to its
721 // lexical context.
722 if (!isa<CXXRecordDecl>(DC))
723 return DC;
724
725 // A C++ inline method/friend is parsed *after* the topmost class
726 // it was declared in is fully parsed ("complete"); the topmost
727 // class is the context we need to return to.
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000728 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000729 DC = RD;
730
731 // Return the declaration context of the topmost class the inline method is
732 // declared in.
733 return DC;
734 }
735
John McCalldc9796e2010-08-06 00:46:05 +0000736 // ObjCMethodDecls are parsed (for some reason) outside the context
737 // of the class.
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +0000738 if (isa<ObjCMethodDecl>(DC))
John McCalldc9796e2010-08-06 00:46:05 +0000739 return DC->getLexicalParent()->getLexicalParent();
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +0000740
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000741 return DC->getLexicalParent();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000742}
743
Douglas Gregor91f84212008-12-11 16:49:14 +0000744void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000745 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu17a37eb2008-12-08 07:14:51 +0000746 "The next DeclContext should be lexically contained in the current one.");
Chris Lattnerbec41342008-04-22 18:39:57 +0000747 CurContext = DC;
Douglas Gregor91f84212008-12-11 16:49:14 +0000748 S->setEntity(DC);
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000749}
750
Chris Lattner0a5ff0d2008-04-06 04:47:34 +0000751void Sema::PopDeclContext() {
752 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor91f84212008-12-11 16:49:14 +0000753
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000754 CurContext = getContainingDC(CurContext);
John McCalldd762d12010-07-23 22:45:07 +0000755 assert(CurContext && "Popped translation unit!");
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000756}
757
Argyrios Kyrtzidis9941a4d2009-06-17 23:19:02 +0000758/// EnterDeclaratorContext - Used when we must lookup names in the context
759/// of a declarator's nested name specifier.
John McCall6df5fef2009-12-19 10:49:29 +0000760///
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000761void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall6df5fef2009-12-19 10:49:29 +0000762 // C++0x [basic.lookup.unqual]p13:
763 // A name used in the definition of a static data member of class
764 // X (after the qualified-id of the static member) is looked up as
765 // if the name was used in a member function of X.
766 // C++0x [basic.lookup.unqual]p14:
767 // If a variable member of a namespace is defined outside of the
768 // scope of its namespace then any name used in the definition of
769 // the variable member (after the declarator-id) is looked up as
770 // if the definition of the variable member occurred in its
771 // namespace.
772 // Both of these imply that we should push a scope whose context
773 // is the semantic context of the declaration. We can't use
774 // PushDeclContext here because that context is not necessarily
775 // lexically contained in the current context. Fortunately,
776 // the containing scope should have the appropriate information.
777
778 assert(!S->getEntity() && "scope already has entity");
779
780#ifndef NDEBUG
781 Scope *Ancestor = S->getParent();
782 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
783 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
784#endif
785
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000786 CurContext = DC;
John McCall6df5fef2009-12-19 10:49:29 +0000787 S->setEntity(DC);
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000788}
789
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000790void Sema::ExitDeclaratorContext(Scope *S) {
John McCall6df5fef2009-12-19 10:49:29 +0000791 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000792
John McCall6df5fef2009-12-19 10:49:29 +0000793 // Switch back to the lexical context. The safety of this is
794 // enforced by an assert in EnterDeclaratorContext.
795 Scope *Ancestor = S->getParent();
796 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
797 CurContext = (DeclContext*) Ancestor->getEntity();
798
799 // We don't need to do anything with the scope, which is going to
800 // disappear.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000801}
802
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000803/// \brief Determine whether we allow overloading of the function
804/// PrevDecl with another declaration.
805///
806/// This routine determines whether overloading is possible, not
807/// whether some new function is actually an overload. It will return
808/// true in C++ (where we can always provide overloads) or, as an
809/// extension, in C when the previous function is already an
810/// overloaded function declaration or has the "overloadable"
811/// attribute.
John McCall1f82f242009-11-18 22:49:29 +0000812static bool AllowOverloadingOfFunction(LookupResult &Previous,
813 ASTContext &Context) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000814 if (Context.getLangOptions().CPlusPlus)
815 return true;
816
John McCall1f82f242009-11-18 22:49:29 +0000817 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000818 return true;
819
John McCall1f82f242009-11-18 22:49:29 +0000820 return (Previous.getResultKind() == LookupResult::Found
821 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000822}
823
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +0000824/// Add this decl to the scope shadowed decl chains.
John McCall759e32b2009-08-31 22:39:49 +0000825void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor07665a62009-01-05 19:45:36 +0000826 // Move up the scope chain until we find the nearest enclosing
827 // non-transparent context. The declaration will be introduced into this
828 // scope.
Mike Stump11289f42009-09-09 15:08:12 +0000829 while (S->getEntity() &&
Douglas Gregor07665a62009-01-05 19:45:36 +0000830 ((DeclContext *)S->getEntity())->isTransparentContext())
831 S = S->getParent();
832
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000833 // Add scoped declarations into their context, so that they can be
834 // found later. Declarations without a context won't be inserted
835 // into any context.
John McCall759e32b2009-08-31 22:39:49 +0000836 if (AddToContext)
837 CurContext->addDecl(D);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000838
Chandler Carruthf50ef6e2010-02-21 07:08:09 +0000839 // Out-of-line definitions shouldn't be pushed into scope in C++.
840 // Out-of-line variable and function definitions shouldn't even in C.
841 if ((getLangOptions().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
842 D->isOutOfLine())
843 return;
844
845 // Template instantiations should also not be pushed into scope.
846 if (isa<FunctionDecl>(D) &&
847 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregor5ad7c542009-09-28 18:41:37 +0000848 return;
849
John McCall9f3059a2009-10-09 21:13:30 +0000850 // If this replaces anything in the current scope,
851 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
852 IEnd = IdResolver.end();
853 for (; I != IEnd; ++I) {
John McCall48871652010-08-21 09:40:31 +0000854 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
855 S->RemoveDecl(*I);
John McCall9f3059a2009-10-09 21:13:30 +0000856 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000857
John McCall9f3059a2009-10-09 21:13:30 +0000858 // Should only need to replace one decl.
859 break;
Douglas Gregor38feed82009-04-24 02:57:34 +0000860 }
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000861 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000862
John McCall48871652010-08-21 09:40:31 +0000863 S->AddDecl(D);
Douglas Gregor88764cf2011-03-14 21:19:51 +0000864
865 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
866 // Implicitly-generated labels may end up getting generated in an order that
867 // isn't strictly lexical, which breaks name lookup. Be careful to insert
868 // the label at the appropriate place in the identifier chain.
869 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
Douglas Gregord7d7e0d2011-03-24 14:35:16 +0000870 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
Douglas Gregor46c04e72011-03-16 16:39:03 +0000871 if (IDC == CurContext) {
872 if (!S->isDeclScope(*I))
873 continue;
874 } else if (IDC->Encloses(CurContext))
Douglas Gregor88764cf2011-03-14 21:19:51 +0000875 break;
876 }
877
Douglas Gregor46c04e72011-03-16 16:39:03 +0000878 IdResolver.InsertDeclAfter(I, D);
Douglas Gregor88764cf2011-03-14 21:19:51 +0000879 } else {
880 IdResolver.AddDecl(D);
881 }
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +0000882}
883
Douglas Gregordb446112011-03-07 16:54:27 +0000884bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S,
885 bool ExplicitInstantiationOrSpecialization) {
886 return IdResolver.isDeclInScope(D, Ctx, Context, S,
887 ExplicitInstantiationOrSpecialization);
Douglas Gregor505ad492009-09-28 00:47:05 +0000888}
889
John McCallcc14d1f2010-08-24 08:50:51 +0000890Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
891 DeclContext *TargetDC = DC->getPrimaryContext();
892 do {
893 if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
894 if (ScopeDC->getPrimaryContext() == TargetDC)
895 return S;
896 } while ((S = S->getParent()));
897
898 return 0;
899}
900
John McCall1f82f242009-11-18 22:49:29 +0000901static bool isOutOfScopePreviousDeclaration(NamedDecl *,
902 DeclContext*,
903 ASTContext&);
904
905/// Filters out lookup results that don't fall within the given scope
906/// as determined by isDeclInScope.
Richard Smith3f1b5d02011-05-05 21:57:07 +0000907void Sema::FilterLookupForScope(LookupResult &R,
908 DeclContext *Ctx, Scope *S,
909 bool ConsiderLinkage,
910 bool ExplicitInstantiationOrSpecialization) {
John McCall1f82f242009-11-18 22:49:29 +0000911 LookupResult::Filter F = R.makeFilter();
912 while (F.hasNext()) {
913 NamedDecl *D = F.next();
914
Richard Smith3f1b5d02011-05-05 21:57:07 +0000915 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
John McCall1f82f242009-11-18 22:49:29 +0000916 continue;
917
918 if (ConsiderLinkage &&
Richard Smith3f1b5d02011-05-05 21:57:07 +0000919 isOutOfScopePreviousDeclaration(D, Ctx, Context))
John McCall1f82f242009-11-18 22:49:29 +0000920 continue;
921
922 F.erase();
923 }
924
925 F.done();
926}
927
928static bool isUsingDecl(NamedDecl *D) {
929 return isa<UsingShadowDecl>(D) ||
930 isa<UnresolvedUsingTypenameDecl>(D) ||
931 isa<UnresolvedUsingValueDecl>(D);
932}
933
934/// Removes using shadow declarations from the lookup results.
935static void RemoveUsingDecls(LookupResult &R) {
936 LookupResult::Filter F = R.makeFilter();
937 while (F.hasNext())
938 if (isUsingDecl(F.next()))
939 F.erase();
940
941 F.done();
942}
943
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000944/// \brief Check for this common pattern:
945/// @code
946/// class S {
947/// S(const S&); // DO NOT IMPLEMENT
948/// void operator=(const S&); // DO NOT IMPLEMENT
949/// };
950/// @endcode
951static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
952 // FIXME: Should check for private access too but access is set after we get
953 // the decl here.
Alexis Hunt4a8ea102011-05-06 20:44:56 +0000954 if (D->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000955 return false;
956
957 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
958 return CD->isCopyConstructor();
Douglas Gregora1ce1f82010-09-27 22:06:20 +0000959 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
960 return Method->isCopyAssignmentOperator();
961 return false;
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000962}
963
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000964bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
965 assert(D);
Argyrios Kyrtzidis540bc012010-08-13 18:42:29 +0000966
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000967 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
968 return false;
969
970 // Ignore class templates.
Chandler Carruth8e666512011-01-03 19:27:19 +0000971 if (D->getDeclContext()->isDependentContext() ||
972 D->getLexicalDeclContext()->isDependentContext())
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000973 return false;
974
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000975 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000976 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
977 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000978
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000979 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
980 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
981 return false;
982 } else {
983 // 'static inline' functions are used in headers; don't warn.
John McCall8e7d6562010-08-26 03:08:43 +0000984 if (FD->getStorageClass() == SC_Static &&
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000985 FD->isInlineSpecified())
986 return false;
987 }
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000988
Alexis Hunt4a8ea102011-05-06 20:44:56 +0000989 if (FD->doesThisDeclarationHaveABody() &&
John McCalld37d35b2010-10-27 01:41:35 +0000990 Context.DeclMustBeEmitted(FD))
991 return false;
John McCalld37d35b2010-10-27 01:41:35 +0000992 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
993 if (!VD->isFileVarDecl() ||
994 VD->getType().isConstant(Context) ||
995 Context.DeclMustBeEmitted(VD))
996 return false;
997
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000998 if (VD->isStaticDataMember() &&
999 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1000 return false;
1001
John McCalld37d35b2010-10-27 01:41:35 +00001002 } else {
1003 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001004 }
1005
John McCalld37d35b2010-10-27 01:41:35 +00001006 // Only warn for unused decls internal to the translation unit.
1007 if (D->getLinkage() == ExternalLinkage)
1008 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001009
John McCalld37d35b2010-10-27 01:41:35 +00001010 return true;
1011}
1012
1013void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001014 if (!D)
1015 return;
1016
1017 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1018 const FunctionDecl *First = FD->getFirstDeclaration();
1019 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1020 return; // First should already be in the vector.
1021 }
1022
1023 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1024 const VarDecl *First = VD->getFirstDeclaration();
1025 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1026 return; // First should already be in the vector.
1027 }
1028
1029 if (ShouldWarnIfUnusedFileScopedDecl(D))
1030 UnusedFileScopedDecls.push_back(D);
1031 }
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00001032
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001033static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall67da35c2010-02-04 22:26:26 +00001034 if (D->isInvalidDecl())
1035 return false;
1036
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001037 if (D->isUsed() || D->hasAttr<UnusedAttr>())
1038 return false;
John McCall67da35c2010-02-04 22:26:26 +00001039
Chris Lattnercab02a62011-02-17 20:34:02 +00001040 if (isa<LabelDecl>(D))
1041 return true;
1042
John McCall67da35c2010-02-04 22:26:26 +00001043 // White-list anything that isn't a local variable.
1044 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1045 !D->getDeclContext()->isFunctionOrMethod())
1046 return false;
1047
1048 // Types of valid local variables should be complete, so this should succeed.
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001049 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
John McCallcef15822010-03-31 02:47:45 +00001050
1051 // White-list anything with an __attribute__((unused)) type.
1052 QualType Ty = VD->getType();
1053
1054 // Only look at the outermost level of typedef.
1055 if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) {
1056 if (TT->getDecl()->hasAttr<UnusedAttr>())
1057 return false;
1058 }
1059
Douglas Gregor14f232e2010-05-08 23:05:03 +00001060 // If we failed to complete the type for some reason, or if the type is
1061 // dependent, don't diagnose the variable.
1062 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregor19defcd2010-04-27 16:20:13 +00001063 return false;
1064
John McCallcef15822010-03-31 02:47:45 +00001065 if (const TagType *TT = Ty->getAs<TagType>()) {
1066 const TagDecl *Tag = TT->getDecl();
1067 if (Tag->hasAttr<UnusedAttr>())
1068 return false;
1069
1070 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Douglas Gregor14f232e2010-05-08 23:05:03 +00001071 // FIXME: Checking for the presence of a user-declared constructor
1072 // isn't completely accurate; we'd prefer to check that the initializer
1073 // has no side effects.
1074 if (RD->hasUserDeclaredConstructor() || !RD->hasTrivialDestructor())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001075 return false;
1076 }
1077 }
John McCallcef15822010-03-31 02:47:45 +00001078
1079 // TODO: __attribute__((unused)) templates?
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001080 }
1081
John McCall67da35c2010-02-04 22:26:26 +00001082 return true;
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001083}
1084
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001085/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1086/// unless they are marked attr(unused).
Douglas Gregor14f232e2010-05-08 23:05:03 +00001087void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1088 if (!ShouldDiagnoseUnusedDecl(D))
1089 return;
1090
Chris Lattnercab02a62011-02-17 20:34:02 +00001091 unsigned DiagID;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001092 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
Chris Lattnercab02a62011-02-17 20:34:02 +00001093 DiagID = diag::warn_unused_exception_param;
1094 else if (isa<LabelDecl>(D))
1095 DiagID = diag::warn_unused_label;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001096 else
Chris Lattnercab02a62011-02-17 20:34:02 +00001097 DiagID = diag::warn_unused_variable;
1098
1099 Diag(D->getLocation(), DiagID) << D->getDeclName();
Douglas Gregor14f232e2010-05-08 23:05:03 +00001100}
1101
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001102static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1103 // Verify that we have no forward references left. If so, there was a goto
1104 // or address of a label taken, but no definition of it. Label fwd
1105 // definitions are indicated with a null substmt.
1106 if (L->getStmt() == 0)
1107 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1108}
1109
Steve Naroffc62adb62007-10-09 22:01:59 +00001110void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001111 if (S->decl_empty()) return;
Douglas Gregor5101c242008-12-05 18:15:24 +00001112 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump11289f42009-09-09 15:08:12 +00001113 "Scope shouldn't contain decls!");
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001114
Chris Lattner302b4be2006-11-19 02:31:38 +00001115 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1116 I != E; ++I) {
John McCall48871652010-08-21 09:40:31 +00001117 Decl *TmpD = (*I);
Steve Naroff9324db12007-09-13 18:10:37 +00001118 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001119
Douglas Gregor91f84212008-12-11 16:49:14 +00001120 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1121 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001122
Douglas Gregor91f84212008-12-11 16:49:14 +00001123 if (!D->getDeclName()) continue;
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001124
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00001125 // Diagnose unused variables in this scope.
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00001126 if (!S->hasErrorOccurred())
Douglas Gregor14f232e2010-05-08 23:05:03 +00001127 DiagnoseUnusedDecl(D);
1128
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001129 // If this was a forward reference to a label, verify it was defined.
1130 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1131 CheckPoppedLabel(LD, *this);
1132
Douglas Gregor91f84212008-12-11 16:49:14 +00001133 // Remove this name from our lexical scope.
1134 IdResolver.RemoveDecl(D);
Chris Lattner302b4be2006-11-19 02:31:38 +00001135 }
1136}
1137
Douglas Gregor1c283312010-08-11 12:19:30 +00001138/// \brief Look for an Objective-C class in the translation unit.
1139///
1140/// \param Id The name of the Objective-C class we're looking for. If
1141/// typo-correction fixes this name, the Id will be updated
1142/// to the fixed name.
1143///
1144/// \param IdLoc The location of the name in the translation unit.
1145///
1146/// \param TypoCorrection If true, this routine will attempt typo correction
1147/// if there is no class with the given name.
1148///
1149/// \returns The declaration of the named Objective-C class, or NULL if the
1150/// class could not be found.
1151ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1152 SourceLocation IdLoc,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001153 bool DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001154 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1155 // creation from this context.
1156 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1157
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001158 if (!IDecl && DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001159 // Perform typo correction at the given location, but only if we
1160 // find an Objective-C class name.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001161 TypoCorrection C;
1162 if ((C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1163 TUScope, NULL, NULL, false, CTC_NoKeywords)) &&
1164 (IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>())) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001165 Diag(IdLoc, diag::err_undef_interface_suggest)
1166 << Id << IDecl->getDeclName()
1167 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
1168 Diag(IDecl->getLocation(), diag::note_previous_decl)
1169 << IDecl->getDeclName();
1170
1171 Id = IDecl->getIdentifier();
1172 }
1173 }
1174
1175 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1176}
1177
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001178/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1179/// from S, where a non-field would be declared. This routine copes
1180/// with the difference between C and C++ scoping rules in structs and
1181/// unions. For example, the following code is well-formed in C but
1182/// ill-formed in C++:
1183/// @code
1184/// struct S6 {
1185/// enum { BAR } e;
1186/// };
Mike Stump11289f42009-09-09 15:08:12 +00001187///
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001188/// void test_S6() {
1189/// struct S6 a;
1190/// a.e = BAR;
1191/// }
1192/// @endcode
1193/// For the declaration of BAR, this routine will return a different
1194/// scope. The scope S will be the scope of the unnamed enumeration
1195/// within S6. In C++, this routine will return the scope associated
1196/// with S6, because the enumeration's scope is a transparent
1197/// context but structures can contain non-field names. In C, this
1198/// routine will return the translation unit scope, since the
1199/// enumeration's scope is a transparent context and structures cannot
1200/// contain non-field names.
1201Scope *Sema::getNonFieldDeclScope(Scope *S) {
1202 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Mike Stump11289f42009-09-09 15:08:12 +00001203 (S->getEntity() &&
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001204 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
1205 (S->isClassScope() && !getLangOptions().CPlusPlus))
1206 S = S->getParent();
1207 return S;
1208}
1209
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001210/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1211/// file scope. lazily create a decl for it. ForRedeclaration is true
1212/// if we're creating this built-in in anticipation of redeclaring the
1213/// built-in.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001214NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001215 Scope *S, bool ForRedeclaration,
1216 SourceLocation Loc) {
Chris Lattner9561a0b2007-01-28 08:20:04 +00001217 Builtin::ID BID = (Builtin::ID)bid;
1218
Chris Lattnerecd79c62009-06-14 00:45:47 +00001219 ASTContext::GetBuiltinTypeError Error;
Mike Stump11289f42009-09-09 15:08:12 +00001220 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor538c3d82009-02-14 01:52:53 +00001221 switch (Error) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00001222 case ASTContext::GE_None:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001223 // Okay
1224 break;
1225
Mike Stump93246cc2009-07-28 23:57:15 +00001226 case ASTContext::GE_Missing_stdio:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001227 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001228 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
Douglas Gregor538c3d82009-02-14 01:52:53 +00001229 << Context.BuiltinInfo.GetName(BID);
1230 return 0;
Mike Stumpa4de80b2009-07-28 02:25:19 +00001231
Mike Stump93246cc2009-07-28 23:57:15 +00001232 case ASTContext::GE_Missing_setjmp:
Mike Stumpa4de80b2009-07-28 02:25:19 +00001233 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001234 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
Mike Stumpa4de80b2009-07-28 02:25:19 +00001235 << Context.BuiltinInfo.GetName(BID);
1236 return 0;
Douglas Gregor538c3d82009-02-14 01:52:53 +00001237 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001238
1239 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1240 Diag(Loc, diag::ext_implicit_lib_function_decl)
1241 << Context.BuiltinInfo.GetName(BID)
1242 << R;
Douglas Gregor9eebd972009-02-16 21:58:21 +00001243 if (Context.BuiltinInfo.getHeaderName(BID) &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001244 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
Chris Lattneraf73cf62009-04-16 03:59:32 +00001245 != Diagnostic::Ignored)
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001246 Diag(Loc, diag::note_please_include_header)
1247 << Context.BuiltinInfo.getHeaderName(BID)
1248 << Context.BuiltinInfo.GetName(BID);
1249 }
1250
Argyrios Kyrtzidis6d053032008-04-17 14:47:13 +00001251 FunctionDecl *New = FunctionDecl::Create(Context,
1252 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001253 Loc, Loc, II, R, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00001254 SC_Extern,
1255 SC_None, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00001256 /*hasPrototype=*/true);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001257 New->setImplicit();
1258
Chris Lattner4dd27102008-05-05 22:18:14 +00001259 // Create Decl objects for each parameter, adding them to the
1260 // FunctionDecl.
John McCall424cec92011-01-19 06:33:43 +00001261 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner4dd27102008-05-05 22:18:14 +00001262 llvm::SmallVector<ParmVarDecl*, 16> Params;
John McCall8fb0d9d2011-05-01 22:35:37 +00001263 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1264 ParmVarDecl *parm =
1265 ParmVarDecl::Create(Context, New, SourceLocation(),
1266 SourceLocation(), 0,
1267 FT->getArgType(i), /*TInfo=*/0,
1268 SC_None, SC_None, 0);
1269 parm->setScopeInfo(0, i);
1270 Params.push_back(parm);
1271 }
Douglas Gregord5058122010-02-11 01:19:42 +00001272 New->setParams(Params.data(), Params.size());
Chris Lattner4dd27102008-05-05 22:18:14 +00001273 }
Mike Stump11289f42009-09-09 15:08:12 +00001274
1275 AddKnownFunctionAttributes(New);
1276
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001277 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregorc72e6452009-01-09 18:51:29 +00001278 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1279 // relate Scopes to DeclContexts, and probably eliminate CurContext
1280 // entirely, but we're not there yet.
1281 DeclContext *SavedContext = CurContext;
1282 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001283 PushOnScopeChains(New, TUScope);
Douglas Gregorc72e6452009-01-09 18:51:29 +00001284 CurContext = SavedContext;
Chris Lattner9561a0b2007-01-28 08:20:04 +00001285 return New;
1286}
1287
Richard Smithdda56e42011-04-15 14:24:37 +00001288/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001289/// same name and scope as a previous declaration 'Old'. Figure out
1290/// how to resolve this situation, merging decls or emitting
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001291/// diagnostics as appropriate. If there was an error, set New to be invalid.
Chris Lattner01564d92007-01-27 19:27:06 +00001292///
Richard Smithdda56e42011-04-15 14:24:37 +00001293void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
John McCall1f82f242009-11-18 22:49:29 +00001294 // If the new decl is known invalid already, don't bother doing any
1295 // merging checks.
1296 if (New->isInvalidDecl()) return;
Mike Stump11289f42009-09-09 15:08:12 +00001297
Steve Naroff44cfcb62008-09-09 14:32:20 +00001298 // Allow multiple definitions for ObjC built-in typedefs.
1299 // FIXME: Verify the underlying types are equivalent!
1300 if (getLangOptions().ObjC1) {
Chris Lattner66e32812008-11-20 05:41:43 +00001301 const IdentifierInfo *TypeID = New->getIdentifier();
1302 switch (TypeID->getLength()) {
1303 default: break;
Mike Stump11289f42009-09-09 15:08:12 +00001304 case 2:
Chris Lattner66e32812008-11-20 05:41:43 +00001305 if (!TypeID->isStr("id"))
1306 break;
David Chisnall9f57c292009-08-17 16:35:33 +00001307 Context.ObjCIdRedefinitionType = New->getUnderlyingType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001308 // Install the built-in type for 'id', ignoring the current definition.
1309 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1310 return;
Chris Lattner66e32812008-11-20 05:41:43 +00001311 case 5:
1312 if (!TypeID->isStr("Class"))
1313 break;
David Chisnall9f57c292009-08-17 16:35:33 +00001314 Context.ObjCClassRedefinitionType = New->getUnderlyingType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001315 // Install the built-in type for 'Class', ignoring the current definition.
1316 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001317 return;
Chris Lattner66e32812008-11-20 05:41:43 +00001318 case 3:
1319 if (!TypeID->isStr("SEL"))
1320 break;
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00001321 Context.ObjCSelRedefinitionType = New->getUnderlyingType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001322 // Install the built-in type for 'SEL', ignoring the current definition.
1323 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001324 return;
Chris Lattner66e32812008-11-20 05:41:43 +00001325 case 8:
1326 if (!TypeID->isStr("Protocol"))
1327 break;
Steve Naroff44cfcb62008-09-09 14:32:20 +00001328 Context.setObjCProtoType(New->getUnderlyingType());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001329 return;
Steve Naroff44cfcb62008-09-09 14:32:20 +00001330 }
1331 // Fall through - the typedef name was not a builtin type.
1332 }
John McCall1f82f242009-11-18 22:49:29 +00001333
Douglas Gregorfb034662009-01-28 17:15:10 +00001334 // Verify the old decl was also a type.
John McCall91f1a022009-12-30 00:31:22 +00001335 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1336 if (!Old) {
Mike Stump11289f42009-09-09 15:08:12 +00001337 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001338 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00001339
1340 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001341 if (OldD->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +00001342 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall1f82f242009-11-18 22:49:29 +00001343
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001344 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00001345 }
Douglas Gregorfb034662009-01-28 17:15:10 +00001346
John McCall1f82f242009-11-18 22:49:29 +00001347 // If the old declaration is invalid, just give up here.
1348 if (Old->isInvalidDecl())
1349 return New->setInvalidDecl();
1350
Mike Stump11289f42009-09-09 15:08:12 +00001351 // Determine the "old" type we'll use for checking and diagnostics.
Douglas Gregorfb034662009-01-28 17:15:10 +00001352 QualType OldType;
Richard Smithdda56e42011-04-15 14:24:37 +00001353 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
Douglas Gregorfb034662009-01-28 17:15:10 +00001354 OldType = OldTypedef->getUnderlyingType();
1355 else
1356 OldType = Context.getTypeDeclType(Old);
1357
Chris Lattnerf9c49e52008-07-25 18:44:27 +00001358 // If the typedef types are not identical, reject them in all languages and
1359 // with any extensions enabled.
Douglas Gregorfb034662009-01-28 17:15:10 +00001360
Mike Stump11289f42009-09-09 15:08:12 +00001361 if (OldType != New->getUnderlyingType() &&
1362 Context.getCanonicalType(OldType) !=
Chris Lattnerf9c49e52008-07-25 18:44:27 +00001363 Context.getCanonicalType(New->getUnderlyingType())) {
Richard Smithdda56e42011-04-15 14:24:37 +00001364 int Kind = 0;
1365 if (isa<TypeAliasDecl>(Old))
1366 Kind = 1;
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00001367 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Richard Smithdda56e42011-04-15 14:24:37 +00001368 << Kind << New->getUnderlyingType() << OldType;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001369 if (Old->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +00001370 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001371 return New->setInvalidDecl();
Chris Lattnerf9c49e52008-07-25 18:44:27 +00001372 }
Mike Stump11289f42009-09-09 15:08:12 +00001373
John McCall91f1a022009-12-30 00:31:22 +00001374 // The types match. Link up the redeclaration chain if the old
1375 // declaration was a typedef.
1376 // FIXME: this is a potential source of wierdness if the type
1377 // spellings don't match exactly.
Richard Smithdda56e42011-04-15 14:24:37 +00001378 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old))
1379 New->setPreviousDeclaration(Typedef);
John McCall91f1a022009-12-30 00:31:22 +00001380
Steve Naroff7cae42b2009-07-10 23:34:53 +00001381 if (getLangOptions().Microsoft)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001382 return;
Eli Friedman61b529f2008-06-11 06:20:39 +00001383
Chris Lattner2581fc32009-04-17 22:04:20 +00001384 if (getLangOptions().CPlusPlus) {
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001385 // C++ [dcl.typedef]p2:
1386 // In a given non-class scope, a typedef specifier can be used to
1387 // redefine the name of any type declared in that scope to refer
1388 // to the type to which it already refers.
Chris Lattner2581fc32009-04-17 22:04:20 +00001389 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001390 return;
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001391
1392 // C++0x [dcl.typedef]p4:
1393 // In a given class scope, a typedef specifier can be used to redefine
1394 // any class-name declared in that scope that is not also a typedef-name
1395 // to refer to the type to which it already refers.
1396 //
1397 // This wording came in via DR424, which was a correction to the
1398 // wording in DR56, which accidentally banned code like:
1399 //
1400 // struct S {
1401 // typedef struct A { } A;
1402 // };
1403 //
1404 // in the C++03 standard. We implement the C++0x semantics, which
1405 // allow the above but disallow
1406 //
1407 // struct S {
1408 // typedef int I;
1409 // typedef int I;
1410 // };
1411 //
1412 // since that was the intent of DR56.
Richard Smithdda56e42011-04-15 14:24:37 +00001413 if (!isa<TypedefNameDecl>(Old))
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001414 return;
1415
Chris Lattner2581fc32009-04-17 22:04:20 +00001416 Diag(New->getLocation(), diag::err_redefinition)
1417 << New->getDeclName();
1418 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001419 return New->setInvalidDecl();
Daniel Dunbar84b70f72008-09-12 18:10:20 +00001420 }
Eli Friedman61b529f2008-06-11 06:20:39 +00001421
Chris Lattner2581fc32009-04-17 22:04:20 +00001422 // If we have a redefinition of a typedef in C, emit a warning. This warning
1423 // is normally mapped to an error, but can be controlled with
Eli Friedman319ce952009-06-04 23:03:07 +00001424 // -Wtypedef-redefinition. If either the original or the redefinition is
1425 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner30d0cfd2010-03-01 20:59:53 +00001426 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman319ce952009-06-04 23:03:07 +00001427 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1428 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattner9a845892009-04-27 01:46:12 +00001429 return;
Mike Stump11289f42009-09-09 15:08:12 +00001430
Chris Lattner2581fc32009-04-17 22:04:20 +00001431 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1432 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001433 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001434 return;
Chris Lattner01564d92007-01-27 19:27:06 +00001435}
1436
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001437/// DeclhasAttr - returns true if decl Declaration already has the target
1438/// attribute.
Mike Stump11289f42009-09-09 15:08:12 +00001439static bool
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001440DeclHasAttr(const Decl *D, const Attr *A) {
1441 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1442 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1443 if ((*i)->getKind() == A->getKind()) {
1444 // FIXME: Don't hardcode this check
1445 if (OA && isa<OwnershipAttr>(*i))
1446 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
Chris Lattner84966392008-03-03 03:28:21 +00001447 return true;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001448 }
Chris Lattner84966392008-03-03 03:28:21 +00001449
1450 return false;
1451}
1452
John McCallf79e87d2011-03-02 04:00:57 +00001453/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
1454static void mergeDeclAttributes(Decl *newDecl, const Decl *oldDecl,
1455 ASTContext &C) {
1456 if (!oldDecl->hasAttrs())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001457 return;
John McCallf79e87d2011-03-02 04:00:57 +00001458
1459 bool foundAny = newDecl->hasAttrs();
1460
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001461 // Ensure that any moving of objects within the allocated map is done before
1462 // we process them.
John McCallf79e87d2011-03-02 04:00:57 +00001463 if (!foundAny) newDecl->setAttrs(AttrVec());
1464
Peter Collingbourneab8bc062011-01-21 02:08:36 +00001465 for (specific_attr_iterator<InheritableAttr>
John McCallf79e87d2011-03-02 04:00:57 +00001466 i = oldDecl->specific_attr_begin<InheritableAttr>(),
1467 e = oldDecl->specific_attr_end<InheritableAttr>(); i != e; ++i) {
1468 if (!DeclHasAttr(newDecl, *i)) {
1469 InheritableAttr *newAttr = cast<InheritableAttr>((*i)->clone(C));
1470 newAttr->setInherited(true);
1471 newDecl->addAttr(newAttr);
1472 foundAny = true;
Chris Lattner84966392008-03-03 03:28:21 +00001473 }
1474 }
John McCallf79e87d2011-03-02 04:00:57 +00001475
1476 if (!foundAny) newDecl->dropAttrs();
1477}
1478
1479/// mergeParamDeclAttributes - Copy attributes from the old parameter
1480/// to the new one.
1481static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
1482 const ParmVarDecl *oldDecl,
1483 ASTContext &C) {
1484 if (!oldDecl->hasAttrs())
1485 return;
1486
1487 bool foundAny = newDecl->hasAttrs();
1488
1489 // Ensure that any moving of objects within the allocated map is
1490 // done before we process them.
1491 if (!foundAny) newDecl->setAttrs(AttrVec());
1492
1493 for (specific_attr_iterator<InheritableParamAttr>
1494 i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
1495 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
1496 if (!DeclHasAttr(newDecl, *i)) {
1497 InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C));
1498 newAttr->setInherited(true);
1499 newDecl->addAttr(newAttr);
1500 foundAny = true;
1501 }
1502 }
1503
1504 if (!foundAny) newDecl->dropAttrs();
Chris Lattner84966392008-03-03 03:28:21 +00001505}
1506
Dan Gohman28ade552010-07-26 21:25:24 +00001507namespace {
1508
Douglas Gregora74a2972009-03-06 22:43:54 +00001509/// Used in MergeFunctionDecl to keep track of function parameters in
1510/// C.
1511struct GNUCompatibleParamWarning {
1512 ParmVarDecl *OldParm;
1513 ParmVarDecl *NewParm;
1514 QualType PromotedType;
1515};
1516
Dan Gohman28ade552010-07-26 21:25:24 +00001517}
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001518
1519/// getSpecialMember - get the special member enum for a method.
Anders Carlsson05bf0092010-04-22 05:40:53 +00001520Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001521 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001522 if (Ctor->isDefaultConstructor())
1523 return Sema::CXXDefaultConstructor;
Alexis Huntd051b872011-05-26 01:26:05 +00001524
1525 if (Ctor->isCopyConstructor())
1526 return Sema::CXXCopyConstructor;
1527
1528 if (Ctor->isMoveConstructor())
1529 return Sema::CXXMoveConstructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00001530 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001531 return Sema::CXXDestructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00001532 } else if (MD->isCopyAssignmentOperator()) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001533 return Sema::CXXCopyAssignment;
Alexis Hunt119c10e2011-05-25 23:16:36 +00001534 }
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001535
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001536 return Sema::CXXInvalid;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001537}
1538
Sebastian Redl243d9052010-06-09 21:17:41 +00001539/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisfea48452010-02-18 02:00:42 +00001540/// only extern inline functions can be redefined, and even then only in
1541/// GNU89 mode.
1542static bool canRedefineFunction(const FunctionDecl *FD,
1543 const LangOptions& LangOpts) {
Eli Friedman51dd0182011-06-13 23:56:42 +00001544 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
1545 !LangOpts.CPlusPlus &&
Charles Davisfea48452010-02-18 02:00:42 +00001546 FD->isInlineSpecified() &&
John McCall8e7d6562010-08-26 03:08:43 +00001547 FD->getStorageClass() == SC_Extern);
Charles Davisfea48452010-02-18 02:00:42 +00001548}
1549
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001550/// MergeFunctionDecl - We just parsed a function 'New' from
1551/// declarator D which has the same name and scope as a previous
1552/// declaration 'Old'. Figure out how to resolve this situation,
1553/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001554///
1555/// In C++, New and Old must be declarations that are not
1556/// overloaded. Use IsOverload to determine whether New and Old are
1557/// overloaded, and to select the Old declaration that New should be
1558/// merged with.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001559///
1560/// Returns true if there was an error, false otherwise.
1561bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +00001562 // Verify the old decl was also a function.
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001563 FunctionDecl *Old = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001564 if (FunctionTemplateDecl *OldFunctionTemplate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001565 = dyn_cast<FunctionTemplateDecl>(OldD))
1566 Old = OldFunctionTemplate->getTemplatedDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001567 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001568 Old = dyn_cast<FunctionDecl>(OldD);
Chris Lattnerc511efb2007-01-27 19:32:14 +00001569 if (!Old) {
John McCalle29c5cd2009-12-10 19:51:03 +00001570 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
1571 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
1572 Diag(Shadow->getTargetDecl()->getLocation(),
1573 diag::note_using_decl_target);
1574 Diag(Shadow->getUsingDecl()->getLocation(),
1575 diag::note_using_decl) << 0;
1576 return true;
1577 }
1578
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00001579 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001580 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001581 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001582 return true;
Chris Lattnerc511efb2007-01-27 19:32:14 +00001583 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001584
1585 // Determine whether the previous declaration was a definition,
1586 // implicit declaration, or a declaration.
1587 diag::kind PrevDiag;
1588 if (Old->isThisDeclarationADefinition())
Chris Lattner0369c572008-11-23 23:12:31 +00001589 PrevDiag = diag::note_previous_definition;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001590 else if (Old->isImplicit())
1591 PrevDiag = diag::note_previous_implicit_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00001592 else
Chris Lattner0369c572008-11-23 23:12:31 +00001593 PrevDiag = diag::note_previous_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00001594
Chris Lattnerfc4379f2008-04-06 23:10:54 +00001595 QualType OldQType = Context.getCanonicalType(Old->getType());
1596 QualType NewQType = Context.getCanonicalType(New->getType());
Mike Stump11289f42009-09-09 15:08:12 +00001597
Charles Davisfea48452010-02-18 02:00:42 +00001598 // Don't complain about this if we're in GNU89 mode and the old function
1599 // is an extern inline function.
Douglas Gregore62c0a42009-02-24 01:23:02 +00001600 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCall8e7d6562010-08-26 03:08:43 +00001601 New->getStorageClass() == SC_Static &&
1602 Old->getStorageClass() != SC_Static &&
Charles Davisfea48452010-02-18 02:00:42 +00001603 !canRedefineFunction(Old, getLangOptions())) {
Francois Pichet6841a122011-04-22 19:50:06 +00001604 if (getLangOptions().Microsoft) {
1605 Diag(New->getLocation(), diag::warn_static_non_static) << New;
1606 Diag(Old->getLocation(), PrevDiag);
1607 } else {
1608 Diag(New->getLocation(), diag::err_static_non_static) << New;
1609 Diag(Old->getLocation(), PrevDiag);
1610 return true;
1611 }
Douglas Gregore62c0a42009-02-24 01:23:02 +00001612 }
1613
John McCallcddbad02010-02-04 05:44:44 +00001614 // If a function is first declared with a calling convention, but is
1615 // later declared or defined without one, the second decl assumes the
1616 // calling convention of the first.
1617 //
1618 // For the new decl, we have to look at the NON-canonical type to tell the
1619 // difference between a function that really doesn't have a calling
1620 // convention and one that is declared cdecl. That's because in
1621 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
1622 // because it is the default calling convention.
1623 //
1624 // Note also that we DO NOT return at this point, because we still have
1625 // other tests to run.
John McCall4f5019e2010-12-19 02:44:49 +00001626 const FunctionType *OldType = cast<FunctionType>(OldQType);
John McCallcddbad02010-02-04 05:44:44 +00001627 const FunctionType *NewType = New->getType()->getAs<FunctionType>();
John McCall4f5019e2010-12-19 02:44:49 +00001628 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
1629 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
1630 bool RequiresAdjustment = false;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001631 if (OldTypeInfo.getCC() != CC_Default &&
1632 NewTypeInfo.getCC() == CC_Default) {
John McCall4f5019e2010-12-19 02:44:49 +00001633 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
1634 RequiresAdjustment = true;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001635 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
1636 NewTypeInfo.getCC())) {
John McCallcddbad02010-02-04 05:44:44 +00001637 // Calling conventions really aren't compatible, so complain.
John McCallab26cfa2010-02-05 21:31:56 +00001638 Diag(New->getLocation(), diag::err_cconv_change)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001639 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
1640 << (OldTypeInfo.getCC() == CC_Default)
1641 << (OldTypeInfo.getCC() == CC_Default ? "" :
1642 FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
John McCallab26cfa2010-02-05 21:31:56 +00001643 Diag(Old->getLocation(), diag::note_previous_declaration);
John McCallcddbad02010-02-04 05:44:44 +00001644 return true;
1645 }
1646
John McCallab26cfa2010-02-05 21:31:56 +00001647 // FIXME: diagnose the other way around?
John McCall4f5019e2010-12-19 02:44:49 +00001648 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
1649 NewTypeInfo = NewTypeInfo.withNoReturn(true);
1650 RequiresAdjustment = true;
John McCallab26cfa2010-02-05 21:31:56 +00001651 }
1652
Douglas Gregor77e274f2010-06-18 21:30:25 +00001653 // Merge regparm attribute.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00001654 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
1655 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
1656 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregor77e274f2010-06-18 21:30:25 +00001657 Diag(New->getLocation(), diag::err_regparm_mismatch)
1658 << NewType->getRegParmType()
1659 << OldType->getRegParmType();
1660 Diag(Old->getLocation(), diag::note_previous_declaration);
1661 return true;
1662 }
John McCall4f5019e2010-12-19 02:44:49 +00001663
1664 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
1665 RequiresAdjustment = true;
1666 }
1667
1668 if (RequiresAdjustment) {
1669 NewType = Context.adjustFunctionType(NewType, NewTypeInfo);
1670 New->setType(QualType(NewType, 0));
1671 NewQType = Context.getCanonicalType(New->getType());
Douglas Gregor77e274f2010-06-18 21:30:25 +00001672 }
1673
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001674 if (getLangOptions().CPlusPlus) {
1675 // (C++98 13.1p2):
1676 // Certain function declarations cannot be overloaded:
Mike Stump11289f42009-09-09 15:08:12 +00001677 // -- Function declarations that differ only in the return type
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001678 // cannot be overloaded.
John McCall4f5019e2010-12-19 02:44:49 +00001679 QualType OldReturnType = OldType->getResultType();
1680 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00001681 QualType ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001682 if (OldReturnType != NewReturnType) {
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00001683 if (NewReturnType->isObjCObjectPointerType()
1684 && OldReturnType->isObjCObjectPointerType())
1685 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
1686 if (ResQT.isNull()) {
Argyrios Kyrtzidis3d320862011-02-05 05:54:49 +00001687 if (New->isCXXClassMember() && New->isOutOfLine())
1688 Diag(New->getLocation(),
1689 diag::err_member_def_does_not_match_ret_type) << New;
1690 else
1691 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00001692 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1693 return true;
1694 }
1695 else
1696 NewQType = ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001697 }
1698
1699 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
John McCall43314ab2010-04-13 07:45:41 +00001700 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001701 if (OldMethod && NewMethod) {
John McCall43314ab2010-04-13 07:45:41 +00001702 // Preserve triviality.
1703 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichetc2fac712011-05-14 19:17:07 +00001704
John McCall43314ab2010-04-13 07:45:41 +00001705 bool isFriend = NewMethod->getFriendObjectKind();
1706
Francois Pichetc2fac712011-05-14 19:17:07 +00001707 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord()) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001708 // -- Member function declarations with the same name and the
1709 // same parameter types cannot be overloaded if any of them
1710 // is a static member function declaration.
1711 if (OldMethod->isStatic() || NewMethod->isStatic()) {
1712 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
1713 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1714 return true;
1715 }
1716
1717 // C++ [class.mem]p1:
1718 // [...] A member shall not be declared twice in the
1719 // member-specification, except that a nested class or member
1720 // class template can be declared and then later defined.
1721 unsigned NewDiag;
1722 if (isa<CXXConstructorDecl>(OldMethod))
1723 NewDiag = diag::err_constructor_redeclared;
1724 else if (isa<CXXDestructorDecl>(NewMethod))
1725 NewDiag = diag::err_destructor_redeclared;
1726 else if (isa<CXXConversionDecl>(NewMethod))
1727 NewDiag = diag::err_conv_function_redeclared;
1728 else
1729 NewDiag = diag::err_member_redeclared;
1730
1731 Diag(New->getLocation(), NewDiag);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001732 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
John McCall43314ab2010-04-13 07:45:41 +00001733
1734 // Complain if this is an explicit declaration of a special
1735 // member that was initially declared implicitly.
1736 //
1737 // As an exception, it's okay to befriend such methods in order
1738 // to permit the implicit constructor/destructor/operator calls.
1739 } else if (OldMethod->isImplicit()) {
1740 if (isFriend) {
1741 NewMethod->setImplicit();
1742 } else {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001743 Diag(NewMethod->getLocation(),
1744 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson05bf0092010-04-22 05:40:53 +00001745 << New << getSpecialMember(OldMethod);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001746 return true;
1747 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00001748 } else if (OldMethod->isExplicitlyDefaulted()) {
1749 Diag(NewMethod->getLocation(),
1750 diag::err_definition_of_explicitly_defaulted_member)
1751 << getSpecialMember(OldMethod);
1752 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001753 }
1754 }
1755
1756 // (C++98 8.3.5p3):
1757 // All declarations for a function shall agree exactly in both the
1758 // return type and the parameter-type-list.
John McCall4f5019e2010-12-19 02:44:49 +00001759 // We also want to respect all the extended bits except noreturn.
1760
1761 // noreturn should now match unless the old type info didn't have it.
1762 QualType OldQTypeForComparison = OldQType;
1763 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
1764 assert(OldQType == QualType(OldType, 0));
1765 const FunctionType *OldTypeForComparison
1766 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
1767 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
1768 assert(OldQTypeForComparison.isCanonical());
1769 }
1770
1771 if (OldQTypeForComparison == NewQType)
Douglas Gregore62c0a42009-02-24 01:23:02 +00001772 return MergeCompatibleFunctionDecls(New, Old);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001773
1774 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor89f238c2008-04-21 02:02:58 +00001775 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001776
1777 // C: Function types need to be compatible, not identical. This handles
Steve Naroff012484d2008-01-14 20:51:29 +00001778 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001779 if (!getLangOptions().CPlusPlus &&
Eli Friedman47f77112008-08-22 00:56:42 +00001780 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall9dd450b2009-09-21 23:43:11 +00001781 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
1782 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001783 const FunctionProtoType *OldProto = 0;
1784 if (isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregora74a2972009-03-06 22:43:54 +00001785 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregorbcbf8632009-02-16 18:20:44 +00001786 // The old declaration provided a function prototype, but the
1787 // new declaration does not. Merge in the prototype.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001788 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Douglas Gregorbcbf8632009-02-16 18:20:44 +00001789 llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
1790 OldProto->arg_type_end());
1791 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
Jay Foad7d0479f2009-05-21 09:52:38 +00001792 ParamTypes.data(), ParamTypes.size(),
John McCalldb40c7f2010-12-14 08:05:40 +00001793 OldProto->getExtProtoInfo());
Douglas Gregorbcbf8632009-02-16 18:20:44 +00001794 New->setType(NewQType);
Anders Carlssone0dd1d52009-05-14 21:46:00 +00001795 New->setHasInheritedPrototype();
Douglas Gregorbfdd6072009-02-16 20:58:07 +00001796
1797 // Synthesize a parameter for each argument type.
1798 llvm::SmallVector<ParmVarDecl*, 16> Params;
Mike Stump11289f42009-09-09 15:08:12 +00001799 for (FunctionProtoType::arg_type_iterator
1800 ParamType = OldProto->arg_type_begin(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00001801 ParamEnd = OldProto->arg_type_end();
1802 ParamType != ParamEnd; ++ParamType) {
1803 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001804 SourceLocation(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00001805 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00001806 *ParamType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00001807 SC_None, SC_None,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001808 0);
John McCall8fb0d9d2011-05-01 22:35:37 +00001809 Param->setScopeInfo(0, Params.size());
Douglas Gregorbfdd6072009-02-16 20:58:07 +00001810 Param->setImplicit();
1811 Params.push_back(Param);
1812 }
1813
Douglas Gregord5058122010-02-11 01:19:42 +00001814 New->setParams(Params.data(), Params.size());
Mike Stump11289f42009-09-09 15:08:12 +00001815 }
Douglas Gregorbcbf8632009-02-16 18:20:44 +00001816
Douglas Gregore62c0a42009-02-24 01:23:02 +00001817 return MergeCompatibleFunctionDecls(New, Old);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001818 }
Chris Lattner45d561a2007-11-06 06:07:26 +00001819
Douglas Gregora74a2972009-03-06 22:43:54 +00001820 // GNU C permits a K&R definition to follow a prototype declaration
1821 // if the declared types of the parameters in the K&R definition
1822 // match the types in the prototype declaration, even when the
1823 // promoted types of the parameters from the K&R definition differ
1824 // from the types in the prototype. GCC then keeps the types from
1825 // the prototype.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001826 //
1827 // If a variadic prototype is followed by a non-variadic K&R definition,
1828 // the K&R definition becomes variadic. This is sort of an edge case, but
1829 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
1830 // C99 6.9.1p8.
Douglas Gregora74a2972009-03-06 22:43:54 +00001831 if (!getLangOptions().CPlusPlus &&
Douglas Gregora74a2972009-03-06 22:43:54 +00001832 Old->hasPrototype() && !New->hasPrototype() &&
John McCall9dd450b2009-09-21 23:43:11 +00001833 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregora74a2972009-03-06 22:43:54 +00001834 Old->getNumParams() == New->getNumParams()) {
1835 llvm::SmallVector<QualType, 16> ArgTypes;
1836 llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump11289f42009-09-09 15:08:12 +00001837 const FunctionProtoType *OldProto
John McCall9dd450b2009-09-21 23:43:11 +00001838 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00001839 const FunctionProtoType *NewProto
John McCall9dd450b2009-09-21 23:43:11 +00001840 = New->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00001841
Douglas Gregora74a2972009-03-06 22:43:54 +00001842 // Determine whether this is the GNU C extension.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001843 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
1844 NewProto->getResultType());
1845 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump11289f42009-09-09 15:08:12 +00001846 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001847 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregora74a2972009-03-06 22:43:54 +00001848 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
1849 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump11289f42009-09-09 15:08:12 +00001850 if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregora74a2972009-03-06 22:43:54 +00001851 NewProto->getArgType(Idx))) {
1852 ArgTypes.push_back(NewParm->getType());
1853 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor17ea3f52010-07-29 15:18:02 +00001854 NewParm->getType(),
1855 /*CompareUnqualified=*/true)) {
Mike Stump11289f42009-09-09 15:08:12 +00001856 GNUCompatibleParamWarning Warn
Douglas Gregora74a2972009-03-06 22:43:54 +00001857 = { OldParm, NewParm, NewProto->getArgType(Idx) };
1858 Warnings.push_back(Warn);
1859 ArgTypes.push_back(NewParm->getType());
1860 } else
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001861 LooseCompatible = false;
Douglas Gregora74a2972009-03-06 22:43:54 +00001862 }
1863
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001864 if (LooseCompatible) {
Douglas Gregora74a2972009-03-06 22:43:54 +00001865 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
1866 Diag(Warnings[Warn].NewParm->getLocation(),
1867 diag::ext_param_promoted_not_compatible_with_prototype)
1868 << Warnings[Warn].PromotedType
1869 << Warnings[Warn].OldParm->getType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00001870 if (Warnings[Warn].OldParm->getLocation().isValid())
1871 Diag(Warnings[Warn].OldParm->getLocation(),
1872 diag::note_previous_declaration);
Douglas Gregora74a2972009-03-06 22:43:54 +00001873 }
1874
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001875 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
1876 ArgTypes.size(),
John McCalldb40c7f2010-12-14 08:05:40 +00001877 OldProto->getExtProtoInfo()));
Douglas Gregora74a2972009-03-06 22:43:54 +00001878 return MergeCompatibleFunctionDecls(New, Old);
1879 }
1880
1881 // Fall through to diagnose conflicting types.
1882 }
1883
Steve Naroff17832a42008-01-16 15:01:34 +00001884 // A function that has already been declared has been redeclared or defined
1885 // with a different type- show appropriate diagnostic
Douglas Gregor15fc9562009-09-12 00:22:50 +00001886 if (unsigned BuiltinID = Old->getBuiltinID()) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001887 // The user has declared a builtin function with an incompatible
1888 // signature.
1889 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
1890 // The function the user is redeclaring is a library-defined
1891 // function like 'malloc' or 'printf'. Warn about the
Douglas Gregor893c2c92009-03-23 17:47:24 +00001892 // redeclaration, then pretend that we don't know about this
1893 // library built-in.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001894 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
1895 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
1896 << Old << Old->getType();
Douglas Gregor893c2c92009-03-23 17:47:24 +00001897 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
1898 Old->setInvalidDecl();
1899 return false;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001900 }
Steve Naroff17832a42008-01-16 15:01:34 +00001901
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001902 PrevDiag = diag::note_previous_builtin_declaration;
1903 }
1904
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001905 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001906 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001907 return true;
Chris Lattner01564d92007-01-27 19:27:06 +00001908}
1909
Douglas Gregore62c0a42009-02-24 01:23:02 +00001910/// \brief Completes the merge of two function declarations that are
Mike Stump11289f42009-09-09 15:08:12 +00001911/// known to be compatible.
Douglas Gregore62c0a42009-02-24 01:23:02 +00001912///
1913/// This routine handles the merging of attributes and other
1914/// properties of function declarations form the old declaration to
1915/// the new declaration, once we know that New is in fact a
1916/// redeclaration of Old.
1917///
1918/// \returns false
1919bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
1920 // Merge the attributes
John McCallf79e87d2011-03-02 04:00:57 +00001921 mergeDeclAttributes(New, Old, Context);
Douglas Gregore62c0a42009-02-24 01:23:02 +00001922
1923 // Merge the storage class.
John McCall8e7d6562010-08-26 03:08:43 +00001924 if (Old->getStorageClass() != SC_Extern &&
1925 Old->getStorageClass() != SC_None)
Douglas Gregor76fe50c2009-04-28 06:37:30 +00001926 New->setStorageClass(Old->getStorageClass());
Douglas Gregore62c0a42009-02-24 01:23:02 +00001927
Douglas Gregore62c0a42009-02-24 01:23:02 +00001928 // Merge "pure" flag.
1929 if (Old->isPure())
1930 New->setPure();
1931
John McCallf79e87d2011-03-02 04:00:57 +00001932 // Merge attributes from the parameters. These can mismatch with K&R
1933 // declarations.
1934 if (New->getNumParams() == Old->getNumParams())
1935 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
1936 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
1937 Context);
1938
Douglas Gregore62c0a42009-02-24 01:23:02 +00001939 if (getLangOptions().CPlusPlus)
1940 return MergeCXXFunctionDecl(New, Old);
1941
1942 return false;
1943}
1944
John McCall31168b02011-06-15 23:02:42 +00001945
John McCallf79e87d2011-03-02 04:00:57 +00001946void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
1947 const ObjCMethodDecl *oldMethod) {
1948 // Merge the attributes.
1949 mergeDeclAttributes(newMethod, oldMethod, Context);
1950
1951 // Merge attributes from the parameters.
1952 for (ObjCMethodDecl::param_iterator oi = oldMethod->param_begin(),
1953 ni = newMethod->param_begin(), ne = newMethod->param_end();
1954 ni != ne; ++ni, ++oi)
Douglas Gregor33823722011-06-11 01:09:30 +00001955 mergeParamDeclAttributes(*ni, *oi, Context);
1956
1957 CheckObjCMethodOverride(newMethod, oldMethod, true);
John McCallf79e87d2011-03-02 04:00:57 +00001958}
1959
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001960/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
1961/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith30482bc2011-02-20 03:19:35 +00001962/// emitting diagnostics as appropriate.
1963///
1964/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
1965/// to here in AddInitializerToDecl and AddCXXDirectInitializerToDecl. We can't
1966/// check them before the initializer is attached.
1967///
1968void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) {
1969 if (New->isInvalidDecl() || Old->isInvalidDecl())
1970 return;
1971
1972 QualType MergedT;
1973 if (getLangOptions().CPlusPlus) {
1974 AutoType *AT = New->getType()->getContainedAutoType();
1975 if (AT && !AT->isDeduced()) {
1976 // We don't know what the new type is until the initializer is attached.
1977 return;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001978 } else if (Context.hasSameType(New->getType(), Old->getType())) {
1979 // These could still be something that needs exception specs checked.
1980 return MergeVarDeclExceptionSpecs(New, Old);
1981 }
Richard Smith30482bc2011-02-20 03:19:35 +00001982 // C++ [basic.link]p10:
1983 // [...] the types specified by all declarations referring to a given
1984 // object or function shall be identical, except that declarations for an
1985 // array object can specify array types that differ by the presence or
1986 // absence of a major array bound (8.3.4).
1987 else if (Old->getType()->isIncompleteArrayType() &&
1988 New->getType()->isArrayType()) {
1989 CanQual<ArrayType> OldArray
1990 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1991 CanQual<ArrayType> NewArray
1992 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1993 if (OldArray->getElementType() == NewArray->getElementType())
1994 MergedT = New->getType();
1995 } else if (Old->getType()->isArrayType() &&
1996 New->getType()->isIncompleteArrayType()) {
1997 CanQual<ArrayType> OldArray
1998 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1999 CanQual<ArrayType> NewArray
2000 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2001 if (OldArray->getElementType() == NewArray->getElementType())
2002 MergedT = Old->getType();
2003 } else if (New->getType()->isObjCObjectPointerType()
2004 && Old->getType()->isObjCObjectPointerType()) {
2005 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2006 Old->getType());
2007 }
2008 } else {
2009 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2010 }
2011 if (MergedT.isNull()) {
2012 Diag(New->getLocation(), diag::err_redefinition_different_type)
2013 << New->getDeclName();
2014 Diag(Old->getLocation(), diag::note_previous_definition);
2015 return New->setInvalidDecl();
2016 }
2017 New->setType(MergedT);
2018}
2019
Chris Lattner01564d92007-01-27 19:27:06 +00002020/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2021/// and scope as a previous declaration 'Old'. Figure out how to resolve this
2022/// situation, merging decls or emitting diagnostics as appropriate.
2023///
Mike Stump11289f42009-09-09 15:08:12 +00002024/// Tentative definition rules (C99 6.9.2p2) are checked by
2025/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroff5bb8f222008-08-08 17:50:35 +00002026/// definitions here, since the initializer hasn't been attached.
Mike Stump11289f42009-09-09 15:08:12 +00002027///
John McCall1f82f242009-11-18 22:49:29 +00002028void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
2029 // If the new decl is already invalid, don't do any other checking.
2030 if (New->isInvalidDecl())
2031 return;
Mike Stump11289f42009-09-09 15:08:12 +00002032
Chris Lattnerc511efb2007-01-27 19:32:14 +00002033 // Verify the old decl was also a variable.
John McCall1f82f242009-11-18 22:49:29 +00002034 VarDecl *Old = 0;
2035 if (!Previous.isSingleResult() ||
2036 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
Chris Lattner651d42d2008-11-20 06:38:18 +00002037 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002038 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00002039 Diag(Previous.getRepresentativeDecl()->getLocation(),
2040 diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002041 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00002042 }
Chris Lattner84966392008-03-03 03:28:21 +00002043
Douglas Gregor2c7d9292010-08-30 14:32:14 +00002044 // C++ [class.mem]p1:
2045 // A member shall not be declared twice in the member-specification [...]
2046 //
2047 // Here, we need only consider static data members.
2048 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
2049 Diag(New->getLocation(), diag::err_duplicate_member)
2050 << New->getIdentifier();
2051 Diag(Old->getLocation(), diag::note_previous_declaration);
2052 New->setInvalidDecl();
2053 }
2054
John McCallf79e87d2011-03-02 04:00:57 +00002055 mergeDeclAttributes(New, Old, Context);
Fariborz Jahanian33e02262011-06-22 22:08:50 +00002056 // Warn if an already-declared variable is made a weak_import in a subsequent declaration
Fariborz Jahanianab578bf2011-06-20 17:50:03 +00002057 if (New->getAttr<WeakImportAttr>() &&
2058 Old->getStorageClass() == SC_None &&
Fariborz Jahanian33e02262011-06-22 22:08:50 +00002059 !Old->getAttr<WeakImportAttr>()) {
2060 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
2061 Diag(Old->getLocation(), diag::note_previous_definition);
2062 // Remove weak_import attribute on new declaration.
Fariborz Jahanian0dfc9502011-06-23 17:50:10 +00002063 New->dropAttr<WeakImportAttr>();
Fariborz Jahanian33e02262011-06-22 22:08:50 +00002064 }
Chris Lattner84966392008-03-03 03:28:21 +00002065
Richard Smith30482bc2011-02-20 03:19:35 +00002066 // Merge the types.
2067 MergeVarDeclTypes(New, Old);
2068 if (New->isInvalidDecl())
2069 return;
Douglas Gregor04e9a032009-03-11 23:52:16 +00002070
Steve Naroff1e787362008-01-30 00:44:01 +00002071 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
John McCall8e7d6562010-08-26 03:08:43 +00002072 if (New->getStorageClass() == SC_Static &&
2073 (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002074 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002075 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002076 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00002077 }
Mike Stump11289f42009-09-09 15:08:12 +00002078 // C99 6.2.2p4:
Douglas Gregor37311622009-03-19 22:01:50 +00002079 // For an identifier declared with the storage-class specifier
2080 // extern in a scope in which a prior declaration of that
2081 // identifier is visible,23) if the prior declaration specifies
2082 // internal or external linkage, the linkage of the identifier at
2083 // the later declaration is the same as the linkage specified at
2084 // the prior declaration. If no prior declaration is visible, or
2085 // if the prior declaration specifies no linkage, then the
2086 // identifier has external linkage.
Douglas Gregord4eca012009-03-23 16:17:01 +00002087 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor37311622009-03-19 22:01:50 +00002088 /* Okay */;
John McCall8e7d6562010-08-26 03:08:43 +00002089 else if (New->getStorageClass() != SC_Static &&
2090 Old->getStorageClass() == SC_Static) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002091 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002092 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002093 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00002094 }
Daniel Dunbar0ca16602009-04-14 02:25:56 +00002095
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00002096 // Check if extern is followed by non-extern and vice-versa.
2097 if (New->hasExternalStorage() &&
2098 !Old->hasLinkage() && Old->isLocalVarDecl()) {
2099 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
2100 Diag(Old->getLocation(), diag::note_previous_definition);
2101 return New->setInvalidDecl();
2102 }
2103 if (Old->hasExternalStorage() &&
2104 !New->hasLinkage() && New->isLocalVarDecl()) {
2105 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
2106 Diag(Old->getLocation(), diag::note_previous_definition);
2107 return New->setInvalidDecl();
2108 }
2109
Steve Naroffa5629372008-09-17 14:05:40 +00002110 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump11289f42009-09-09 15:08:12 +00002111
Daniel Dunbar0ca16602009-04-14 02:25:56 +00002112 // FIXME: The test for external storage here seems wrong? We still
2113 // need to check for mismatches.
2114 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor04e9a032009-03-11 23:52:16 +00002115 // Don't complain about out-of-line definitions of static members.
2116 !(Old->getLexicalDeclContext()->isRecord() &&
2117 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattnere3d20d92008-11-23 21:45:46 +00002118 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002119 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002120 return New->setInvalidDecl();
Steve Naroff6fbf0dc2007-03-16 00:33:25 +00002121 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00002122
Eli Friedmand5c0eed2009-04-19 20:27:55 +00002123 if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
2124 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
2125 Diag(Old->getLocation(), diag::note_previous_definition);
2126 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
2127 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
2128 Diag(Old->getLocation(), diag::note_previous_definition);
2129 }
2130
Sebastian Redlf1842912010-02-02 18:35:11 +00002131 // C++ doesn't have tentative definitions, so go right ahead and check here.
2132 const VarDecl *Def;
Sebastian Redld85be0c2010-02-03 02:08:48 +00002133 if (getLangOptions().CPlusPlus &&
2134 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redlf1842912010-02-02 18:35:11 +00002135 (Def = Old->getDefinition())) {
2136 Diag(New->getLocation(), diag::err_redefinition)
2137 << New->getDeclName();
2138 Diag(Def->getLocation(), diag::note_previous_definition);
2139 New->setInvalidDecl();
2140 return;
2141 }
Fariborz Jahanianad356a12010-06-25 00:05:45 +00002142 // c99 6.2.2 P4.
2143 // For an identifier declared with the storage-class specifier extern in a
2144 // scope in which a prior declaration of that identifier is visible, if
2145 // the prior declaration specifies internal or external linkage, the linkage
2146 // of the identifier at the later declaration is the same as the linkage
2147 // specified at the prior declaration.
2148 // FIXME. revisit this code.
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00002149 if (New->hasExternalStorage() &&
Fariborz Jahanian4f9c9d62010-06-24 18:50:41 +00002150 Old->getLinkage() == InternalLinkage &&
2151 New->getDeclContext() == Old->getDeclContext())
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00002152 New->setStorageClass(Old->getStorageClass());
2153
Douglas Gregor0760fa12009-03-10 23:43:53 +00002154 // Keep a chain of previous declarations.
2155 New->setPreviousDeclaration(Old);
John McCall401982f2010-01-20 21:53:11 +00002156
2157 // Inherit access appropriately.
2158 New->setAccess(Old->getAccess());
Chris Lattner01564d92007-01-27 19:27:06 +00002159}
2160
Chris Lattnerb6738ec2007-01-28 00:38:24 +00002161/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2162/// no declarator (e.g. "struct foo;") is parsed.
John McCall48871652010-08-21 09:40:31 +00002163Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallaa017372011-03-22 23:00:04 +00002164 DeclSpec &DS) {
Chandler Carruth7c9856d2011-05-03 18:35:10 +00002165 return ParsedFreeStandingDeclSpec(S, AS, DS,
2166 MultiTemplateParamsArg(*this, 0, 0));
2167}
2168
2169/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2170/// no declarator (e.g. "struct foo;") is parsed. It also accopts template
2171/// parameters to cope with template friend declarations.
2172Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2173 DeclSpec &DS,
2174 MultiTemplateParamsArg TemplateParams) {
John McCallc3987482009-10-07 23:34:25 +00002175 Decl *TagD = 0;
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002176 TagDecl *Tag = 0;
2177 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
2178 DS.getTypeSpecType() == DeclSpec::TST_struct ||
2179 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002180 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallba7bf592010-08-24 05:47:05 +00002181 TagD = DS.getRepAsDecl();
John McCallc3987482009-10-07 23:34:25 +00002182
2183 if (!TagD) // We probably had an error
John McCall48871652010-08-21 09:40:31 +00002184 return 0;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002185
John McCall07e91c02009-08-06 02:15:43 +00002186 // Note that the above type specs guarantee that the
2187 // type rep is a Decl, whereas in many of the others
2188 // it's a Type.
John McCallc3987482009-10-07 23:34:25 +00002189 Tag = dyn_cast<TagDecl>(TagD);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002190 }
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002191
Nuno Lopese9823fa2009-12-17 11:35:26 +00002192 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
2193 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
2194 // or incomplete types shall not be restrict-qualified."
2195 if (TypeQuals & DeclSpec::TQ_restrict)
2196 Diag(DS.getRestrictSpecLoc(),
2197 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
2198 << DS.getSourceRange();
2199 }
2200
Douglas Gregor3dad8422009-09-26 06:47:28 +00002201 if (DS.isFriendSpecified()) {
John McCallace48cd2010-10-19 01:40:49 +00002202 // If we're dealing with a decl but not a TagDecl, assume that
2203 // whatever routines created it handled the friendship aspect.
2204 if (TagD && !Tag)
John McCall48871652010-08-21 09:40:31 +00002205 return 0;
Chandler Carruth7c9856d2011-05-03 18:35:10 +00002206 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregor3dad8422009-09-26 06:47:28 +00002207 }
John McCallaa017372011-03-22 23:00:04 +00002208
2209 // Track whether we warned about the fact that there aren't any
2210 // declarators.
2211 bool emittedWarning = false;
Douglas Gregor3dad8422009-09-26 06:47:28 +00002212
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002213 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCall53fa7142010-12-24 02:08:15 +00002214 ProcessDeclAttributeList(S, Record, DS.getAttributes().getList());
Chris Lattnerecf328e2009-10-25 22:21:57 +00002215
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002216 if (!Record->getDeclName() && Record->isDefinition() &&
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002217 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
2218 if (getLangOptions().CPlusPlus ||
2219 Record->getDeclContext()->isRecord())
John McCallb54367d2010-05-21 20:45:30 +00002220 return BuildAnonymousStructOrUnion(S, DS, AS, Record);
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002221
Douglas Gregorf19ac0e2010-04-08 21:33:23 +00002222 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002223 << DS.getSourceRange();
John McCallaa017372011-03-22 23:00:04 +00002224 emittedWarning = true;
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002225 }
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002226 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002227
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002228 // Check for Microsoft C extension: anonymous struct.
2229 if (getLangOptions().Microsoft && !getLangOptions().CPlusPlus &&
2230 CurContext->isRecord() &&
2231 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
2232 // Handle 2 kinds of anonymous struct:
2233 // struct STRUCT;
2234 // and
2235 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
2236 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
2237 if ((Record && Record->getDeclName() && !Record->isDefinition()) ||
2238 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
2239 DS.getRepAsType().get()->isStructureType())) {
2240 Diag(DS.getSourceRange().getBegin(), diag::ext_ms_anonymous_struct)
2241 << DS.getSourceRange();
2242 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
2243 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002244 }
Douglas Gregor3dad8422009-09-26 06:47:28 +00002245
Douglas Gregoraa8c9722010-07-13 06:24:26 +00002246 if (getLangOptions().CPlusPlus &&
2247 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
2248 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
2249 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
John McCallaa017372011-03-22 23:00:04 +00002250 !Enum->getIdentifier() && !Enum->isInvalidDecl()) {
Douglas Gregoraa8c9722010-07-13 06:24:26 +00002251 Diag(Enum->getLocation(), diag::ext_no_declarators)
2252 << DS.getSourceRange();
John McCallaa017372011-03-22 23:00:04 +00002253 emittedWarning = true;
2254 }
2255
2256 // Skip all the checks below if we have a type error.
2257 if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD;
Douglas Gregoraa8c9722010-07-13 06:24:26 +00002258
John McCallaa017372011-03-22 23:00:04 +00002259 if (!DS.isMissingDeclaratorOk()) {
Douglas Gregor2d9dde0e2009-01-22 16:23:54 +00002260 // Warn about typedefs of enums without names, since this is an
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00002261 // extension in both Microsoft and GNU.
Douglas Gregor051d8fd2009-01-17 02:55:50 +00002262 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
2263 Tag && isa<EnumDecl>(Tag)) {
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00002264 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
2265 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00002266 return Tag;
Douglas Gregor2b136fe2009-01-13 23:10:51 +00002267 }
2268
Douglas Gregorf19ac0e2010-04-08 21:33:23 +00002269 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
Sebastian Redla2b5e312008-12-28 15:28:59 +00002270 << DS.getSourceRange();
John McCallaa017372011-03-22 23:00:04 +00002271 emittedWarning = true;
Sebastian Redla2b5e312008-12-28 15:28:59 +00002272 }
Mike Stump11289f42009-09-09 15:08:12 +00002273
John McCallaa017372011-03-22 23:00:04 +00002274 // We're going to complain about a bunch of spurious specifiers;
2275 // only do this if we're declaring a tag, because otherwise we
2276 // should be getting diag::ext_no_declarators.
2277 if (emittedWarning || (TagD && TagD->isInvalidDecl()))
2278 return TagD;
2279
John McCall4d55f5a2011-03-26 02:09:52 +00002280 // Note that a linkage-specification sets a storage class, but
2281 // 'extern "C" struct foo;' is actually valid and not theoretically
2282 // useless.
John McCallaa017372011-03-22 23:00:04 +00002283 if (DeclSpec::SCS scs = DS.getStorageClassSpec())
John McCall4d55f5a2011-03-26 02:09:52 +00002284 if (!DS.isExternInLinkageSpec())
2285 Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier)
2286 << DeclSpec::getSpecifierName(scs);
2287
John McCallaa017372011-03-22 23:00:04 +00002288 if (DS.isThreadSpecified())
2289 Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread";
2290 if (DS.getTypeQualifiers()) {
2291 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2292 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const";
2293 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2294 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile";
2295 // Restrict is covered above.
2296 }
2297 if (DS.isInlineSpecified())
2298 Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline";
2299 if (DS.isVirtualSpecified())
2300 Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual";
2301 if (DS.isExplicitSpecified())
2302 Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit";
2303
2304 // FIXME: Warn on useless attributes
2305
John McCall48871652010-08-21 09:40:31 +00002306 return TagD;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002307}
2308
Fariborz Jahanian1db5c942010-09-28 20:42:35 +00002309/// ActOnVlaStmt - This rouine if finds a vla expression in a decl spec.
2310/// builds a statement for it and returns it so it is evaluated.
2311StmtResult Sema::ActOnVlaStmt(const DeclSpec &DS) {
2312 StmtResult R;
2313 if (DS.getTypeSpecType() == DeclSpec::TST_typeofExpr) {
2314 Expr *Exp = DS.getRepAsExpr();
2315 QualType Ty = Exp->getType();
2316 if (Ty->isPointerType()) {
2317 do
2318 Ty = Ty->getAs<PointerType>()->getPointeeType();
2319 while (Ty->isPointerType());
2320 }
2321 if (Ty->isVariableArrayType()) {
2322 R = ActOnExprStmt(MakeFullExpr(Exp));
2323 }
2324 }
2325 return R;
2326}
2327
John McCallea305ed2009-12-18 10:40:03 +00002328/// We are trying to inject an anonymous member into the given scope;
John McCall1f82f242009-11-18 22:49:29 +00002329/// check if there's an existing declaration that can't be overloaded.
2330///
2331/// \return true if this is a forbidden redeclaration
John McCallea305ed2009-12-18 10:40:03 +00002332static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
2333 Scope *S,
Fariborz Jahanian53967e22010-01-22 18:30:17 +00002334 DeclContext *Owner,
John McCallea305ed2009-12-18 10:40:03 +00002335 DeclarationName Name,
2336 SourceLocation NameLoc,
2337 unsigned diagnostic) {
2338 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
2339 Sema::ForRedeclaration);
2340 if (!SemaRef.LookupName(R, S)) return false;
John McCall1f82f242009-11-18 22:49:29 +00002341
John McCallea305ed2009-12-18 10:40:03 +00002342 if (R.getAsSingle<TagDecl>())
John McCall1f82f242009-11-18 22:49:29 +00002343 return false;
2344
2345 // Pick a representative declaration.
John McCallea305ed2009-12-18 10:40:03 +00002346 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidise619e992010-09-23 14:26:01 +00002347 assert(PrevDecl && "Expected a non-null Decl");
2348
2349 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
2350 return false;
John McCall1f82f242009-11-18 22:49:29 +00002351
John McCallea305ed2009-12-18 10:40:03 +00002352 SemaRef.Diag(NameLoc, diagnostic) << Name;
2353 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall1f82f242009-11-18 22:49:29 +00002354
2355 return true;
2356}
2357
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002358/// InjectAnonymousStructOrUnionMembers - Inject the members of the
2359/// anonymous struct or union AnonRecord into the owning context Owner
2360/// and scope S. This routine will be invoked just after we realize
2361/// that an unnamed union or struct is actually an anonymous union or
2362/// struct, e.g.,
2363///
2364/// @code
2365/// union {
2366/// int i;
2367/// float f;
2368/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
2369/// // f into the surrounding scope.x
2370/// @endcode
2371///
2372/// This routine is recursive, injecting the names of nested anonymous
2373/// structs/unions into the owning context and scope as well.
John McCallb54367d2010-05-21 20:45:30 +00002374static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
2375 DeclContext *Owner,
2376 RecordDecl *AnonRecord,
Francois Pichet783dd6e2010-11-21 06:08:52 +00002377 AccessSpecifier AS,
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002378 llvm::SmallVector<NamedDecl*, 2> &Chaining,
2379 bool MSAnonStruct) {
John McCall1f82f242009-11-18 22:49:29 +00002380 unsigned diagKind
2381 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
2382 : diag::err_anonymous_struct_member_redecl;
2383
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002384 bool Invalid = false;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002385
2386 // Look every FieldDecl and IndirectFieldDecl with a name.
2387 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
2388 DEnd = AnonRecord->decls_end();
2389 D != DEnd; ++D) {
2390 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
2391 cast<NamedDecl>(*D)->getDeclName()) {
2392 ValueDecl *VD = cast<ValueDecl>(*D);
2393 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
2394 VD->getLocation(), diagKind)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002395 // C++ [class.union]p2:
2396 // The names of the members of an anonymous union shall be
2397 // distinct from the names of any other entity in the
2398 // scope in which the anonymous union is declared.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002399 Invalid = true;
2400 } else {
2401 // C++ [class.union]p2:
2402 // For the purpose of name lookup, after the anonymous union
2403 // definition, the members of the anonymous union are
2404 // considered to have been defined in the scope in which the
2405 // anonymous union is declared.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002406 unsigned OldChainingSize = Chaining.size();
2407 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
2408 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
2409 PE = IF->chain_end(); PI != PE; ++PI)
2410 Chaining.push_back(*PI);
2411 else
2412 Chaining.push_back(VD);
2413
Francois Pichet783dd6e2010-11-21 06:08:52 +00002414 assert(Chaining.size() >= 2);
2415 NamedDecl **NamedChain =
2416 new (SemaRef.Context)NamedDecl*[Chaining.size()];
2417 for (unsigned i = 0; i < Chaining.size(); i++)
2418 NamedChain[i] = Chaining[i];
2419
2420 IndirectFieldDecl* IndirectField =
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002421 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
2422 VD->getIdentifier(), VD->getType(),
Francois Pichet783dd6e2010-11-21 06:08:52 +00002423 NamedChain, Chaining.size());
2424
2425 IndirectField->setAccess(AS);
2426 IndirectField->setImplicit();
2427 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallb54367d2010-05-21 20:45:30 +00002428
2429 // That includes picking up the appropriate access specifier.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002430 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002431
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002432 Chaining.resize(OldChainingSize);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002433 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002434 }
2435 }
2436
2437 return Invalid;
2438}
2439
Douglas Gregorc4df4072010-04-19 22:54:31 +00002440/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
2441/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCall8e7d6562010-08-26 03:08:43 +00002442/// illegal input values are mapped to SC_None.
2443static StorageClass
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00002444StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
Douglas Gregorc4df4072010-04-19 22:54:31 +00002445 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00002446 case DeclSpec::SCS_unspecified: return SC_None;
2447 case DeclSpec::SCS_extern: return SC_Extern;
2448 case DeclSpec::SCS_static: return SC_Static;
2449 case DeclSpec::SCS_auto: return SC_Auto;
2450 case DeclSpec::SCS_register: return SC_Register;
2451 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002452 // Illegal SCSs map to None: error reporting is up to the caller.
2453 case DeclSpec::SCS_mutable: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00002454 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002455 }
2456 llvm_unreachable("unknown storage class specifier");
2457}
2458
2459/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
John McCall8e7d6562010-08-26 03:08:43 +00002460/// a StorageClass. Any error reporting is up to the caller:
2461/// illegal input values are mapped to SC_None.
2462static StorageClass
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00002463StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
Douglas Gregorc4df4072010-04-19 22:54:31 +00002464 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00002465 case DeclSpec::SCS_unspecified: return SC_None;
2466 case DeclSpec::SCS_extern: return SC_Extern;
2467 case DeclSpec::SCS_static: return SC_Static;
2468 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002469 // Illegal SCSs map to None: error reporting is up to the caller.
2470 case DeclSpec::SCS_auto: // Fall through.
2471 case DeclSpec::SCS_mutable: // Fall through.
2472 case DeclSpec::SCS_register: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00002473 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002474 }
2475 llvm_unreachable("unknown storage class specifier");
2476}
2477
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002478/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002479/// anonymous structure or union. Anonymous unions are a C++ feature
2480/// (C++ [class.union]) and a GNU C extension; anonymous structures
Mike Stump11289f42009-09-09 15:08:12 +00002481/// are a GNU C and GNU C++ extension.
John McCall48871652010-08-21 09:40:31 +00002482Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2483 AccessSpecifier AS,
2484 RecordDecl *Record) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002485 DeclContext *Owner = Record->getDeclContext();
2486
2487 // Diagnose whether this anonymous struct/union is an extension.
2488 if (Record->isUnion() && !getLangOptions().CPlusPlus)
2489 Diag(Record->getLocation(), diag::ext_anonymous_union);
2490 else if (!Record->isUnion())
2491 Diag(Record->getLocation(), diag::ext_anonymous_struct);
Mike Stump11289f42009-09-09 15:08:12 +00002492
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002493 // C and C++ require different kinds of checks for anonymous
2494 // structs/unions.
2495 bool Invalid = false;
2496 if (getLangOptions().CPlusPlus) {
2497 const char* PrevSpec = 0;
John McCall49bfce42009-08-03 20:12:06 +00002498 unsigned DiagID;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002499 // C++ [class.union]p3:
2500 // Anonymous unions declared in a named namespace or in the
2501 // global namespace shall be declared static.
2502 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
2503 (isa<TranslationUnitDecl>(Owner) ||
Mike Stump11289f42009-09-09 15:08:12 +00002504 (isa<NamespaceDecl>(Owner) &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002505 cast<NamespaceDecl>(Owner)->getDeclName()))) {
2506 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
2507 Invalid = true;
2508
2509 // Recover by adding 'static'.
John McCall49bfce42009-08-03 20:12:06 +00002510 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(),
Peter Collingbournede32b202011-02-11 19:59:54 +00002511 PrevSpec, DiagID, getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +00002512 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002513 // C++ [class.union]p3:
2514 // A storage class is not allowed in a declaration of an
2515 // anonymous union in a class scope.
2516 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
2517 isa<RecordDecl>(Owner)) {
Mike Stump11289f42009-09-09 15:08:12 +00002518 Diag(DS.getStorageClassSpecLoc(),
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002519 diag::err_anonymous_union_with_storage_spec);
2520 Invalid = true;
2521
2522 // Recover by removing the storage specifier.
2523 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
Peter Collingbournede32b202011-02-11 19:59:54 +00002524 PrevSpec, DiagID, getLangOptions());
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002525 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00002526
Douglas Gregor0f8bc972011-05-09 23:05:33 +00002527 // Ignore const/volatile/restrict qualifiers.
2528 if (DS.getTypeQualifiers()) {
2529 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2530 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
2531 << Record->isUnion() << 0
2532 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
2533 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2534 Diag(DS.getVolatileSpecLoc(), diag::ext_anonymous_struct_union_qualified)
2535 << Record->isUnion() << 1
2536 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
2537 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
2538 Diag(DS.getRestrictSpecLoc(), diag::ext_anonymous_struct_union_qualified)
2539 << Record->isUnion() << 2
2540 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
2541
2542 DS.ClearTypeQualifiers();
2543 }
2544
Mike Stump11289f42009-09-09 15:08:12 +00002545 // C++ [class.union]p2:
Douglas Gregorf4d33272009-01-07 19:46:03 +00002546 // The member-specification of an anonymous union shall only
2547 // define non-static data members. [Note: nested types and
2548 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002549 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
2550 MemEnd = Record->decls_end();
Douglas Gregorf4d33272009-01-07 19:46:03 +00002551 Mem != MemEnd; ++Mem) {
2552 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
2553 // C++ [class.union]p3:
2554 // An anonymous union shall not have private or protected
2555 // members (clause 11).
John McCallb54367d2010-05-21 20:45:30 +00002556 assert(FD->getAccess() != AS_none);
2557 if (FD->getAccess() != AS_public) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00002558 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
2559 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
2560 Invalid = true;
2561 }
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00002562
Alexis Hunt97ab5542011-05-16 22:41:40 +00002563 // C++ [class.union]p1
2564 // An object of a class with a non-trivial constructor, a non-trivial
2565 // copy constructor, a non-trivial destructor, or a non-trivial copy
2566 // assignment operator cannot be a member of a union, nor can an
2567 // array of such objects.
2568 if (!getLangOptions().CPlusPlus0x && CheckNontrivialField(FD))
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00002569 Invalid = true;
Douglas Gregorf4d33272009-01-07 19:46:03 +00002570 } else if ((*Mem)->isImplicit()) {
2571 // Any implicit members are fine.
Douglas Gregor8761da52009-02-03 00:34:39 +00002572 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
2573 // This is a type that showed up in an
2574 // elaborated-type-specifier inside the anonymous struct or
2575 // union, but which actually declares a type outside of the
2576 // anonymous struct or union. It's okay.
Douglas Gregorf4d33272009-01-07 19:46:03 +00002577 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
2578 if (!MemRecord->isAnonymousStructOrUnion() &&
2579 MemRecord->getDeclName()) {
Francois Pichet4ad4b582010-09-08 11:32:25 +00002580 // Visual C++ allows type definition in anonymous struct or union.
2581 if (getLangOptions().Microsoft)
2582 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
2583 << (int)Record->isUnion();
2584 else {
2585 // This is a nested type declaration.
2586 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
2587 << (int)Record->isUnion();
2588 Invalid = true;
2589 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00002590 }
Abramo Bagnarad7340582010-06-05 05:09:32 +00002591 } else if (isa<AccessSpecDecl>(*Mem)) {
2592 // Any access specifier is fine.
Douglas Gregorf4d33272009-01-07 19:46:03 +00002593 } else {
2594 // We have something that isn't a non-static data
2595 // member. Complain about it.
2596 unsigned DK = diag::err_anonymous_record_bad_member;
2597 if (isa<TypeDecl>(*Mem))
2598 DK = diag::err_anonymous_record_with_type;
2599 else if (isa<FunctionDecl>(*Mem))
2600 DK = diag::err_anonymous_record_with_function;
2601 else if (isa<VarDecl>(*Mem))
2602 DK = diag::err_anonymous_record_with_static;
Francois Pichet4ad4b582010-09-08 11:32:25 +00002603
2604 // Visual C++ allows type definition in anonymous struct or union.
2605 if (getLangOptions().Microsoft &&
2606 DK == diag::err_anonymous_record_with_type)
2607 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregorf4d33272009-01-07 19:46:03 +00002608 << (int)Record->isUnion();
Francois Pichet4ad4b582010-09-08 11:32:25 +00002609 else {
2610 Diag((*Mem)->getLocation(), DK)
2611 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00002612 Invalid = true;
Francois Pichet4ad4b582010-09-08 11:32:25 +00002613 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00002614 }
2615 }
Mike Stump11289f42009-09-09 15:08:12 +00002616 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002617
2618 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002619 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
2620 << (int)getLangOptions().CPlusPlus;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002621 Invalid = true;
2622 }
2623
John McCallfa2d6922009-10-22 23:31:08 +00002624 // Mock up a declarator.
Argyrios Kyrtzidis7baa0af2011-06-28 03:01:18 +00002625 Declarator Dc(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00002626 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCallbcd03502009-12-07 02:54:59 +00002627 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCallfa2d6922009-10-22 23:31:08 +00002628
Mike Stump11289f42009-09-09 15:08:12 +00002629 // Create a declaration for this anonymous struct/union.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002630 NamedDecl *Anon = 0;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002631 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00002632 Anon = FieldDecl::Create(Context, OwningClass,
2633 DS.getSourceRange().getBegin(),
2634 Record->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002635 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00002636 Context.getTypeDeclType(Record),
John McCallbcd03502009-12-07 02:54:59 +00002637 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00002638 /*BitWidth=*/0, /*Mutable=*/false,
2639 /*HasInit=*/false);
John McCallb54367d2010-05-21 20:45:30 +00002640 Anon->setAccess(AS);
Douglas Gregor9d5938a2010-09-28 20:38:10 +00002641 if (getLangOptions().CPlusPlus)
Douglas Gregorf4d33272009-01-07 19:46:03 +00002642 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002643 } else {
Douglas Gregorc4df4072010-04-19 22:54:31 +00002644 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
2645 assert(SCSpec != DeclSpec::SCS_typedef &&
2646 "Parser allowed 'typedef' as storage class VarDecl.");
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00002647 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregorc4df4072010-04-19 22:54:31 +00002648 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002649 // mutable can only appear on non-static class members, so it's always
2650 // an error here
2651 Diag(Record->getLocation(), diag::err_mutable_nonmember);
2652 Invalid = true;
John McCall8e7d6562010-08-26 03:08:43 +00002653 SC = SC_None;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002654 }
Douglas Gregorc4df4072010-04-19 22:54:31 +00002655 SCSpec = DS.getStorageClassSpecAsWritten();
2656 VarDecl::StorageClass SCAsWritten
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00002657 = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002658
Abramo Bagnaradff19302011-03-08 08:55:46 +00002659 Anon = VarDecl::Create(Context, Owner,
2660 DS.getSourceRange().getBegin(),
2661 Record->getLocation(), /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00002662 Context.getTypeDeclType(Record),
Douglas Gregorc4df4072010-04-19 22:54:31 +00002663 TInfo, SC, SCAsWritten);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002664 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00002665 Anon->setImplicit();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002666
2667 // Add the anonymous struct/union object to the current
2668 // context. We'll be referencing this object when we refer to one of
2669 // its members.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002670 Owner->addDecl(Anon);
Douglas Gregor456ad1a2010-05-03 15:18:25 +00002671
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002672 // Inject the members of the anonymous struct/union into the owning
2673 // context and into the identifier resolver chain for name lookup
2674 // purposes.
Francois Pichet783dd6e2010-11-21 06:08:52 +00002675 llvm::SmallVector<NamedDecl*, 2> Chain;
2676 Chain.push_back(Anon);
2677
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002678 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
2679 Chain, false))
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002680 Invalid = true;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002681
2682 // Mark this as an anonymous struct/union type. Note that we do not
2683 // do this until after we have already checked and injected the
2684 // members of this anonymous struct/union type, because otherwise
2685 // the members could be injected twice: once by DeclContext when it
2686 // builds its lookup table, and once by
Mike Stump11289f42009-09-09 15:08:12 +00002687 // InjectAnonymousStructOrUnionMembers.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002688 Record->setAnonymousStructOrUnion(true);
2689
2690 if (Invalid)
2691 Anon->setInvalidDecl();
2692
John McCall48871652010-08-21 09:40:31 +00002693 return Anon;
Chris Lattnerb6738ec2007-01-28 00:38:24 +00002694}
2695
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002696/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
2697/// Microsoft C anonymous structure.
2698/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
2699/// Example:
2700///
2701/// struct A { int a; };
2702/// struct B { struct A; int b; };
2703///
2704/// void foo() {
2705/// B var;
2706/// var.a = 3;
2707/// }
2708///
2709Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2710 RecordDecl *Record) {
2711
2712 // If there is no Record, get the record via the typedef.
2713 if (!Record)
2714 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
2715
2716 // Mock up a declarator.
2717 Declarator Dc(DS, Declarator::TypeNameContext);
2718 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
2719 assert(TInfo && "couldn't build declarator info for anonymous struct");
2720
2721 // Create a declaration for this anonymous struct.
2722 NamedDecl* Anon = FieldDecl::Create(Context,
2723 cast<RecordDecl>(CurContext),
2724 DS.getSourceRange().getBegin(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002725 DS.getSourceRange().getBegin(),
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002726 /*IdentifierInfo=*/0,
2727 Context.getTypeDeclType(Record),
2728 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00002729 /*BitWidth=*/0, /*Mutable=*/false,
2730 /*HasInit=*/false);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002731 Anon->setImplicit();
2732
2733 // Add the anonymous struct object to the current context.
2734 CurContext->addDecl(Anon);
2735
2736 // Inject the members of the anonymous struct into the current
2737 // context and into the identifier resolver chain for name lookup
2738 // purposes.
2739 llvm::SmallVector<NamedDecl*, 2> Chain;
2740 Chain.push_back(Anon);
2741
2742 if (InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
2743 Record->getDefinition(),
2744 AS_none, Chain, true))
2745 Anon->setInvalidDecl();
2746
2747 return Anon;
2748}
Steve Naroff2fea1392007-09-02 02:04:30 +00002749
Douglas Gregor92751d42008-11-17 22:58:34 +00002750/// GetNameForDeclarator - Determine the full declaration name for the
2751/// given Declarator.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002752DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregora121b752009-11-03 16:56:39 +00002753 return GetNameFromUnqualifiedId(D.getName());
2754}
2755
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002756/// \brief Retrieves the declaration name from a parsed unqualified-id.
2757DeclarationNameInfo
2758Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
2759 DeclarationNameInfo NameInfo;
2760 NameInfo.setLoc(Name.StartLocation);
2761
Douglas Gregor7861a802009-11-03 01:35:08 +00002762 switch (Name.getKind()) {
Alexis Hunt34458502009-11-28 04:44:28 +00002763
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002764 case UnqualifiedId::IK_Identifier:
2765 NameInfo.setName(Name.Identifier);
2766 NameInfo.setLoc(Name.StartLocation);
2767 return NameInfo;
Alexis Hunt34458502009-11-28 04:44:28 +00002768
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002769 case UnqualifiedId::IK_OperatorFunctionId:
2770 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
2771 Name.OperatorFunctionId.Operator));
2772 NameInfo.setLoc(Name.StartLocation);
2773 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
2774 = Name.OperatorFunctionId.SymbolLocations[0];
2775 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
2776 = Name.EndLocation.getRawEncoding();
2777 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002778
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002779 case UnqualifiedId::IK_LiteralOperatorId:
2780 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
2781 Name.Identifier));
2782 NameInfo.setLoc(Name.StartLocation);
2783 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
2784 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002785
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002786 case UnqualifiedId::IK_ConversionFunctionId: {
2787 TypeSourceInfo *TInfo;
2788 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
2789 if (Ty.isNull())
2790 return DeclarationNameInfo();
2791 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
2792 Context.getCanonicalType(Ty)));
2793 NameInfo.setLoc(Name.StartLocation);
2794 NameInfo.setNamedTypeInfo(TInfo);
2795 return NameInfo;
Douglas Gregord90fd522009-09-25 21:45:23 +00002796 }
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002797
2798 case UnqualifiedId::IK_ConstructorName: {
2799 TypeSourceInfo *TInfo;
2800 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
2801 if (Ty.isNull())
2802 return DeclarationNameInfo();
2803 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
2804 Context.getCanonicalType(Ty)));
2805 NameInfo.setLoc(Name.StartLocation);
2806 NameInfo.setNamedTypeInfo(TInfo);
2807 return NameInfo;
2808 }
2809
2810 case UnqualifiedId::IK_ConstructorTemplateId: {
2811 // In well-formed code, we can only have a constructor
2812 // template-id that refers to the current context, so go there
2813 // to find the actual type being constructed.
2814 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
2815 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
2816 return DeclarationNameInfo();
2817
2818 // Determine the type of the class being constructed.
2819 QualType CurClassType = Context.getTypeDeclType(CurClass);
2820
2821 // FIXME: Check two things: that the template-id names the same type as
2822 // CurClassType, and that the template-id does not occur when the name
2823 // was qualified.
2824
2825 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
2826 Context.getCanonicalType(CurClassType)));
2827 NameInfo.setLoc(Name.StartLocation);
2828 // FIXME: should we retrieve TypeSourceInfo?
2829 NameInfo.setNamedTypeInfo(0);
2830 return NameInfo;
2831 }
2832
2833 case UnqualifiedId::IK_DestructorName: {
2834 TypeSourceInfo *TInfo;
2835 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
2836 if (Ty.isNull())
2837 return DeclarationNameInfo();
2838 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
2839 Context.getCanonicalType(Ty)));
2840 NameInfo.setLoc(Name.StartLocation);
2841 NameInfo.setNamedTypeInfo(TInfo);
2842 return NameInfo;
2843 }
2844
2845 case UnqualifiedId::IK_TemplateId: {
John McCall3e56fd42010-08-23 07:28:44 +00002846 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002847 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
2848 return Context.getNameForTemplate(TName, TNameLoc);
2849 }
2850
2851 } // switch (Name.getKind())
2852
Douglas Gregor92751d42008-11-17 22:58:34 +00002853 assert(false && "Unknown name kind");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002854 return DeclarationNameInfo();
Douglas Gregor92751d42008-11-17 22:58:34 +00002855}
2856
Douglas Gregor8af63e42009-02-06 17:46:57 +00002857/// isNearlyMatchingFunction - Determine whether the C++ functions
2858/// Declaration and Definition are "nearly" matching. This heuristic
2859/// is used to improve diagnostics in the case where an out-of-line
2860/// function definition doesn't match any declaration within
2861/// the class or namespace.
2862static bool isNearlyMatchingFunction(ASTContext &Context,
2863 FunctionDecl *Declaration,
2864 FunctionDecl *Definition) {
Douglas Gregorad590502008-12-15 23:53:10 +00002865 if (Declaration->param_size() != Definition->param_size())
2866 return false;
2867 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
2868 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
2869 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
2870
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002871 if (!Context.hasSameUnqualifiedType(DeclParamTy.getNonReferenceType(),
2872 DefParamTy.getNonReferenceType()))
Douglas Gregorad590502008-12-15 23:53:10 +00002873 return false;
2874 }
2875
2876 return true;
2877}
2878
John McCall99b2fe52010-04-29 23:50:39 +00002879/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
2880/// declarator needs to be rebuilt in the current instantiation.
2881/// Any bits of declarator which appear before the name are valid for
2882/// consideration here. That's specifically the type in the decl spec
2883/// and the base type in any member-pointer chunks.
2884static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
2885 DeclarationName Name) {
2886 // The types we specifically need to rebuild are:
2887 // - typenames, typeofs, and decltypes
2888 // - types which will become injected class names
2889 // Of course, we also need to rebuild any type referencing such a
2890 // type. It's safest to just say "dependent", but we call out a
2891 // few cases here.
2892
2893 DeclSpec &DS = D.getMutableDeclSpec();
2894 switch (DS.getTypeSpecType()) {
2895 case DeclSpec::TST_typename:
2896 case DeclSpec::TST_typeofType:
Alexis Hunt4a257072011-05-19 05:37:45 +00002897 case DeclSpec::TST_decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002898 case DeclSpec::TST_underlyingType: {
John McCall99b2fe52010-04-29 23:50:39 +00002899 // Grab the type from the parser.
2900 TypeSourceInfo *TSI = 0;
John McCallba7bf592010-08-24 05:47:05 +00002901 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall99b2fe52010-04-29 23:50:39 +00002902 if (T.isNull() || !T->isDependentType()) break;
2903
2904 // Make sure there's a type source info. This isn't really much
2905 // of a waste; most dependent types should have type source info
2906 // attached already.
2907 if (!TSI)
2908 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
2909
2910 // Rebuild the type in the current instantiation.
2911 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
2912 if (!TSI) return true;
2913
2914 // Store the new type back in the decl spec.
John McCallba7bf592010-08-24 05:47:05 +00002915 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
2916 DS.UpdateTypeRep(LocType);
2917 break;
2918 }
2919
2920 case DeclSpec::TST_typeofExpr: {
2921 Expr *E = DS.getRepAsExpr();
John McCalldadc5752010-08-24 06:29:42 +00002922 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallba7bf592010-08-24 05:47:05 +00002923 if (Result.isInvalid()) return true;
2924 DS.UpdateExprRep(Result.get());
John McCall99b2fe52010-04-29 23:50:39 +00002925 break;
2926 }
2927
2928 default:
2929 // Nothing to do for these decl specs.
2930 break;
2931 }
2932
2933 // It doesn't matter what order we do this in.
2934 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
2935 DeclaratorChunk &Chunk = D.getTypeObject(I);
2936
2937 // The only type information in the declarator which can come
2938 // before the declaration name is the base type of a member
2939 // pointer.
2940 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
2941 continue;
2942
2943 // Rebuild the scope specifier in-place.
2944 CXXScopeSpec &SS = Chunk.Mem.Scope();
2945 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
2946 return true;
2947 }
2948
2949 return false;
2950}
2951
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002952Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D,
2953 bool IsFunctionDefinition) {
2954 return HandleDeclarator(S, D, MultiTemplateParamsArg(*this),
2955 IsFunctionDefinition);
John McCallde6836a2010-08-24 07:21:54 +00002956}
2957
Richard Smithdda56e42011-04-15 14:24:37 +00002958/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
2959/// If T is the name of a class, then each of the following shall have a
2960/// name different from T:
2961/// - every static data member of class T;
2962/// - every member function of class T
2963/// - every member of class T that is itself a type;
2964/// \returns true if the declaration name violates these rules.
2965bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
2966 DeclarationNameInfo NameInfo) {
2967 DeclarationName Name = NameInfo.getName();
2968
2969 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
2970 if (Record->getIdentifier() && Record->getDeclName() == Name) {
2971 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
2972 return true;
2973 }
2974
2975 return false;
2976}
2977
John McCall48871652010-08-21 09:40:31 +00002978Decl *Sema::HandleDeclarator(Scope *S, Declarator &D,
2979 MultiTemplateParamsArg TemplateParamLists,
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002980 bool IsFunctionDefinition) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002981 // TODO: consider using NameInfo for diagnostic.
2982 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2983 DeclarationName Name = NameInfo.getName();
Douglas Gregor92751d42008-11-17 22:58:34 +00002984
Chris Lattner02c04392007-07-25 00:24:17 +00002985 // All of these full declarators require an identifier. If it doesn't have
2986 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor92751d42008-11-17 22:58:34 +00002987 if (!Name) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002988 if (!D.isInvalidType()) // Reject this if we think it is valid.
Chris Lattner8c5dd732008-11-11 06:13:16 +00002989 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002990 diag::err_declarator_need_ident)
2991 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00002992 return 0;
Douglas Gregorc4356532010-12-16 00:46:58 +00002993 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
2994 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002995
Chris Lattner1a76a3c2007-08-26 06:24:45 +00002996 // The scope passed in may not be a decl scope. Zip up the scope tree until
2997 // we find one that is.
Douglas Gregor91f84212008-12-11 16:49:14 +00002998 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregorded2d7b2009-02-04 19:02:06 +00002999 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner1a76a3c2007-08-26 06:24:45 +00003000 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003001
John McCall99b2fe52010-04-29 23:50:39 +00003002 DeclContext *DC = CurContext;
3003 if (D.getCXXScopeSpec().isInvalid())
3004 D.setInvalidType();
3005 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6c110f32010-12-16 01:14:37 +00003006 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
3007 UPPC_DeclarationQualifier))
3008 return 0;
3009
John McCall99b2fe52010-04-29 23:50:39 +00003010 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
3011 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
3012 if (!DC) {
3013 // If we could not compute the declaration context, it's because the
3014 // declaration context is dependent but does not refer to a class,
3015 // class template, or class template partial specialization. Complain
3016 // and return early, to avoid the coming semantic disaster.
3017 Diag(D.getIdentifierLoc(),
3018 diag::err_template_qualified_declarator_no_match)
3019 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
3020 << D.getCXXScopeSpec().getRange();
John McCall48871652010-08-21 09:40:31 +00003021 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00003022 }
John McCall99b2fe52010-04-29 23:50:39 +00003023 bool IsDependentContext = DC->isDependentContext();
John McCall4d6d6132009-12-19 09:35:56 +00003024
John McCall99b2fe52010-04-29 23:50:39 +00003025 if (!IsDependentContext &&
John McCall0b66eb32010-05-01 00:40:08 +00003026 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCall48871652010-08-21 09:40:31 +00003027 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00003028
Douglas Gregora007d362010-10-13 22:19:53 +00003029 if (isa<CXXRecordDecl>(DC)) {
3030 if (!cast<CXXRecordDecl>(DC)->hasDefinition()) {
3031 Diag(D.getIdentifierLoc(),
3032 diag::err_member_def_undefined_record)
3033 << Name << DC << D.getCXXScopeSpec().getRange();
3034 D.setInvalidType();
3035 } else if (isa<CXXRecordDecl>(CurContext) &&
3036 !D.getDeclSpec().isFriendSpecified()) {
3037 // The user provided a superfluous scope specifier inside a class
3038 // definition:
3039 //
3040 // class X {
3041 // void X::f();
3042 // };
3043 if (CurContext->Equals(DC))
3044 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
3045 << Name << FixItHint::CreateRemoval(D.getCXXScopeSpec().getRange());
3046 else
3047 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3048 << Name << D.getCXXScopeSpec().getRange();
3049
3050 // Pretend that this qualifier was not here.
3051 D.getCXXScopeSpec().clear();
3052 }
John McCall99b2fe52010-04-29 23:50:39 +00003053 }
3054
3055 // Check whether we need to rebuild the type of the given
3056 // declaration in the current instantiation.
3057 if (EnteringContext && IsDependentContext &&
3058 TemplateParamLists.size() != 0) {
3059 ContextRAII SavedContext(*this, DC);
3060 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
3061 D.setInvalidType();
Douglas Gregor15acfb92009-08-06 16:20:37 +00003062 }
3063 }
Richard Smithdda56e42011-04-15 14:24:37 +00003064
3065 if (DiagnoseClassNameShadow(DC, NameInfo))
3066 // If this is a typedef, we'll end up spewing multiple diagnostics.
3067 // Just return early; it's safer.
3068 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3069 return 0;
Douglas Gregor36c22a22010-10-15 13:21:21 +00003070
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003071 NamedDecl *New;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00003072
John McCall8cb7bdf2010-06-04 23:28:52 +00003073 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3074 QualType R = TInfo->getType();
Douglas Gregoreddf4332009-02-24 20:03:32 +00003075
Douglas Gregor506bd562010-12-13 22:49:22 +00003076 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
3077 UPPC_DeclarationType))
3078 D.setInvalidType();
3079
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003080 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00003081 ForRedeclaration);
3082
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003083 // See if this is a redefinition of a variable in the same scope.
John McCall99b2fe52010-04-29 23:50:39 +00003084 if (!D.getCXXScopeSpec().isSet()) {
John McCall1f82f242009-11-18 22:49:29 +00003085 bool IsLinkageLookup = false;
Douglas Gregoreddf4332009-02-24 20:03:32 +00003086
3087 // If the declaration we're planning to build will be a function
3088 // or object with linkage, then look for another declaration with
3089 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
3090 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3091 /* Do nothing*/;
3092 else if (R->isFunctionType()) {
Douglas Gregor20749772009-07-07 17:00:05 +00003093 if (CurContext->isFunctionOrMethod() ||
3094 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall1f82f242009-11-18 22:49:29 +00003095 IsLinkageLookup = true;
Douglas Gregoreddf4332009-02-24 20:03:32 +00003096 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
John McCall1f82f242009-11-18 22:49:29 +00003097 IsLinkageLookup = true;
Sebastian Redl50c68252010-08-31 00:36:30 +00003098 else if (CurContext->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor20749772009-07-07 17:00:05 +00003099 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall1f82f242009-11-18 22:49:29 +00003100 IsLinkageLookup = true;
3101
3102 if (IsLinkageLookup)
3103 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregoreddf4332009-02-24 20:03:32 +00003104
John McCall1f82f242009-11-18 22:49:29 +00003105 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003106 } else { // Something like "int foo::x;"
John McCall1f82f242009-11-18 22:49:29 +00003107 LookupQualifiedName(Previous, DC);
3108
3109 // Don't consider using declarations as previous declarations for
3110 // out-of-line members.
3111 RemoveUsingDecls(Previous);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003112
3113 // C++ 7.3.1.2p2:
3114 // Members (including explicit specializations of templates) of a named
3115 // namespace can also be defined outside that namespace by explicit
3116 // qualification of the name being defined, provided that the entity being
3117 // defined was already declared in the namespace and the definition appears
3118 // after the point of declaration in a namespace that encloses the
3119 // declarations namespace.
3120 //
Douglas Gregorad590502008-12-15 23:53:10 +00003121 // Note that we only check the context at this point. We don't yet
3122 // have enough information to make sure that PrevDecl is actually
3123 // the declaration we want to match. For example, given:
3124 //
Douglas Gregor4287b372008-12-12 08:25:50 +00003125 // class X {
3126 // void f();
Douglas Gregorad590502008-12-15 23:53:10 +00003127 // void f(float);
Douglas Gregor4287b372008-12-12 08:25:50 +00003128 // };
3129 //
Douglas Gregorad590502008-12-15 23:53:10 +00003130 // void X::f(int) { } // ill-formed
3131 //
3132 // In this case, PrevDecl will point to the overload set
3133 // containing the two f's declared in X, but neither of them
Mike Stump11289f42009-09-09 15:08:12 +00003134 // matches.
Douglas Gregor8af63e42009-02-06 17:46:57 +00003135
3136 // First check whether we named the global scope.
3137 if (isa<TranslationUnitDecl>(DC)) {
Mike Stump11289f42009-09-09 15:08:12 +00003138 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
Douglas Gregor8af63e42009-02-06 17:46:57 +00003139 << Name << D.getCXXScopeSpec().getRange();
Sebastian Redlafb8be72009-11-08 11:36:54 +00003140 } else {
3141 DeclContext *Cur = CurContext;
3142 while (isa<LinkageSpecDecl>(Cur))
3143 Cur = Cur->getParent();
3144 if (!Cur->Encloses(DC)) {
3145 // The qualifying scope doesn't enclose the original declaration.
3146 // Emit diagnostic based on current scope.
3147 SourceLocation L = D.getIdentifierLoc();
3148 SourceRange R = D.getCXXScopeSpec().getRange();
3149 if (isa<FunctionDecl>(Cur))
3150 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
3151 else
3152 Diag(L, diag::err_invalid_declarator_scope)
3153 << Name << cast<NamedDecl>(DC) << R;
3154 D.setInvalidType();
3155 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003156 }
3157 }
3158
John McCall1f82f242009-11-18 22:49:29 +00003159 if (Previous.isSingleResult() &&
3160 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00003161 // Maybe we will complain about the shadowed template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003162 if (!D.isInvalidType())
John McCall1f82f242009-11-18 22:49:29 +00003163 if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
3164 Previous.getFoundDecl()))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003165 D.setInvalidType();
Mike Stump11289f42009-09-09 15:08:12 +00003166
Douglas Gregor5101c242008-12-05 18:15:24 +00003167 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00003168 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00003169 }
3170
Douglas Gregor83a586e2008-04-13 21:07:44 +00003171 // In C++, the previous declaration we find might be a tag type
3172 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorfb034662009-01-28 17:15:10 +00003173 // tag type. Note that this does does not apply if we're declaring a
3174 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00003175 if (Previous.isSingleTagDecl() &&
Douglas Gregorfb034662009-01-28 17:15:10 +00003176 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall1f82f242009-11-18 22:49:29 +00003177 Previous.clear();
Douglas Gregor83a586e2008-04-13 21:07:44 +00003178
Douglas Gregor75a45ba2009-02-16 17:45:42 +00003179 bool Redeclaration = false;
Chris Lattner01a7c532007-01-25 23:09:03 +00003180 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003181 if (TemplateParamLists.size()) {
3182 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
John McCall48871652010-08-21 09:40:31 +00003183 return 0;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003184 }
Mike Stump11289f42009-09-09 15:08:12 +00003185
John McCallbcd03502009-12-07 02:54:59 +00003186 New = ActOnTypedefDeclarator(S, D, DC, R, TInfo, Previous, Redeclaration);
Douglas Gregoreddf4332009-02-24 20:03:32 +00003187 } else if (R->isFunctionType()) {
John McCallbcd03502009-12-07 02:54:59 +00003188 New = ActOnFunctionDeclarator(S, D, DC, R, TInfo, Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003189 move(TemplateParamLists),
Alexis Hunt5a7fa252011-05-12 06:15:49 +00003190 IsFunctionDefinition, Redeclaration);
Chris Lattner01a7c532007-01-25 23:09:03 +00003191 } else {
John McCallbcd03502009-12-07 02:54:59 +00003192 New = ActOnVariableDeclarator(S, D, DC, R, TInfo, Previous,
Douglas Gregorb09f3d82009-07-22 17:18:37 +00003193 move(TemplateParamLists),
3194 Redeclaration);
Chris Lattner01a7c532007-01-25 23:09:03 +00003195 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00003196
3197 if (New == 0)
John McCall48871652010-08-21 09:40:31 +00003198 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003199
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003200 // If this has an identifier and is not an invalid redeclaration or
3201 // function template specialization, add it to the scope stack.
Douglas Gregor536f0912010-07-24 00:10:38 +00003202 if (New->getDeclName() && !(Redeclaration && New->isInvalidDecl()))
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00003203 PushOnScopeChains(New, S);
Mike Stump11289f42009-09-09 15:08:12 +00003204
John McCall48871652010-08-21 09:40:31 +00003205 return New;
Chris Lattnere168f762006-11-10 05:29:30 +00003206}
3207
Eli Friedmana3b1d032009-02-21 00:44:51 +00003208/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3209/// types into constant array types in certain situations which would otherwise
3210/// be errors (for GCC compatibility).
3211static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3212 ASTContext &Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003213 bool &SizeIsNegative,
3214 llvm::APSInt &Oversized) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00003215 // This method tries to turn a variable array into a constant
3216 // array even when the size isn't an ICE. This is necessary
3217 // for compatibility with code that depends on gcc's buggy
3218 // constant expression folding, like struct {char x[(int)(char*)2];}
3219 SizeIsNegative = false;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003220 Oversized = 0;
3221
3222 if (T->isDependentType())
3223 return QualType();
3224
John McCall8ccfcb52009-09-24 19:53:00 +00003225 QualifierCollector Qs;
3226 const Type *Ty = Qs.strip(T);
3227
3228 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00003229 QualType Pointee = PTy->getPointeeType();
3230 QualType FixedType =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003231 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
3232 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003233 if (FixedType.isNull()) return FixedType;
Eli Friedman44c0f2a2009-02-21 00:58:02 +00003234 FixedType = Context.getPointerType(FixedType);
John McCall717d9b02010-12-10 11:01:00 +00003235 return Qs.apply(Context, FixedType);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003236 }
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003237 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
3238 QualType Inner = PTy->getInnerType();
3239 QualType FixedType =
3240 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
3241 Oversized);
3242 if (FixedType.isNull()) return FixedType;
3243 FixedType = Context.getParenType(FixedType);
3244 return Qs.apply(Context, FixedType);
3245 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00003246
3247 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanadf40d42009-02-26 03:58:54 +00003248 if (!VLATy)
3249 return QualType();
3250 // FIXME: We should probably handle this case
3251 if (VLATy->getElementType()->isVariablyModifiedType())
3252 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00003253
Eli Friedmana3b1d032009-02-21 00:44:51 +00003254 Expr::EvalResult EvalResult;
3255 if (!VLATy->getSizeExpr() ||
Eli Friedmanadf40d42009-02-26 03:58:54 +00003256 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
3257 !EvalResult.Val.isInt())
Eli Friedmana3b1d032009-02-21 00:44:51 +00003258 return QualType();
Eli Friedmanadf40d42009-02-26 03:58:54 +00003259
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003260 // Check whether the array size is negative.
Eli Friedmana3b1d032009-02-21 00:44:51 +00003261 llvm::APSInt &Res = EvalResult.Val.getInt();
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003262 if (Res.isSigned() && Res.isNegative()) {
3263 SizeIsNegative = true;
3264 return QualType();
Douglas Gregor04318252009-07-06 15:59:29 +00003265 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00003266
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003267 // Check whether the array is too large to be addressed.
3268 unsigned ActiveSizeBits
3269 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
3270 Res);
3271 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
3272 Oversized = Res;
3273 return QualType();
3274 }
3275
3276 return Context.getConstantArrayType(VLATy->getElementType(),
3277 Res, ArrayType::Normal, 0);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003278}
3279
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003280/// \brief Register the given locally-scoped external C declaration so
3281/// that it can be found later for redeclarations
Mike Stump11289f42009-09-09 15:08:12 +00003282void
John McCall1f82f242009-11-18 22:49:29 +00003283Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
3284 const LookupResult &Previous,
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003285 Scope *S) {
3286 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
3287 "Decl is not a locally-scoped decl!");
3288 // Note that we have a locally-scoped external with this name.
3289 LocallyScopedExternalDecls[ND->getDeclName()] = ND;
3290
John McCall1f82f242009-11-18 22:49:29 +00003291 if (!Previous.isSingleResult())
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003292 return;
3293
John McCall1f82f242009-11-18 22:49:29 +00003294 NamedDecl *PrevDecl = Previous.getFoundDecl();
3295
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003296 // If there was a previous declaration of this variable, it may be
3297 // in our identifier chain. Update the identifier chain with the new
3298 // declaration.
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003299 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003300 // The previous declaration was found on the identifer resolver
3301 // chain, so remove it from its scope.
John McCall48871652010-08-21 09:40:31 +00003302 while (S && !S->isDeclScope(PrevDecl))
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003303 S = S->getParent();
3304
3305 if (S)
John McCall48871652010-08-21 09:40:31 +00003306 S->RemoveDecl(PrevDecl);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003307 }
3308}
3309
Eli Friedman574c7452009-04-07 19:37:57 +00003310/// \brief Diagnose function specifiers on a declaration of an identifier that
3311/// does not identify a function.
3312void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
3313 // FIXME: We should probably indicate the identifier in question to avoid
3314 // confusion for constructs like "inline int a(), b;"
3315 if (D.getDeclSpec().isInlineSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00003316 Diag(D.getDeclSpec().getInlineSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00003317 diag::err_inline_non_function);
3318
3319 if (D.getDeclSpec().isVirtualSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00003320 Diag(D.getDeclSpec().getVirtualSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00003321 diag::err_virtual_non_function);
3322
3323 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00003324 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00003325 diag::err_explicit_non_function);
3326}
3327
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003328NamedDecl*
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003329Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
John McCallbcd03502009-12-07 02:54:59 +00003330 QualType R, TypeSourceInfo *TInfo,
John McCall1f82f242009-11-18 22:49:29 +00003331 LookupResult &Previous, bool &Redeclaration) {
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003332 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
3333 if (D.getCXXScopeSpec().isSet()) {
3334 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
3335 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003336 D.setInvalidType();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003337 // Pretend we didn't see the scope specifier.
Douglas Gregorb525ef82010-03-23 15:26:55 +00003338 DC = CurContext;
3339 Previous.clear();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003340 }
3341
Douglas Gregor0c880302009-03-11 23:00:04 +00003342 if (getLangOptions().CPlusPlus) {
3343 // Check that there are no default arguments (C++ only).
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003344 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00003345 }
3346
Eli Friedman574c7452009-04-07 19:37:57 +00003347 DiagnoseFunctionSpecifiers(D);
3348
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003349 if (D.getDeclSpec().isThreadSpecified())
3350 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
3351
Douglas Gregord8f446f2010-07-13 06:37:01 +00003352 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
3353 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
3354 << D.getName().getSourceRange();
3355 return 0;
3356 }
3357
John McCallbcd03502009-12-07 02:54:59 +00003358 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, TInfo);
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003359 if (!NewTD) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003360
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003361 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00003362 ProcessDeclAttributes(S, NewTD, D);
John McCall1f82f242009-11-18 22:49:29 +00003363
Richard Smith3f1b5d02011-05-05 21:57:07 +00003364 CheckTypedefForVariablyModifiedType(S, NewTD);
3365
Richard Smithdda56e42011-04-15 14:24:37 +00003366 return ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
3367}
3368
Richard Smith3f1b5d02011-05-05 21:57:07 +00003369void
3370Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner9fecd742009-04-19 05:21:20 +00003371 // C99 6.7.7p2: If a typedef name specifies a variably modified type
3372 // then it shall have block scope.
Eli Friedman88f4ed92010-08-10 03:13:15 +00003373 // Note that variably modified types must be fixed before merging the decl so
3374 // that redeclarations will match.
Chris Lattner9fecd742009-04-19 05:21:20 +00003375 QualType T = NewTD->getUnderlyingType();
3376 if (T->isVariablyModifiedType()) {
John McCallaab3e412010-08-25 08:40:02 +00003377 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00003378
Chris Lattner9fecd742009-04-19 05:21:20 +00003379 if (S->getFnParent() == 0) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00003380 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003381 llvm::APSInt Oversized;
Eli Friedmana3b1d032009-02-21 00:44:51 +00003382 QualType FixedTy =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003383 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
3384 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003385 if (!FixedTy.isNull()) {
Richard Smithdda56e42011-04-15 14:24:37 +00003386 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
John McCallbcd03502009-12-07 02:54:59 +00003387 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
Eli Friedmana3b1d032009-02-21 00:44:51 +00003388 } else {
3389 if (SizeIsNegative)
Richard Smithdda56e42011-04-15 14:24:37 +00003390 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003391 else if (T->isVariableArrayType())
Richard Smithdda56e42011-04-15 14:24:37 +00003392 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003393 else if (Oversized.getBoolValue())
Richard Smithdda56e42011-04-15 14:24:37 +00003394 Diag(NewTD->getLocation(), diag::err_array_too_large) << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003395 else
Richard Smithdda56e42011-04-15 14:24:37 +00003396 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003397 NewTD->setInvalidDecl();
Eli Friedmana3b1d032009-02-21 00:44:51 +00003398 }
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003399 }
3400 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003401}
Douglas Gregor27821ce2009-07-07 16:35:42 +00003402
Richard Smith3f1b5d02011-05-05 21:57:07 +00003403
3404/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
3405/// declares a typedef-name, either using the 'typedef' type specifier or via
3406/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
3407NamedDecl*
3408Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
3409 LookupResult &Previous, bool &Redeclaration) {
Eli Friedman88f4ed92010-08-10 03:13:15 +00003410 // Merge the decl with the existing one if appropriate. If the decl is
3411 // in an outer scope, it isn't the same thing.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003412 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
Douglas Gregordb446112011-03-07 16:54:27 +00003413 /*ExplicitInstantiationOrSpecialization=*/false);
Eli Friedman88f4ed92010-08-10 03:13:15 +00003414 if (!Previous.empty()) {
3415 Redeclaration = true;
Richard Smithdda56e42011-04-15 14:24:37 +00003416 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00003417 }
3418
Douglas Gregor27821ce2009-07-07 16:35:42 +00003419 // If this is the C FILE type, notify the AST context.
3420 if (IdentifierInfo *II = NewTD->getIdentifier())
3421 if (!NewTD->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003422 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stumpa4de80b2009-07-28 02:25:19 +00003423 if (II->isStr("FILE"))
3424 Context.setFILEDecl(NewTD);
3425 else if (II->isStr("jmp_buf"))
3426 Context.setjmp_bufDecl(NewTD);
3427 else if (II->isStr("sigjmp_buf"))
3428 Context.setsigjmp_bufDecl(NewTD);
Douglas Gregor2c2c4cd2010-10-05 15:41:24 +00003429 else if (II->isStr("__builtin_va_list"))
3430 Context.setBuiltinVaListType(Context.getTypedefType(NewTD));
Mike Stumpa4de80b2009-07-28 02:25:19 +00003431 }
3432
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003433 return NewTD;
3434}
3435
Douglas Gregor5d68a202009-02-24 19:23:27 +00003436/// \brief Determines whether the given declaration is an out-of-scope
3437/// previous declaration.
3438///
3439/// This routine should be invoked when name lookup has found a
3440/// previous declaration (PrevDecl) that is not in the scope where a
3441/// new declaration by the same name is being introduced. If the new
3442/// declaration occurs in a local scope, previous declarations with
3443/// linkage may still be considered previous declarations (C99
3444/// 6.2.2p4-5, C++ [basic.link]p6).
3445///
3446/// \param PrevDecl the previous declaration found by name
3447/// lookup
Mike Stump11289f42009-09-09 15:08:12 +00003448///
Douglas Gregor5d68a202009-02-24 19:23:27 +00003449/// \param DC the context in which the new declaration is being
3450/// declared.
3451///
3452/// \returns true if PrevDecl is an out-of-scope previous declaration
3453/// for a new delcaration with the same name.
Mike Stump11289f42009-09-09 15:08:12 +00003454static bool
Douglas Gregor5d68a202009-02-24 19:23:27 +00003455isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
3456 ASTContext &Context) {
3457 if (!PrevDecl)
Sebastian Redl50c68252010-08-31 00:36:30 +00003458 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00003459
Douglas Gregoreddf4332009-02-24 20:03:32 +00003460 if (!PrevDecl->hasLinkage())
3461 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00003462
3463 if (Context.getLangOptions().CPlusPlus) {
3464 // C++ [basic.link]p6:
3465 // If there is a visible declaration of an entity with linkage
3466 // having the same name and type, ignoring entities declared
3467 // outside the innermost enclosing namespace scope, the block
3468 // scope declaration declares that same entity and receives the
3469 // linkage of the previous declaration.
Sebastian Redl50c68252010-08-31 00:36:30 +00003470 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor5d68a202009-02-24 19:23:27 +00003471 if (!OuterContext->isFunctionOrMethod())
3472 // This rule only applies to block-scope declarations.
3473 return false;
Douglas Gregorfcee9462010-08-27 22:55:10 +00003474
3475 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
3476 if (PrevOuterContext->isRecord())
3477 // We found a member function: ignore it.
3478 return false;
3479
3480 // Find the innermost enclosing namespace for the new and
3481 // previous declarations.
Sebastian Redl50c68252010-08-31 00:36:30 +00003482 OuterContext = OuterContext->getEnclosingNamespaceContext();
3483 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump11289f42009-09-09 15:08:12 +00003484
Douglas Gregorfcee9462010-08-27 22:55:10 +00003485 // The previous declaration is in a different namespace, so it
3486 // isn't the same function.
3487 if (!OuterContext->Equals(PrevOuterContext))
3488 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00003489 }
3490
Douglas Gregor5d68a202009-02-24 19:23:27 +00003491 return true;
3492}
3493
John McCall3e11ebe2010-03-15 10:12:16 +00003494static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
3495 CXXScopeSpec &SS = D.getCXXScopeSpec();
3496 if (!SS.isSet()) return;
Douglas Gregor14454802011-02-25 02:25:35 +00003497 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00003498}
3499
John McCall31168b02011-06-15 23:02:42 +00003500bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
3501 QualType type = decl->getType();
3502 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
3503 if (lifetime == Qualifiers::OCL_Autoreleasing) {
3504 // Various kinds of declaration aren't allowed to be __autoreleasing.
3505 unsigned kind = -1U;
3506 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
3507 if (var->hasAttr<BlocksAttr>())
3508 kind = 0; // __block
3509 else if (!var->hasLocalStorage())
3510 kind = 1; // global
3511 } else if (isa<ObjCIvarDecl>(decl)) {
3512 kind = 3; // ivar
3513 } else if (isa<FieldDecl>(decl)) {
3514 kind = 2; // field
3515 }
3516
3517 if (kind != -1U) {
3518 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
3519 << kind;
3520 }
3521 } else if (lifetime == Qualifiers::OCL_None) {
3522 // Try to infer lifetime.
3523 if (!type->isObjCLifetimeType())
3524 return false;
3525
3526 lifetime = type->getObjCARCImplicitLifetime();
3527 type = Context.getLifetimeQualifiedType(type, lifetime);
3528 decl->setType(type);
3529 }
3530
3531 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
3532 // Thread-local variables cannot have lifetime.
3533 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
3534 var->isThreadSpecified()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003535 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCall31168b02011-06-15 23:02:42 +00003536 << var->getType();
3537 return true;
3538 }
3539 }
3540
3541 return false;
3542}
3543
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003544NamedDecl*
Chris Lattner88fdea82010-10-10 18:16:20 +00003545Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
John McCallbcd03502009-12-07 02:54:59 +00003546 QualType R, TypeSourceInfo *TInfo,
John McCall1f82f242009-11-18 22:49:29 +00003547 LookupResult &Previous,
Douglas Gregorb09f3d82009-07-22 17:18:37 +00003548 MultiTemplateParamsArg TemplateParamLists,
Douglas Gregor75a45ba2009-02-16 17:45:42 +00003549 bool &Redeclaration) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003550 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003551
3552 // Check that there are no default arguments (C++ only).
3553 if (getLangOptions().CPlusPlus)
3554 CheckExtraCXXDefaultArguments(D);
3555
Douglas Gregorc4df4072010-04-19 22:54:31 +00003556 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
3557 assert(SCSpec != DeclSpec::SCS_typedef &&
3558 "Parser allowed 'typedef' as storage class VarDecl.");
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00003559 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregorc4df4072010-04-19 22:54:31 +00003560 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003561 // mutable can only appear on non-static class members, so it's always
3562 // an error here
3563 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003564 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003565 SC = SC_None;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003566 }
Douglas Gregorc4df4072010-04-19 22:54:31 +00003567 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
3568 VarDecl::StorageClass SCAsWritten
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00003569 = StorageClassSpecToVarDeclStorageClass(SCSpec);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003570
3571 IdentifierInfo *II = Name.getAsIdentifierInfo();
3572 if (!II) {
3573 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
3574 << Name.getAsString();
3575 return 0;
3576 }
3577
Eli Friedman574c7452009-04-07 19:37:57 +00003578 DiagnoseFunctionSpecifiers(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00003579
Douglas Gregor212cab32009-03-11 20:22:50 +00003580 if (!DC->isRecord() && S->getFnParent() == 0) {
3581 // C99 6.9p2: The storage-class specifiers auto and register shall not
3582 // appear in the declaration specifiers in an external declaration.
John McCall8e7d6562010-08-26 03:08:43 +00003583 if (SC == SC_Auto || SC == SC_Register) {
Mike Stump11289f42009-09-09 15:08:12 +00003584
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00003585 // If this is a register variable with an asm label specified, then this
3586 // is a GNU extension.
John McCall8e7d6562010-08-26 03:08:43 +00003587 if (SC == SC_Register && D.getAsmLabel())
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00003588 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
3589 else
3590 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003591 D.setInvalidType();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003592 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003593 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003594
Ted Kremenek582a0992011-01-23 17:04:59 +00003595 bool isExplicitSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003596 VarDecl *NewVD;
3597 if (!getLangOptions().CPlusPlus) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003598 NewVD = VarDecl::Create(Context, DC, D.getSourceRange().getBegin(),
3599 D.getIdentifierLoc(), II,
3600 R, TInfo, SC, SCAsWritten);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003601
3602 if (D.isInvalidType())
3603 NewVD->setInvalidDecl();
3604 } else {
3605 if (DC->isRecord() && !CurContext->isRecord()) {
3606 // This is an out-of-line definition of a static data member.
3607 if (SC == SC_Static) {
3608 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
3609 diag::err_static_out_of_line)
3610 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3611 } else if (SC == SC_None)
3612 SC = SC_Static;
Anders Carlssond2e8adf2009-06-24 00:28:53 +00003613 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003614 if (SC == SC_Static) {
3615 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
3616 if (RD->isLocalClass())
3617 Diag(D.getIdentifierLoc(),
3618 diag::err_static_data_member_not_allowed_in_local_class)
3619 << Name << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003620
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003621 // C++ [class.union]p1: If a union contains a static data member,
3622 // the program is ill-formed.
3623 //
3624 // We also disallow static data members in anonymous structs.
3625 if (CurContext->isRecord() && (RD->isUnion() || !RD->getDeclName()))
3626 Diag(D.getIdentifierLoc(),
3627 diag::err_static_data_member_not_allowed_in_union_or_anon_struct)
3628 << Name << RD->isUnion();
3629 }
3630 }
3631
3632 // Match up the template parameter lists with the scope specifier, then
3633 // determine whether we have a template or a template specialization.
3634 isExplicitSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003635 bool Invalid = false;
3636 if (TemplateParameterList *TemplateParams
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003637 = MatchTemplateParametersToScopeSpecifier(
Douglas Gregor972fe532011-05-10 18:27:06 +00003638 D.getDeclSpec().getSourceRange().getBegin(),
3639 D.getIdentifierLoc(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003640 D.getCXXScopeSpec(),
John McCallace48cd2010-10-19 01:40:49 +00003641 TemplateParamLists.get(),
3642 TemplateParamLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00003643 /*never a friend*/ false,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003644 isExplicitSpecialization,
3645 Invalid)) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003646 if (TemplateParams->size() > 0) {
3647 // There is no such thing as a variable template.
3648 Diag(D.getIdentifierLoc(), diag::err_template_variable)
3649 << II
3650 << SourceRange(TemplateParams->getTemplateLoc(),
3651 TemplateParams->getRAngleLoc());
3652 return 0;
3653 } else {
3654 // There is an extraneous 'template<>' for this variable. Complain
3655 // about it, but allow the declaration of the variable.
3656 Diag(TemplateParams->getTemplateLoc(),
3657 diag::err_template_variable_noparams)
3658 << II
3659 << SourceRange(TemplateParams->getTemplateLoc(),
3660 TemplateParams->getRAngleLoc());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003661 }
Douglas Gregorb09f3d82009-07-22 17:18:37 +00003662 }
Mike Stump11289f42009-09-09 15:08:12 +00003663
Abramo Bagnaradff19302011-03-08 08:55:46 +00003664 NewVD = VarDecl::Create(Context, DC, D.getSourceRange().getBegin(),
3665 D.getIdentifierLoc(), II,
3666 R, TInfo, SC, SCAsWritten);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003667
Richard Smithb2bc2e62011-02-21 20:05:19 +00003668 // If this decl has an auto type in need of deduction, make a note of the
3669 // Decl so we can diagnose uses of it in its own initializer.
3670 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
3671 R->getContainedAutoType())
3672 ParsingInitForAutoVars.insert(NewVD);
Richard Smith30482bc2011-02-20 03:19:35 +00003673
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003674 if (D.isInvalidType() || Invalid)
3675 NewVD->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003676
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003677 SetNestedNameSpecifier(NewVD, D);
John McCall3e11ebe2010-03-15 10:12:16 +00003678
Abramo Bagnara60804e12011-03-18 15:16:37 +00003679 if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003680 NewVD->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00003681 TemplateParamLists.size(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003682 TemplateParamLists.release());
3683 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003684 }
3685
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003686 if (D.getDeclSpec().isThreadSpecified()) {
3687 if (NewVD->hasLocalStorage())
3688 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
Eli Friedmandaea3f62009-04-19 21:48:33 +00003689 else if (!Context.Target.isTLSSupported())
3690 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003691 else
3692 NewVD->setThreadSpecified(true);
3693 }
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003694
Douglas Gregor04e9a032009-03-11 23:52:16 +00003695 // Set the lexical context. If the declarator has a C++ scope specifier, the
3696 // lexical context will be different from the semantic context.
3697 NewVD->setLexicalDeclContext(CurContext);
3698
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003699 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00003700 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003701
John McCall31168b02011-06-15 23:02:42 +00003702 // In auto-retain/release, infer strong retension for variables of
3703 // retainable type.
3704 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
3705 NewVD->setInvalidDecl();
3706
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003707 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner88fdea82010-10-10 18:16:20 +00003708 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003709 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00003710 StringLiteral *SE = cast<StringLiteral>(E);
Rafael Espindola478abca2011-01-01 21:47:03 +00003711 llvm::StringRef Label = SE->getString();
Abramo Bagnara13392232011-01-11 15:16:52 +00003712 if (S->getFnParent() != 0) {
3713 switch (SC) {
3714 case SC_None:
3715 case SC_Auto:
3716 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
3717 break;
3718 case SC_Register:
3719 if (!Context.Target.isValidGCCRegisterName(Label))
3720 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
3721 break;
3722 case SC_Static:
3723 case SC_Extern:
3724 case SC_PrivateExtern:
3725 break;
3726 }
3727 }
3728
3729 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Rafael Espindola478abca2011-01-01 21:47:03 +00003730 Context, Label));
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003731 }
3732
John McCalla2a3f7d2010-03-16 21:48:18 +00003733 // Diagnose shadowed variables before filtering for scope.
John McCall2d8c7602010-03-20 04:12:52 +00003734 if (!D.getCXXScopeSpec().isSet())
John McCalldf8b37c2010-03-22 09:20:08 +00003735 CheckShadow(S, NewVD, Previous);
John McCalla2a3f7d2010-03-16 21:48:18 +00003736
John McCall1f82f242009-11-18 22:49:29 +00003737 // Don't consider existing declarations that are in a different
3738 // scope and are out-of-semantic-context declarations (if the new
3739 // declaration has linkage).
Richard Smith3f1b5d02011-05-05 21:57:07 +00003740 FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(),
Douglas Gregordb446112011-03-07 16:54:27 +00003741 isExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00003742
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003743 if (!getLangOptions().CPlusPlus)
3744 CheckVariableDeclaration(NewVD, Previous, Redeclaration);
3745 else {
3746 // Merge the decl with the existing one if appropriate.
3747 if (!Previous.empty()) {
3748 if (Previous.isSingleResult() &&
3749 isa<FieldDecl>(Previous.getFoundDecl()) &&
3750 D.getCXXScopeSpec().isSet()) {
3751 // The user tried to define a non-static data member
3752 // out-of-line (C++ [dcl.meaning]p1).
3753 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
3754 << D.getCXXScopeSpec().getRange();
3755 Previous.clear();
3756 NewVD->setInvalidDecl();
3757 }
3758 } else if (D.getCXXScopeSpec().isSet()) {
3759 // No previous declaration in the qualifying scope.
3760 Diag(D.getIdentifierLoc(), diag::err_no_member)
3761 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003762 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003763 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003764 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003765
3766 CheckVariableDeclaration(NewVD, Previous, Redeclaration);
3767
3768 // This is an explicit specialization of a static data member. Check it.
3769 if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
3770 CheckMemberSpecialization(NewVD, Previous))
3771 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003772 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003773
Ryan Flynne5dc8592009-07-25 22:29:44 +00003774 // attributes declared post-definition are currently ignored
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003775 // FIXME: This should be handled in attribute merging, not
3776 // here.
John McCall1f82f242009-11-18 22:49:29 +00003777 if (Previous.isSingleResult()) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00003778 VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl());
3779 if (Def && (Def = Def->getDefinition()) &&
3780 Def != NewVD && D.hasAttributes()) {
Ryan Flynne5dc8592009-07-25 22:29:44 +00003781 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
3782 Diag(Def->getLocation(), diag::note_previous_definition);
3783 }
3784 }
3785
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003786 // If this is a locally-scoped extern C variable, update the map of
3787 // such variables.
Douglas Gregor16618f22009-09-12 00:17:51 +00003788 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003789 !NewVD->isInvalidDecl())
John McCall1f82f242009-11-18 22:49:29 +00003790 RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003791
Eli Friedman570024a2010-08-05 06:57:20 +00003792 // If there's a #pragma GCC visibility in scope, and this isn't a class
3793 // member, set the visibility of this variable.
3794 if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord())
3795 AddPushedVisibilityAttribute(NewVD);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003796
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00003797 MarkUnusedFileScopedDecl(NewVD);
3798
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003799 return NewVD;
3800}
3801
John McCalldf8b37c2010-03-22 09:20:08 +00003802/// \brief Diagnose variable or built-in function shadowing. Implements
3803/// -Wshadow.
John McCalla2a3f7d2010-03-16 21:48:18 +00003804///
John McCalldf8b37c2010-03-22 09:20:08 +00003805/// This method is called whenever a VarDecl is added to a "useful"
3806/// scope.
John McCalla2a3f7d2010-03-16 21:48:18 +00003807///
John McCall2d8c7602010-03-20 04:12:52 +00003808/// \param S the scope in which the shadowing name is being declared
3809/// \param R the lookup of the name
John McCalla2a3f7d2010-03-16 21:48:18 +00003810///
John McCalldf8b37c2010-03-22 09:20:08 +00003811void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCalla2a3f7d2010-03-16 21:48:18 +00003812 // Return if warning is ignored.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003813 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
3814 Diagnostic::Ignored)
John McCalla2a3f7d2010-03-16 21:48:18 +00003815 return;
3816
Argyrios Kyrtzidis898fdbf2011-02-08 18:21:25 +00003817 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00003818 if (D->hasGlobalStorage())
John McCalla2a3f7d2010-03-16 21:48:18 +00003819 return;
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00003820
3821 DeclContext *NewDC = D->getDeclContext();
3822
John McCall2d8c7602010-03-20 04:12:52 +00003823 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregor319aa6c2010-03-17 16:03:44 +00003824 if (R.getResultKind() != LookupResult::Found)
John McCalla2a3f7d2010-03-16 21:48:18 +00003825 return;
John McCalla2a3f7d2010-03-16 21:48:18 +00003826
John McCalla2a3f7d2010-03-16 21:48:18 +00003827 NamedDecl* ShadowedDecl = R.getFoundDecl();
3828 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
3829 return;
3830
Argyrios Kyrtzidisf46cc652011-01-31 07:04:54 +00003831 // Fields are not shadowed by variables in C++ static methods.
3832 if (isa<FieldDecl>(ShadowedDecl))
3833 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
3834 if (MD->isStatic())
3835 return;
3836
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00003837 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
3838 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00003839 // For shadowing external vars, make sure that we point to the global
3840 // declaration, not a locally scoped extern declaration.
3841 for (VarDecl::redecl_iterator
3842 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
3843 I != E; ++I)
3844 if (I->isFileVarDecl()) {
3845 ShadowedDecl = *I;
3846 break;
3847 }
3848 }
3849
3850 DeclContext *OldDC = ShadowedDecl->getDeclContext();
3851
John McCall2d8c7602010-03-20 04:12:52 +00003852 // Only warn about certain kinds of shadowing for class members.
3853 if (NewDC && NewDC->isRecord()) {
3854 // In particular, don't warn about shadowing non-class members.
3855 if (!OldDC->isRecord())
3856 return;
3857
3858 // TODO: should we warn about static data members shadowing
3859 // static data members from base classes?
3860
3861 // TODO: don't diagnose for inaccessible shadowed members.
3862 // This is hard to do perfectly because we might friend the
3863 // shadowing context, but that's just a false negative.
3864 }
3865
3866 // Determine what kind of declaration we're shadowing.
John McCalla2a3f7d2010-03-16 21:48:18 +00003867 unsigned Kind;
John McCall2d8c7602010-03-20 04:12:52 +00003868 if (isa<RecordDecl>(OldDC)) {
John McCalla2a3f7d2010-03-16 21:48:18 +00003869 if (isa<FieldDecl>(ShadowedDecl))
3870 Kind = 3; // field
3871 else
3872 Kind = 2; // static data member
John McCall2d8c7602010-03-20 04:12:52 +00003873 } else if (OldDC->isFileContext())
John McCalla2a3f7d2010-03-16 21:48:18 +00003874 Kind = 1; // global
3875 else
3876 Kind = 0; // local
3877
John McCall2d8c7602010-03-20 04:12:52 +00003878 DeclarationName Name = R.getLookupName();
3879
John McCalla2a3f7d2010-03-16 21:48:18 +00003880 // Emit warning and note.
John McCall2d8c7602010-03-20 04:12:52 +00003881 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCalla2a3f7d2010-03-16 21:48:18 +00003882 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
3883}
3884
John McCalldf8b37c2010-03-22 09:20:08 +00003885/// \brief Check -Wshadow without the advantage of a previous lookup.
3886void Sema::CheckShadow(Scope *S, VarDecl *D) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003887 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
3888 Diagnostic::Ignored)
3889 return;
3890
John McCalldf8b37c2010-03-22 09:20:08 +00003891 LookupResult R(*this, D->getDeclName(), D->getLocation(),
3892 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
3893 LookupName(R, S);
3894 CheckShadow(S, D, R);
3895}
3896
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003897/// \brief Perform semantic checking on a newly-created variable
3898/// declaration.
3899///
3900/// This routine performs all of the type-checking required for a
Douglas Gregorf16a8a72009-05-01 15:47:09 +00003901/// variable declaration once it has been built. It is used both to
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003902/// check variables after they have been parsed and their declarators
Douglas Gregorf16a8a72009-05-01 15:47:09 +00003903/// have been translated into a declaration, and to check variables
3904/// that have been instantiated from a template.
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003905///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003906/// Sets NewVD->isInvalidDecl() if an error was encountered.
John McCall1f82f242009-11-18 22:49:29 +00003907void Sema::CheckVariableDeclaration(VarDecl *NewVD,
3908 LookupResult &Previous,
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003909 bool &Redeclaration) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003910 // If the decl is already known invalid, don't check it.
3911 if (NewVD->isInvalidDecl())
3912 return;
Mike Stump11289f42009-09-09 15:08:12 +00003913
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003914 QualType T = NewVD->getType();
3915
John McCall8b07ec22010-05-15 11:32:37 +00003916 if (T->isObjCObjectType()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003917 Diag(NewVD->getLocation(), diag::err_statically_allocated_object);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003918 return NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003919 }
Mike Stump11289f42009-09-09 15:08:12 +00003920
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003921 // Emit an error if an address space was applied to decl with local storage.
3922 // This includes arrays of objects with address space qualifiers, but not
3923 // automatic variables that point to other address spaces.
3924 // ISO/IEC TR 18037 S5.1.2
Chris Lattner88fdea82010-10-10 18:16:20 +00003925 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003926 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003927 return NewVD->setInvalidDecl();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003928 }
Fariborz Jahanian0c9404e2009-02-21 19:44:02 +00003929
Mike Stumpca5ae662009-04-14 00:57:29 +00003930 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00003931 && !NewVD->hasAttr<BlocksAttr>()) {
3932 if (getLangOptions().getGCMode() != LangOptions::NonGC)
3933 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
3934 else
3935 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
3936 }
Chris Lattner88fdea82010-10-10 18:16:20 +00003937
Chris Lattner9fecd742009-04-19 05:21:20 +00003938 bool isVM = T->isVariablyModifiedType();
Chris Lattner9662cd32009-07-19 20:17:11 +00003939 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalld4e1b762010-08-01 01:24:59 +00003940 NewVD->hasAttr<BlocksAttr>())
John McCallaab3e412010-08-25 08:40:02 +00003941 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00003942
Chris Lattner9fecd742009-04-19 05:21:20 +00003943 if ((isVM && NewVD->hasLinkage()) ||
3944 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson6c885802009-02-28 21:56:50 +00003945 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003946 llvm::APSInt Oversized;
Anders Carlsson6c885802009-02-28 21:56:50 +00003947 QualType FixedTy =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003948 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
3949 Oversized);
Mike Stump11289f42009-09-09 15:08:12 +00003950
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003951 if (FixedTy.isNull() && T->isVariableArrayType()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003952 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00003953 // FIXME: This won't give the correct result for
3954 // int a[10][n];
Anders Carlsson6c885802009-02-28 21:56:50 +00003955 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003956
Anders Carlsson6c885802009-02-28 21:56:50 +00003957 if (NewVD->isFileVarDecl())
3958 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003959 << SizeRange;
John McCall8e7d6562010-08-26 03:08:43 +00003960 else if (NewVD->getStorageClass() == SC_Static)
Anders Carlsson6c885802009-02-28 21:56:50 +00003961 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003962 << SizeRange;
Anders Carlsson6c885802009-02-28 21:56:50 +00003963 else
3964 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003965 << SizeRange;
3966 return NewVD->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003967 }
3968
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003969 if (FixedTy.isNull()) {
Anders Carlsson6c885802009-02-28 21:56:50 +00003970 if (NewVD->isFileVarDecl())
3971 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
3972 else
3973 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003974 return NewVD->setInvalidDecl();
Anders Carlsson6c885802009-02-28 21:56:50 +00003975 }
Mike Stump11289f42009-09-09 15:08:12 +00003976
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003977 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
3978 NewVD->setType(FixedTy);
Anders Carlsson6c885802009-02-28 21:56:50 +00003979 }
3980
John McCall1f82f242009-11-18 22:49:29 +00003981 if (Previous.empty() && NewVD->isExternC()) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003982 // Since we did not find anything by this name and we're declaring
3983 // an extern "C" variable, look for a non-visible extern "C"
3984 // declaration with the same name.
3985 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003986 = LocallyScopedExternalDecls.find(NewVD->getDeclName());
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003987 if (Pos != LocallyScopedExternalDecls.end())
John McCall1f82f242009-11-18 22:49:29 +00003988 Previous.addDecl(Pos->second);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003989 }
3990
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003991 if (T->isVoidType() && !NewVD->hasExternalStorage()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003992 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
3993 << T;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003994 return NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003995 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003996
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003997 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00003998 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
3999 return NewVD->setInvalidDecl();
4000 }
Mike Stump11289f42009-09-09 15:08:12 +00004001
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004002 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpa7128632009-05-01 23:41:47 +00004003 Diag(NewVD->getLocation(), diag::err_block_on_vm);
4004 return NewVD->setInvalidDecl();
4005 }
4006
Sebastian Redl5467c9f2010-07-12 23:11:43 +00004007 // Function pointers and references cannot have qualified function type, only
4008 // function pointer-to-members can do that.
4009 QualType Pointee;
4010 unsigned PtrOrRef = 0;
4011 if (const PointerType *Ptr = T->getAs<PointerType>())
4012 Pointee = Ptr->getPointeeType();
4013 else if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
4014 Pointee = Ref->getPointeeType();
4015 PtrOrRef = 1;
4016 }
4017 if (!Pointee.isNull() && Pointee->isFunctionProtoType() &&
4018 Pointee->getAs<FunctionProtoType>()->getTypeQuals() != 0) {
4019 Diag(NewVD->getLocation(), diag::err_invalid_qualified_function_pointer)
4020 << PtrOrRef;
4021 return NewVD->setInvalidDecl();
4022 }
4023
John McCall1f82f242009-11-18 22:49:29 +00004024 if (!Previous.empty()) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00004025 Redeclaration = true;
John McCall1f82f242009-11-18 22:49:29 +00004026 MergeVarDecl(NewVD, Previous);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004027 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004028}
4029
Douglas Gregor36d1b142009-10-06 17:59:45 +00004030/// \brief Data used with FindOverriddenMethod
4031struct FindOverriddenMethodData {
4032 Sema *S;
4033 CXXMethodDecl *Method;
4034};
4035
4036/// \brief Member lookup function that determines whether a given C++
4037/// method overrides a method in a base class, to be used with
4038/// CXXRecordDecl::lookupInBases().
John McCall84c16cf2009-11-12 03:15:40 +00004039static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregor36d1b142009-10-06 17:59:45 +00004040 CXXBasePath &Path,
4041 void *UserData) {
4042 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlssone985fae2009-11-26 20:50:40 +00004043
Douglas Gregor36d1b142009-10-06 17:59:45 +00004044 FindOverriddenMethodData *Data
4045 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlssone985fae2009-11-26 20:50:40 +00004046
4047 DeclarationName Name = Data->Method->getDeclName();
4048
4049 // FIXME: Do we care about other names here too?
4050 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCalle9cccd82010-06-16 08:42:20 +00004051 // We really want to find the base class destructor here.
Anders Carlssone985fae2009-11-26 20:50:40 +00004052 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
4053 CanQualType CT = Data->S->Context.getCanonicalType(T);
4054
Anders Carlsson5a4f7722009-11-27 01:26:58 +00004055 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlssone985fae2009-11-26 20:50:40 +00004056 }
4057
4058 for (Path.Decls = BaseRecord->lookup(Name);
Douglas Gregor36d1b142009-10-06 17:59:45 +00004059 Path.Decls.first != Path.Decls.second;
4060 ++Path.Decls.first) {
John McCall38e5f432010-06-16 09:33:39 +00004061 NamedDecl *D = *Path.Decls.first;
John McCalle9cccd82010-06-16 08:42:20 +00004062 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4063 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregor36d1b142009-10-06 17:59:45 +00004064 return true;
4065 }
4066 }
4067
4068 return false;
4069}
4070
Sebastian Redld5b24532009-11-18 21:51:29 +00004071/// AddOverriddenMethods - See if a method overrides any in the base classes,
4072/// and if so, check that it's a valid override and remember it.
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004073bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redld5b24532009-11-18 21:51:29 +00004074 // Look for virtual methods in base classes that this method might override.
4075 CXXBasePaths Paths;
4076 FindOverriddenMethodData Data;
4077 Data.Method = MD;
4078 Data.S = this;
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004079 bool AddedAny = false;
Sebastian Redld5b24532009-11-18 21:51:29 +00004080 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
4081 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
4082 E = Paths.found_decls_end(); I != E; ++I) {
4083 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
4084 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Alexis Hunt96d5c762009-11-21 08:43:09 +00004085 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
Anders Carlsson3f610c72011-01-20 16:25:36 +00004086 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
Anders Carlssonf3935b42009-12-04 05:51:56 +00004087 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004088 AddedAny = true;
4089 }
Sebastian Redld5b24532009-11-18 21:51:29 +00004090 }
4091 }
4092 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004093
4094 return AddedAny;
Sebastian Redld5b24532009-11-18 21:51:29 +00004095}
4096
John McCallf7cfb222010-10-13 05:45:15 +00004097static void DiagnoseInvalidRedeclaration(Sema &S, FunctionDecl *NewFD) {
4098 LookupResult Prev(S, NewFD->getDeclName(), NewFD->getLocation(),
4099 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
4100 S.LookupQualifiedName(Prev, NewFD->getDeclContext());
4101 assert(!Prev.isAmbiguous() &&
4102 "Cannot have an ambiguity in previous-declaration lookup");
4103 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
4104 Func != FuncEnd; ++Func) {
4105 if (isa<FunctionDecl>(*Func) &&
4106 isNearlyMatchingFunction(S.Context, cast<FunctionDecl>(*Func), NewFD))
4107 S.Diag((*Func)->getLocation(), diag::note_member_def_close_match);
4108 }
4109}
4110
Mike Stump11289f42009-09-09 15:08:12 +00004111NamedDecl*
Zhongxing Xubece5d62009-01-16 01:13:29 +00004112Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
John McCallbcd03502009-12-07 02:54:59 +00004113 QualType R, TypeSourceInfo *TInfo,
John McCall1f82f242009-11-18 22:49:29 +00004114 LookupResult &Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004115 MultiTemplateParamsArg TemplateParamLists,
Alexis Hunt5a7fa252011-05-12 06:15:49 +00004116 bool IsFunctionDefinition, bool &Redeclaration) {
Zhongxing Xubece5d62009-01-16 01:13:29 +00004117 assert(R.getTypePtr()->isFunctionType());
4118
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004119 // TODO: consider using NameInfo for diagnostic.
4120 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4121 DeclarationName Name = NameInfo.getName();
John McCall8e7d6562010-08-26 03:08:43 +00004122 FunctionDecl::StorageClass SC = SC_None;
Zhongxing Xubece5d62009-01-16 01:13:29 +00004123 switch (D.getDeclSpec().getStorageClassSpec()) {
4124 default: assert(0 && "Unknown storage class!");
4125 case DeclSpec::SCS_auto:
4126 case DeclSpec::SCS_register:
4127 case DeclSpec::SCS_mutable:
Mike Stump11289f42009-09-09 15:08:12 +00004128 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregore62c0a42009-02-24 01:23:02 +00004129 diag::err_typecheck_sclass_func);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004130 D.setInvalidType();
Zhongxing Xubece5d62009-01-16 01:13:29 +00004131 break;
John McCall8e7d6562010-08-26 03:08:43 +00004132 case DeclSpec::SCS_unspecified: SC = SC_None; break;
4133 case DeclSpec::SCS_extern: SC = SC_Extern; break;
Douglas Gregore62c0a42009-02-24 01:23:02 +00004134 case DeclSpec::SCS_static: {
Sebastian Redl50c68252010-08-31 00:36:30 +00004135 if (CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregore62c0a42009-02-24 01:23:02 +00004136 // C99 6.7.1p5:
4137 // The declaration of an identifier for a function that has
4138 // block scope shall have no explicit storage-class specifier
4139 // other than extern
4140 // See also (C++ [dcl.stc]p4).
Mike Stump11289f42009-09-09 15:08:12 +00004141 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregore62c0a42009-02-24 01:23:02 +00004142 diag::err_static_block_func);
John McCall8e7d6562010-08-26 03:08:43 +00004143 SC = SC_None;
Douglas Gregore62c0a42009-02-24 01:23:02 +00004144 } else
John McCall8e7d6562010-08-26 03:08:43 +00004145 SC = SC_Static;
Douglas Gregore62c0a42009-02-24 01:23:02 +00004146 break;
4147 }
Gabor Greif80c21832010-09-08 00:31:13 +00004148 case DeclSpec::SCS_private_extern: SC = SC_PrivateExtern; break;
Zhongxing Xubece5d62009-01-16 01:13:29 +00004149 }
4150
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004151 if (D.getDeclSpec().isThreadSpecified())
4152 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4153
Chris Lattner347eec92009-04-11 19:17:25 +00004154 // Do not allow returning a objc interface by-value.
John McCall8b07ec22010-05-15 11:32:37 +00004155 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
Chris Lattner347eec92009-04-11 19:17:25 +00004156 Diag(D.getIdentifierLoc(),
4157 diag::err_object_cannot_be_passed_returned_by_value) << 0
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004158 << R->getAs<FunctionType>()->getResultType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004159 D.setInvalidType();
Chris Lattner347eec92009-04-11 19:17:25 +00004160 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004161
Zhongxing Xubece5d62009-01-16 01:13:29 +00004162 FunctionDecl *NewFD;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004163 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor513e63c2010-12-10 19:28:19 +00004164 bool isFriend = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004165 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
4166 FunctionDecl::StorageClass SCAsWritten
4167 = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
Douglas Gregor513e63c2010-12-10 19:28:19 +00004168 FunctionTemplateDecl *FunctionTemplate = 0;
4169 bool isExplicitSpecialization = false;
4170 bool isFunctionTemplateSpecialization = false;
Abramo Bagnara60804e12011-03-18 15:16:37 +00004171
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004172 if (!getLangOptions().CPlusPlus) {
Douglas Gregor2797d322009-03-19 18:33:54 +00004173 // Determine whether the function was written with a
4174 // prototype. This true when:
Douglas Gregor2797d322009-03-19 18:33:54 +00004175 // - there is a prototype in the declarator, or
4176 // - the type R of the function is some kind of typedef or other reference
4177 // to a type name (which eventually refers to a function type).
Mike Stump11289f42009-09-09 15:08:12 +00004178 bool HasPrototype =
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004179 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004180 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
4181
Abramo Bagnaradff19302011-03-08 08:55:46 +00004182 NewFD = FunctionDecl::Create(Context, DC, D.getSourceRange().getBegin(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004183 NameInfo, R, TInfo, SC, SCAsWritten, isInline,
Douglas Gregorc4df4072010-04-19 22:54:31 +00004184 HasPrototype);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004185 if (D.isInvalidType())
4186 NewFD->setInvalidDecl();
4187
4188 // Set the lexical context.
4189 NewFD->setLexicalDeclContext(CurContext);
4190 // Filter out previous declarations that don't match the scope.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004191 FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(),
Douglas Gregordb446112011-03-07 16:54:27 +00004192 /*ExplicitInstantiationOrSpecialization=*/false);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004193 } else {
4194 isFriend = D.getDeclSpec().isFriendSpecified();
Douglas Gregor513e63c2010-12-10 19:28:19 +00004195 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
4196 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
4197 bool isVirtualOkay = false;
Zhongxing Xubece5d62009-01-16 01:13:29 +00004198
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004199 // Check that the return type is not an abstract class type.
4200 // For record types, this is done by the AbstractClassUsageDiagnoser once
4201 // the class has been completely parsed.
4202 if (!DC->isRecord() &&
4203 RequireNonAbstractType(D.getIdentifierLoc(),
4204 R->getAs<FunctionType>()->getResultType(),
4205 diag::err_abstract_type_in_decl,
4206 AbstractReturnType))
4207 D.setInvalidType();
Mike Stump11289f42009-09-09 15:08:12 +00004208
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004209 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
4210 // This is a C++ constructor declaration.
4211 assert(DC->isRecord() &&
4212 "Constructors can only be declared in a member context");
4213
4214 R = CheckConstructorDeclarator(D, R, SC);
4215
4216 // Create the new declaration
Alexis Hunt5dafebc2011-05-06 01:42:00 +00004217 CXXConstructorDecl *NewCD = CXXConstructorDecl::Create(
4218 Context,
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004219 cast<CXXRecordDecl>(DC),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004220 D.getSourceRange().getBegin(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004221 NameInfo, R, TInfo,
4222 isExplicit, isInline,
Alexis Hunt58dad7d2011-05-06 00:11:07 +00004223 /*isImplicitlyDeclared=*/false);
Alexis Hunt5dafebc2011-05-06 01:42:00 +00004224
4225 NewFD = NewCD;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004226 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4227 // This is a C++ destructor declaration.
4228 if (DC->isRecord()) {
4229 R = CheckDestructorDeclarator(D, R, SC);
Sebastian Redl623ea822011-05-19 05:13:44 +00004230 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004231
Sebastian Redl623ea822011-05-19 05:13:44 +00004232 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004233 D.getSourceRange().getBegin(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004234 NameInfo, R, TInfo,
4235 isInline,
4236 /*isImplicitlyDeclared=*/false);
Sebastian Redl623ea822011-05-19 05:13:44 +00004237 NewFD = NewDD;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004238 isVirtualOkay = true;
Sebastian Redl623ea822011-05-19 05:13:44 +00004239
4240 // If the class is complete, then we now create the implicit exception
4241 // specification. If the class is incomplete or dependent, we can't do
4242 // it yet.
4243 if (getLangOptions().CPlusPlus0x && !Record->isDependentType() &&
4244 Record->getDefinition() && !Record->isBeingDefined() &&
4245 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
4246 AdjustDestructorExceptionSpec(Record, NewDD);
4247 }
4248
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004249 } else {
4250 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
4251
4252 // Create a FunctionDecl to satisfy the function definition parsing
4253 // code path.
Abramo Bagnaradff19302011-03-08 08:55:46 +00004254 NewFD = FunctionDecl::Create(Context, DC, D.getSourceRange().getBegin(),
4255 D.getIdentifierLoc(), Name, R, TInfo,
4256 SC, SCAsWritten, isInline,
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004257 /*hasPrototype=*/true);
4258 D.setInvalidType();
4259 }
4260 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
4261 if (!DC->isRecord()) {
4262 Diag(D.getIdentifierLoc(),
4263 diag::err_conv_function_not_member);
4264 return 0;
4265 }
4266
4267 CheckConversionDeclarator(D, R, SC);
4268 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004269 D.getSourceRange().getBegin(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004270 NameInfo, R, TInfo,
Douglas Gregorf2f08062011-03-08 17:10:18 +00004271 isInline, isExplicit,
4272 SourceLocation());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004273
4274 isVirtualOkay = true;
4275 } else if (DC->isRecord()) {
4276 // If the of the function is the same as the name of the record, then this
4277 // must be an invalid constructor that has a return type.
4278 // (The parser checks for a return type and makes the declarator a
4279 // constructor if it has no return type).
4280 // must have an invalid constructor that has a return type
4281 if (Name.getAsIdentifierInfo() &&
4282 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
4283 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
4284 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4285 << SourceRange(D.getIdentifierLoc());
4286 return 0;
4287 }
4288
4289 bool isStatic = SC == SC_Static;
Sebastian Redl37588092011-03-14 18:08:30 +00004290
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004291 // [class.free]p1:
4292 // Any allocation function for a class T is a static member
4293 // (even if not explicitly declared static).
4294 if (Name.getCXXOverloadedOperator() == OO_New ||
4295 Name.getCXXOverloadedOperator() == OO_Array_New)
4296 isStatic = true;
4297
4298 // [class.free]p6 Any deallocation function for a class X is a static member
4299 // (even if not explicitly declared static).
4300 if (Name.getCXXOverloadedOperator() == OO_Delete ||
4301 Name.getCXXOverloadedOperator() == OO_Array_Delete)
4302 isStatic = true;
Sebastian Redl37588092011-03-14 18:08:30 +00004303
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004304 // This is a C++ method declaration.
Alexis Hunt5dafebc2011-05-06 01:42:00 +00004305 CXXMethodDecl *NewMD = CXXMethodDecl::Create(
4306 Context, cast<CXXRecordDecl>(DC),
4307 D.getSourceRange().getBegin(),
4308 NameInfo, R, TInfo,
4309 isStatic, SCAsWritten, isInline,
4310 SourceLocation());
4311 NewFD = NewMD;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004312
4313 isVirtualOkay = !isStatic;
4314 } else {
4315 // Determine whether the function was written with a
4316 // prototype. This true when:
4317 // - we're in C++ (where every function has a prototype),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004318 NewFD = FunctionDecl::Create(Context, DC, D.getSourceRange().getBegin(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004319 NameInfo, R, TInfo, SC, SCAsWritten, isInline,
4320 true/*HasPrototype*/);
4321 }
Abramo Bagnaraa3088e62011-03-18 15:21:59 +00004322
4323 if (isFriend && !isInline && IsFunctionDefinition) {
4324 // C++ [class.friend]p5
4325 // A function can be defined in a friend declaration of a
4326 // class . . . . Such a function is implicitly inline.
4327 NewFD->setImplicitlyInline();
4328 }
4329
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004330 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004331 isExplicitSpecialization = false;
4332 isFunctionTemplateSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004333 if (D.isInvalidType())
4334 NewFD->setInvalidDecl();
4335
4336 // Set the lexical context. If the declarator has a C++
4337 // scope specifier, or is the object of a friend declaration, the
4338 // lexical context will be different from the semantic context.
4339 NewFD->setLexicalDeclContext(CurContext);
4340
4341 // Match up the template parameter lists with the scope specifier, then
4342 // determine whether we have a template or a template specialization.
4343 bool Invalid = false;
4344 if (TemplateParameterList *TemplateParams
Douglas Gregor93ded322011-03-04 22:45:55 +00004345 = MatchTemplateParametersToScopeSpecifier(
Douglas Gregord8d297c2009-07-21 23:53:31 +00004346 D.getDeclSpec().getSourceRange().getBegin(),
Douglas Gregor972fe532011-05-10 18:27:06 +00004347 D.getIdentifierLoc(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00004348 D.getCXXScopeSpec(),
John McCall2c2eb122010-10-16 06:59:13 +00004349 TemplateParamLists.get(),
4350 TemplateParamLists.size(),
4351 isFriend,
4352 isExplicitSpecialization,
4353 Invalid)) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00004354 if (TemplateParams->size() > 0) {
4355 // This is a function template
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00004356
Abramo Bagnara60804e12011-03-18 15:16:37 +00004357 // Check that we can declare a template here.
4358 if (CheckTemplateDeclScope(S, TemplateParams))
4359 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004360
Abramo Bagnara60804e12011-03-18 15:16:37 +00004361 // A destructor cannot be a template.
4362 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4363 Diag(NewFD->getLocation(), diag::err_destructor_template);
4364 return 0;
John McCall1f0479e2010-03-24 08:27:58 +00004365 }
4366
Abramo Bagnara60804e12011-03-18 15:16:37 +00004367 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
4368 NewFD->getLocation(),
4369 Name, TemplateParams,
4370 NewFD);
4371 FunctionTemplate->setLexicalDeclContext(CurContext);
4372 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
4373
4374 // For source fidelity, store the other template param lists.
4375 if (TemplateParamLists.size() > 1) {
4376 NewFD->setTemplateParameterListsInfo(Context,
4377 TemplateParamLists.size() - 1,
4378 TemplateParamLists.release());
4379 }
4380 } else {
4381 // This is a function template specialization.
4382 isFunctionTemplateSpecialization = true;
4383 // For source fidelity, store all the template param lists.
4384 NewFD->setTemplateParameterListsInfo(Context,
4385 TemplateParamLists.size(),
4386 TemplateParamLists.release());
4387
4388 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
4389 if (isFriend) {
4390 // We want to remove the "template<>", found here.
4391 SourceRange RemoveRange = TemplateParams->getSourceRange();
4392
4393 // If we remove the template<> and the name is not a
4394 // template-id, we're actually silently creating a problem:
4395 // the friend declaration will refer to an untemplated decl,
4396 // and clearly the user wants a template specialization. So
4397 // we need to insert '<>' after the name.
4398 SourceLocation InsertLoc;
4399 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
4400 InsertLoc = D.getName().getSourceRange().getEnd();
4401 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
4402 }
4403
4404 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
4405 << Name << RemoveRange
4406 << FixItHint::CreateRemoval(RemoveRange)
4407 << FixItHint::CreateInsertion(InsertLoc, "<>");
4408 }
4409 }
4410 }
4411 else {
4412 // All template param lists were matched against the scope specifier:
4413 // this is NOT (an explicit specialization of) a template.
4414 if (TemplateParamLists.size() > 0)
4415 // For source fidelity, store all the template param lists.
4416 NewFD->setTemplateParameterListsInfo(Context,
4417 TemplateParamLists.size(),
4418 TemplateParamLists.release());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004419 }
4420
4421 if (Invalid) {
4422 NewFD->setInvalidDecl();
4423 if (FunctionTemplate)
4424 FunctionTemplate->setInvalidDecl();
4425 }
4426
4427 // C++ [dcl.fct.spec]p5:
4428 // The virtual specifier shall only be used in declarations of
4429 // nonstatic class member functions that appear within a
4430 // member-specification of a class declaration; see 10.3.
4431 //
4432 if (isVirtual && !NewFD->isInvalidDecl()) {
4433 if (!isVirtualOkay) {
4434 Diag(D.getDeclSpec().getVirtualSpecLoc(),
4435 diag::err_virtual_non_function);
4436 } else if (!CurContext->isRecord()) {
4437 // 'virtual' was specified outside of the class.
Anders Carlssone9738992011-01-22 14:43:56 +00004438 Diag(D.getDeclSpec().getVirtualSpecLoc(),
4439 diag::err_virtual_out_of_class)
4440 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
4441 } else if (NewFD->getDescribedFunctionTemplate()) {
4442 // C++ [temp.mem]p3:
4443 // A member function template shall not be virtual.
4444 Diag(D.getDeclSpec().getVirtualSpecLoc(),
4445 diag::err_virtual_member_function_template)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004446 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
4447 } else {
4448 // Okay: Add virtual to the method.
4449 NewFD->setVirtualAsWritten(true);
John McCall816d75b2010-03-24 07:46:06 +00004450 }
Douglas Gregorc1da0f02009-06-24 00:23:40 +00004451 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00004452
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004453 // C++ [dcl.fct.spec]p3:
4454 // The inline specifier shall not appear on a block scope function declaration.
4455 if (isInline && !NewFD->isInvalidDecl()) {
4456 if (CurContext->isFunctionOrMethod()) {
4457 // 'inline' is not allowed on block scope function declaration.
4458 Diag(D.getDeclSpec().getInlineSpecLoc(),
4459 diag::err_inline_declaration_block_scope) << Name
4460 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
4461 }
4462 }
4463
4464 // C++ [dcl.fct.spec]p6:
4465 // The explicit specifier shall be used only in the declaration of a
4466 // constructor or conversion function within its class definition; see 12.3.1
4467 // and 12.3.2.
4468 if (isExplicit && !NewFD->isInvalidDecl()) {
4469 if (!CurContext->isRecord()) {
4470 // 'explicit' was specified outside of the class.
4471 Diag(D.getDeclSpec().getExplicitSpecLoc(),
4472 diag::err_explicit_out_of_class)
4473 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
4474 } else if (!isa<CXXConstructorDecl>(NewFD) &&
4475 !isa<CXXConversionDecl>(NewFD)) {
4476 // 'explicit' was specified on a function that wasn't a constructor
4477 // or conversion function.
4478 Diag(D.getDeclSpec().getExplicitSpecLoc(),
4479 diag::err_explicit_non_ctor_or_conv_function)
4480 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
4481 }
4482 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00004483
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004484 // Filter out previous declarations that don't match the scope.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004485 FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(),
Douglas Gregordb446112011-03-07 16:54:27 +00004486 isExplicitSpecialization ||
4487 isFunctionTemplateSpecialization);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004488
4489 if (isFriend) {
4490 // For now, claim that the objects have no previous declaration.
4491 if (FunctionTemplate) {
4492 FunctionTemplate->setObjectOfFriendDecl(false);
4493 FunctionTemplate->setAccess(AS_public);
4494 }
4495 NewFD->setObjectOfFriendDecl(false);
4496 NewFD->setAccess(AS_public);
4497 }
4498
John McCall357d0f32010-12-15 04:00:32 +00004499 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && IsFunctionDefinition) {
4500 // A method is implicitly inline if it's defined in its class
4501 // definition.
4502 NewFD->setImplicitlyInline();
4503 }
4504
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004505 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
4506 !CurContext->isRecord()) {
4507 // C++ [class.static]p1:
4508 // A data or function member of a class may be declared static
4509 // in a class definition, in which case it is a static member of
4510 // the class.
4511
4512 // Complain about the 'static' specifier if it's on an out-of-line
4513 // member function definition.
4514 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4515 diag::err_static_out_of_line)
4516 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4517 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00004518 }
4519
Zhongxing Xubece5d62009-01-16 01:13:29 +00004520 // Handle GNU asm-label extension (encoded as an attribute).
4521 if (Expr *E = (Expr*) D.getAsmLabel()) {
4522 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00004523 StringLiteral *SE = cast<StringLiteral>(E);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004524 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
4525 SE->getString()));
Zhongxing Xubece5d62009-01-16 01:13:29 +00004526 }
4527
Chris Lattner9af40c12009-04-25 06:12:16 +00004528 // Copy the parameter declarations from the declarator D to the function
4529 // declaration NewFD, if they are available. First scavenge them into Params.
4530 llvm::SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara6d810632010-12-14 22:11:44 +00004531 if (D.isFunctionDeclarator()) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004532 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xubece5d62009-01-16 01:13:29 +00004533
Zhongxing Xubece5d62009-01-16 01:13:29 +00004534 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
4535 // function that takes no arguments, not a function that takes a
4536 // single void argument.
4537 // We let through "const void" here because Sema::GetTypeForDeclarator
4538 // already checks for that case.
4539 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4540 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00004541 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
Chris Lattner9af40c12009-04-25 06:12:16 +00004542 // Empty arg list, don't push any params.
John McCall48871652010-08-21 09:40:31 +00004543 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[0].Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00004544
4545 // In C++, the empty parameter-type-list must be spelled "void"; a
4546 // typedef of void is not permitted.
4547 if (getLangOptions().CPlusPlus &&
Richard Smithdda56e42011-04-15 14:24:37 +00004548 Param->getType().getUnqualifiedType() != Context.VoidTy) {
4549 bool IsTypeAlias = false;
4550 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
4551 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00004552 else if (const TemplateSpecializationType *TST =
4553 Param->getType()->getAs<TemplateSpecializationType>())
4554 IsTypeAlias = TST->isTypeAlias();
Richard Smithdda56e42011-04-15 14:24:37 +00004555 Diag(Param->getLocation(), diag::err_param_typedef_of_void)
4556 << IsTypeAlias;
4557 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004558 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00004559 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +00004560 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00004561 assert(Param->getDeclContext() != NewFD && "Was set before ?");
4562 Param->setDeclContext(NewFD);
4563 Params.push_back(Param);
John McCallb7238602010-04-14 01:27:20 +00004564
4565 if (Param->isInvalidDecl())
4566 NewFD->setInvalidDecl();
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00004567 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004568 }
Mike Stump11289f42009-09-09 15:08:12 +00004569
John McCall9dd450b2009-09-21 23:43:11 +00004570 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner47c0d002009-04-25 06:03:53 +00004571 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xubece5d62009-01-16 01:13:29 +00004572 // following example, we'll need to synthesize (unnamed)
4573 // parameters for use in the declaration.
4574 //
4575 // @code
4576 // typedef void fn(int);
4577 // fn f;
4578 // @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004579
Chris Lattner47c0d002009-04-25 06:03:53 +00004580 // Synthesize a parameter for each argument type.
Chris Lattner47c0d002009-04-25 06:03:53 +00004581 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
4582 AE = FT->arg_type_end(); AI != AE; ++AI) {
John McCalla3ccba02010-06-04 11:21:44 +00004583 ParmVarDecl *Param =
4584 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
John McCall8fb0d9d2011-05-01 22:35:37 +00004585 Param->setScopeInfo(0, Params.size());
Chris Lattner47c0d002009-04-25 06:03:53 +00004586 Params.push_back(Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00004587 }
Chris Lattner49303b22009-04-25 18:38:18 +00004588 } else {
4589 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
4590 "Should not need args for typedef of non-prototype fn");
Zhongxing Xubece5d62009-01-16 01:13:29 +00004591 }
Chris Lattner9af40c12009-04-25 06:12:16 +00004592 // Finally, we know we have the right number of parameters, install them.
Douglas Gregord5058122010-02-11 01:19:42 +00004593 NewFD->setParams(Params.data(), Params.size());
Mike Stump11289f42009-09-09 15:08:12 +00004594
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004595 // Process the non-inheritable attributes on this declaration.
4596 ProcessDeclAttributes(S, NewFD, D,
4597 /*NonInheritable=*/true, /*Inheritable=*/false);
4598
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004599 if (!getLangOptions().CPlusPlus) {
4600 // Perform semantic checking on the function declaration.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00004601 bool isExplicitSpecialization=false;
4602 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization,
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004603 Redeclaration);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004604 assert((NewFD->isInvalidDecl() || !Redeclaration ||
4605 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
4606 "previous declaration set still overloaded");
4607 } else {
4608 // If the declarator is a template-id, translate the parser's template
4609 // argument list into our AST format.
4610 bool HasExplicitTemplateArgs = false;
4611 TemplateArgumentListInfo TemplateArgs;
4612 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4613 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4614 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4615 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
4616 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4617 TemplateId->getTemplateArgs(),
4618 TemplateId->NumArgs);
4619 translateTemplateArguments(TemplateArgsPtr,
4620 TemplateArgs);
4621 TemplateArgsPtr.release();
Douglas Gregor0e876e02009-09-25 23:53:26 +00004622
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004623 HasExplicitTemplateArgs = true;
Douglas Gregor0e876e02009-09-25 23:53:26 +00004624
Douglas Gregor522d5eb2011-06-06 15:22:55 +00004625 if (NewFD->isInvalidDecl()) {
4626 HasExplicitTemplateArgs = false;
4627 } else if (FunctionTemplate) {
Douglas Gregora5f6f9c2011-01-24 18:54:39 +00004628 // Function template with explicit template arguments.
4629 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
4630 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
4631
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004632 HasExplicitTemplateArgs = false;
4633 } else if (!isFunctionTemplateSpecialization &&
4634 !D.getDeclSpec().isFriendSpecified()) {
4635 // We have encountered something that the user meant to be a
4636 // specialization (because it has explicitly-specified template
4637 // arguments) but that was not introduced with a "template<>" (or had
4638 // too few of them).
4639 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
4640 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
4641 << FixItHint::CreateInsertion(
4642 D.getDeclSpec().getSourceRange().getBegin(),
4643 "template<> ");
4644 isFunctionTemplateSpecialization = true;
John McCallf7cfb222010-10-13 05:45:15 +00004645 } else {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004646 // "friend void foo<>(int);" is an implicit specialization decl.
4647 isFunctionTemplateSpecialization = true;
Francois Pichet6d76e6c2010-10-01 21:19:28 +00004648 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004649 } else if (isFriend && isFunctionTemplateSpecialization) {
4650 // This combination is only possible in a recovery case; the user
4651 // wrote something like:
4652 // template <> friend void foo(int);
4653 // which we're recovering from as if the user had written:
4654 // friend void foo<>(int);
4655 // Go ahead and fake up a template id.
4656 HasExplicitTemplateArgs = true;
4657 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
4658 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004659 }
John McCallf7cfb222010-10-13 05:45:15 +00004660
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004661 // If it's a friend (and only if it's a friend), it's possible
4662 // that either the specialized function type or the specialized
4663 // template is dependent, and therefore matching will fail. In
4664 // this case, don't check the specialization yet.
4665 if (isFunctionTemplateSpecialization && isFriend &&
4666 (NewFD->getType()->isDependentType() || DC->isDependentContext())) {
4667 assert(HasExplicitTemplateArgs &&
4668 "friend function specialization without template args");
4669 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
4670 Previous))
4671 NewFD->setInvalidDecl();
4672 } else if (isFunctionTemplateSpecialization) {
Douglas Gregor63fab342011-03-16 19:27:09 +00004673 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetb5037052011-06-03 13:59:45 +00004674 && !isFriend) {
Douglas Gregor63fab342011-03-16 19:27:09 +00004675 Diag(NewFD->getLocation(), diag::err_function_specialization_in_class)
4676 << NewFD->getDeclName();
4677 NewFD->setInvalidDecl();
4678 return 0;
4679 } else if (CheckFunctionTemplateSpecialization(NewFD,
4680 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
4681 Previous))
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004682 NewFD->setInvalidDecl();
Douglas Gregor781ba6e2011-05-21 18:53:30 +00004683
4684 // C++ [dcl.stc]p1:
4685 // A storage-class-specifier shall not be specified in an explicit
4686 // specialization (14.7.3)
4687 if (SC != SC_None) {
Douglas Gregor84265a02011-06-17 05:09:08 +00004688 if (SC != NewFD->getStorageClass())
4689 Diag(NewFD->getLocation(),
4690 diag::err_explicit_specialization_inconsistent_storage_class)
4691 << SC
4692 << FixItHint::CreateRemoval(
4693 D.getDeclSpec().getStorageClassSpecLoc());
4694
4695 else
4696 Diag(NewFD->getLocation(),
4697 diag::ext_explicit_specialization_storage_class)
4698 << FixItHint::CreateRemoval(
4699 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregor781ba6e2011-05-21 18:53:30 +00004700 }
4701
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004702 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
4703 if (CheckMemberSpecialization(NewFD, Previous))
4704 NewFD->setInvalidDecl();
4705 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004706
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004707 // Perform semantic checking on the function declaration.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004708 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization,
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004709 Redeclaration);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004710
4711 assert((NewFD->isInvalidDecl() || !Redeclaration ||
4712 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
4713 "previous declaration set still overloaded");
4714
4715 NamedDecl *PrincipalDecl = (FunctionTemplate
4716 ? cast<NamedDecl>(FunctionTemplate)
4717 : NewFD);
4718
4719 if (isFriend && Redeclaration) {
4720 AccessSpecifier Access = AS_public;
4721 if (!NewFD->isInvalidDecl())
4722 Access = NewFD->getPreviousDeclaration()->getAccess();
4723
4724 NewFD->setAccess(Access);
4725 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
4726
4727 PrincipalDecl->setObjectOfFriendDecl(true);
4728 }
4729
4730 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
4731 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4732 PrincipalDecl->setNonMemberOperator();
4733
4734 // If we have a function template, check the template parameter
4735 // list. This will check and merge default template arguments.
4736 if (FunctionTemplate) {
4737 FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration();
4738 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
4739 PrevTemplate? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregora99fb4c2011-02-04 04:20:44 +00004740 D.getDeclSpec().isFriendSpecified()
4741 ? (IsFunctionDefinition
4742 ? TPC_FriendFunctionTemplateDefinition
4743 : TPC_FriendFunctionTemplate)
4744 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor4d5c2972011-02-04 12:22:53 +00004745 DC && DC->isRecord() &&
4746 DC->isDependentContext())
Douglas Gregora99fb4c2011-02-04 04:20:44 +00004747 ? TPC_ClassTemplateMember
4748 : TPC_FunctionTemplate);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004749 }
4750
4751 if (NewFD->isInvalidDecl()) {
4752 // Ignore all the rest of this.
4753 } else if (!Redeclaration) {
4754 // Fake up an access specifier if it's supposed to be a class member.
4755 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
4756 NewFD->setAccess(AS_public);
4757
4758 // Qualified decls generally require a previous declaration.
4759 if (D.getCXXScopeSpec().isSet()) {
4760 // ...with the major exception of templated-scope or
4761 // dependent-scope friend declarations.
4762
4763 // TODO: we currently also suppress this check in dependent
4764 // contexts because (1) the parameter depth will be off when
4765 // matching friend templates and (2) we might actually be
4766 // selecting a friend based on a dependent factor. But there
4767 // are situations where these conditions don't apply and we
4768 // can actually do this check immediately.
4769 if (isFriend &&
Abramo Bagnara60804e12011-03-18 15:16:37 +00004770 (TemplateParamLists.size() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004771 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
4772 CurContext->isDependentContext())) {
4773 // ignore these
4774 } else {
4775 // The user tried to provide an out-of-line definition for a
4776 // function that is a member of a class or namespace, but there
4777 // was no such member function declared (C++ [class.mfct]p2,
4778 // C++ [namespace.memdef]p2). For example:
4779 //
4780 // class X {
4781 // void f() const;
4782 // };
4783 //
4784 // void X::f() { } // ill-formed
4785 //
4786 // Complain about this problem, and attempt to suggest close
4787 // matches (e.g., those that differ only in cv-qualifiers and
4788 // whether the parameter types are references).
4789 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
4790 << Name << DC << D.getCXXScopeSpec().getRange();
4791 NewFD->setInvalidDecl();
4792
4793 DiagnoseInvalidRedeclaration(*this, NewFD);
4794 }
4795
4796 // Unqualified local friend declarations are required to resolve
4797 // to something.
4798 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
4799 Diag(D.getIdentifierLoc(), diag::err_no_matching_local_friend);
4800 NewFD->setInvalidDecl();
4801 DiagnoseInvalidRedeclaration(*this, NewFD);
4802 }
4803
4804 } else if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
4805 !isFriend && !isFunctionTemplateSpecialization &&
Alexis Hunt5a7fa252011-05-12 06:15:49 +00004806 !isExplicitSpecialization) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004807 // An out-of-line member function declaration must also be a
4808 // definition (C++ [dcl.meaning]p1).
4809 // Note that this is not the case for explicit specializations of
4810 // function templates or member functions of class templates, per
4811 // C++ [temp.expl.spec]p2. We also allow these declarations as an extension
4812 // for compatibility with old SWIG code which likes to generate them.
4813 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
4814 << D.getCXXScopeSpec().getRange();
4815 }
4816 }
Alexis Hunt5a7fa252011-05-12 06:15:49 +00004817
4818
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004819 // Handle attributes. We need to have merged decls when handling attributes
4820 // (for example to check for conflicts, etc).
4821 // FIXME: This needs to happen before we merge declarations. Then,
4822 // let attribute merging cope with attribute conflicts.
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004823 ProcessDeclAttributes(S, NewFD, D,
4824 /*NonInheritable=*/false, /*Inheritable=*/true);
Ryan Flynne5dc8592009-07-25 22:29:44 +00004825
4826 // attributes declared post-definition are currently ignored
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004827 // FIXME: This should happen during attribute merging
John McCall1f82f242009-11-18 22:49:29 +00004828 if (Redeclaration && Previous.isSingleResult()) {
4829 const FunctionDecl *Def;
4830 FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004831 if (PrevFD && PrevFD->isDefined(Def) && D.hasAttributes()) {
Ryan Flynne5dc8592009-07-25 22:29:44 +00004832 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
4833 Diag(Def->getLocation(), diag::note_previous_definition);
4834 }
4835 }
4836
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004837 AddKnownFunctionAttributes(NewFD);
4838
Douglas Gregor72609052010-08-06 13:50:58 +00004839 if (NewFD->hasAttr<OverloadableAttr>() &&
4840 !NewFD->getType()->getAs<FunctionProtoType>()) {
4841 Diag(NewFD->getLocation(),
4842 diag::err_attribute_overloadable_no_prototype)
4843 << NewFD;
4844
4845 // Turn this into a variadic function with no parameters.
4846 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
John McCalldb40c7f2010-12-14 08:05:40 +00004847 FunctionProtoType::ExtProtoInfo EPI;
4848 EPI.Variadic = true;
4849 EPI.ExtInfo = FT->getExtInfo();
4850
4851 QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI);
Douglas Gregor72609052010-08-06 13:50:58 +00004852 NewFD->setType(R);
4853 }
4854
Eli Friedman570024a2010-08-05 06:57:20 +00004855 // If there's a #pragma GCC visibility in scope, and this isn't a class
4856 // member, set the visibility of this function.
4857 if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
4858 AddPushedVisibilityAttribute(NewFD);
4859
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004860 // If this is a locally-scoped extern C function, update the
4861 // map of such names.
Douglas Gregor16618f22009-09-12 00:17:51 +00004862 if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004863 && !NewFD->isInvalidDecl())
John McCall1f82f242009-11-18 22:49:29 +00004864 RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004865
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00004866 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraea947882011-03-08 16:41:52 +00004867 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00004868
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004869 if (getLangOptions().CPlusPlus) {
4870 if (FunctionTemplate) {
4871 if (NewFD->isInvalidDecl())
4872 FunctionTemplate->setInvalidDecl();
4873 return FunctionTemplate;
4874 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004875 }
Mike Stump11289f42009-09-09 15:08:12 +00004876
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004877 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004878
4879 if (getLangOptions().CUDA)
4880 if (IdentifierInfo *II = NewFD->getIdentifier())
4881 if (!NewFD->isInvalidDecl() &&
4882 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
4883 if (II->isStr("cudaConfigureCall")) {
4884 if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
4885 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
4886
4887 Context.setcudaConfigureCallDecl(NewFD);
4888 }
4889 }
4890
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004891 return NewFD;
4892}
4893
4894/// \brief Perform semantic checking of a new function declaration.
4895///
4896/// Performs semantic analysis of the new function declaration
4897/// NewFD. This routine performs all semantic checking that does not
4898/// require the actual declarator involved in the declaration, and is
4899/// used both for the declaration of functions as they are parsed
4900/// (called via ActOnDeclarator) and for the declaration of functions
4901/// that have been instantiated via C++ template instantiation (called
4902/// via InstantiateDecl).
4903///
Douglas Gregorcf915552009-10-13 16:30:37 +00004904/// \param IsExplicitSpecialiation whether this new function declaration is
4905/// an explicit specialization of the previous declaration.
4906///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004907/// This sets NewFD->isInvalidDecl() to true if there was an error.
John McCall84d87672009-12-10 09:41:52 +00004908void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall1f82f242009-11-18 22:49:29 +00004909 LookupResult &Previous,
Douglas Gregorcf915552009-10-13 16:30:37 +00004910 bool IsExplicitSpecialization,
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004911 bool &Redeclaration) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004912 // If NewFD is already known erroneous, don't do any of this checking.
John McCall12d53da2010-08-12 00:57:17 +00004913 if (NewFD->isInvalidDecl()) {
4914 // If this is a class member, mark the class invalid immediately.
4915 // This avoids some consistency errors later.
4916 if (isa<CXXMethodDecl>(NewFD))
4917 cast<CXXMethodDecl>(NewFD)->getParent()->setInvalidDecl();
4918
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004919 return;
John McCall12d53da2010-08-12 00:57:17 +00004920 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004921
Eli Friedman54135832009-05-16 12:15:55 +00004922 if (NewFD->getResultType()->isVariablyModifiedType()) {
4923 // Functions returning a variably modified type violate C99 6.7.5.2p2
4924 // because all functions have linkage.
4925 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
4926 return NewFD->setInvalidDecl();
4927 }
4928
Douglas Gregor16618f22009-09-12 00:17:51 +00004929 if (NewFD->isMain())
4930 CheckMain(NewFD);
John McCalld9baf6a2009-07-24 03:03:21 +00004931
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004932 // Check for a previous declaration of this name.
John McCall1f82f242009-11-18 22:49:29 +00004933 if (Previous.empty() && NewFD->isExternC()) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004934 // Since we did not find anything by this name and we're declaring
4935 // an extern "C" function, look for a non-visible extern "C"
4936 // declaration with the same name.
4937 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004938 = LocallyScopedExternalDecls.find(NewFD->getDeclName());
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004939 if (Pos != LocallyScopedExternalDecls.end())
John McCall1f82f242009-11-18 22:49:29 +00004940 Previous.addDecl(Pos->second);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004941 }
4942
Douglas Gregore62c0a42009-02-24 01:23:02 +00004943 // Merge or overload the declaration with an existing declaration of
4944 // the same name, if appropriate.
John McCall1f82f242009-11-18 22:49:29 +00004945 if (!Previous.empty()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00004946 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xubece5d62009-01-16 01:13:29 +00004947 // a declaration that requires merging. If it's an overload,
4948 // there's no more work to do here; we'll just add the new
4949 // function to the scope.
Douglas Gregor633b7372009-02-13 00:26:38 +00004950
John McCall1f82f242009-11-18 22:49:29 +00004951 NamedDecl *OldDecl = 0;
John McCalldaa3d6b2009-12-09 03:35:25 +00004952 if (!AllowOverloadingOfFunction(Previous, Context)) {
4953 Redeclaration = true;
4954 OldDecl = Previous.getFoundDecl();
4955 } else {
John McCalle9cccd82010-06-16 08:42:20 +00004956 switch (CheckOverload(S, NewFD, Previous, OldDecl,
4957 /*NewIsUsingDecl*/ false)) {
John McCalldaa3d6b2009-12-09 03:35:25 +00004958 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00004959 Redeclaration = true;
John McCalldaa3d6b2009-12-09 03:35:25 +00004960 break;
4961
4962 case Ovl_NonFunction:
4963 Redeclaration = true;
4964 break;
4965
4966 case Ovl_Overload:
4967 Redeclaration = false;
4968 break;
John McCall1f82f242009-11-18 22:49:29 +00004969 }
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004970
4971 if (!getLangOptions().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
4972 // If a function name is overloadable in C, then every function
4973 // with that name must be marked "overloadable".
4974 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
4975 << Redeclaration << NewFD;
4976 NamedDecl *OverloadedDecl = 0;
4977 if (Redeclaration)
4978 OverloadedDecl = OldDecl;
4979 else if (!Previous.empty())
4980 OverloadedDecl = Previous.getRepresentativeDecl();
4981 if (OverloadedDecl)
4982 Diag(OverloadedDecl->getLocation(),
4983 diag::note_attribute_overloadable_prev_overload);
4984 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
4985 Context));
4986 }
John McCall1f82f242009-11-18 22:49:29 +00004987 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004988
John McCall1f82f242009-11-18 22:49:29 +00004989 if (Redeclaration) {
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004990 // NewFD and OldDecl represent declarations that need to be
Mike Stump11289f42009-09-09 15:08:12 +00004991 // merged.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00004992 if (MergeFunctionDecl(NewFD, OldDecl))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004993 return NewFD->setInvalidDecl();
Zhongxing Xubece5d62009-01-16 01:13:29 +00004994
John McCall1f82f242009-11-18 22:49:29 +00004995 Previous.clear();
4996 Previous.addDecl(OldDecl);
4997
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004998 if (FunctionTemplateDecl *OldTemplateDecl
Douglas Gregorca027af2009-10-12 22:27:17 +00004999 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
Douglas Gregorcf915552009-10-13 16:30:37 +00005000 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
Douglas Gregorca027af2009-10-12 22:27:17 +00005001 FunctionTemplateDecl *NewTemplateDecl
5002 = NewFD->getDescribedFunctionTemplate();
5003 assert(NewTemplateDecl && "Template/non-template mismatch");
5004 if (CXXMethodDecl *Method
5005 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
5006 Method->setAccess(OldTemplateDecl->getAccess());
5007 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
5008 }
Douglas Gregorcf915552009-10-13 16:30:37 +00005009
5010 // If this is an explicit specialization of a member that is a function
5011 // template, mark it as a member specialization.
5012 if (IsExplicitSpecialization &&
5013 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
5014 NewTemplateDecl->setMemberSpecialization();
5015 assert(OldTemplateDecl->isMemberSpecialization());
5016 }
Douglas Gregorca027af2009-10-12 22:27:17 +00005017 } else {
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00005018 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
5019 NewFD->setAccess(OldDecl->getAccess());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005020 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00005021 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005022 }
Douglas Gregor8af63e42009-02-06 17:46:57 +00005023 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005024
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005025 // Semantic checking for this function declaration (in isolation).
5026 if (getLangOptions().CPlusPlus) {
5027 // C++-specific checks.
5028 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
5029 CheckConstructor(Constructor);
Anders Carlsson2a50e952009-11-15 22:49:34 +00005030 } else if (CXXDestructorDecl *Destructor =
5031 dyn_cast<CXXDestructorDecl>(NewFD)) {
5032 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005033 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson2a50e952009-11-15 22:49:34 +00005034
Douglas Gregor7454c562010-07-02 20:37:36 +00005035 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson2a50e952009-11-15 22:49:34 +00005036 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005037 if (!ClassType->isDependentType()) {
5038 DeclarationName Name
5039 = Context.DeclarationNames.getCXXDestructorName(
5040 Context.getCanonicalType(ClassType));
5041 if (NewFD->getDeclName() != Name) {
5042 Diag(NewFD->getLocation(), diag::err_destructor_name);
5043 return NewFD->setInvalidDecl();
5044 }
5045 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005046 } else if (CXXConversionDecl *Conversion
Douglas Gregor21920e372009-12-01 17:24:26 +00005047 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005048 ActOnConversionDeclarator(Conversion);
Douglas Gregor21920e372009-12-01 17:24:26 +00005049 }
5050
5051 // Find any virtual functions that this function overrides.
Douglas Gregor6be3de32009-12-01 17:35:23 +00005052 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
5053 if (!Method->isFunctionTemplateSpecialization() &&
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005054 !Method->getDescribedFunctionTemplate()) {
5055 if (AddOverriddenMethods(Method->getParent(), Method)) {
5056 // If the function was marked as "static", we have a problem.
5057 if (NewFD->getStorageClass() == SC_Static) {
5058 Diag(NewFD->getLocation(), diag::err_static_overrides_virtual)
5059 << NewFD->getDeclName();
5060 for (CXXMethodDecl::method_iterator
5061 Overridden = Method->begin_overridden_methods(),
5062 OverriddenEnd = Method->end_overridden_methods();
5063 Overridden != OverriddenEnd;
5064 ++Overridden) {
5065 Diag((*Overridden)->getLocation(),
5066 diag::note_overridden_virtual_function);
5067 }
5068 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005069 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005070 }
Douglas Gregor6be3de32009-12-01 17:35:23 +00005071 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005072
5073 // Extra checking for C++ overloaded operators (C++ [over.oper]).
5074 if (NewFD->isOverloadedOperator() &&
5075 CheckOverloadedOperatorDeclaration(NewFD))
5076 return NewFD->setInvalidDecl();
Alexis Huntc88db062010-01-13 09:01:02 +00005077
5078 // Extra checking for C++0x literal operators (C++0x [over.literal]).
5079 if (NewFD->getLiteralIdentifier() &&
5080 CheckLiteralOperatorDeclaration(NewFD))
5081 return NewFD->setInvalidDecl();
5082
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005083 // In C++, check default arguments now that we have merged decls. Unless
5084 // the lexical context is the class, because in this case this is done
5085 // during delayed parsing anyway.
5086 if (!CurContext->isRecord())
5087 CheckCXXDefaultArguments(NewFD);
Douglas Gregor9246b682010-12-21 19:47:46 +00005088
5089 // If this function declares a builtin function, check the type of this
5090 // declaration against the expected type for the builtin.
5091 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
5092 ASTContext::GetBuiltinTypeError Error;
5093 QualType T = Context.GetBuiltinType(BuiltinID, Error);
5094 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
5095 // The type of this function differs from the type of the builtin,
5096 // so forget about the builtin entirely.
5097 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
5098 }
5099 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005100 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005101}
5102
John McCalld9baf6a2009-07-24 03:03:21 +00005103void Sema::CheckMain(FunctionDecl* FD) {
John McCall02dee0a2009-07-25 04:36:53 +00005104 // C++ [basic.start.main]p3: A program that declares main to be inline
5105 // or static is ill-formed.
5106 // C99 6.7.4p4: In a hosted environment, the inline function specifier
5107 // shall not appear in a declaration of main.
5108 // static main is not an error under C99, but we should warn about it.
Douglas Gregor35b57532009-10-27 21:01:01 +00005109 bool isInline = FD->isInlineSpecified();
John McCall8e7d6562010-08-26 03:08:43 +00005110 bool isStatic = FD->getStorageClass() == SC_Static;
John McCall02dee0a2009-07-25 04:36:53 +00005111 if (isInline || isStatic) {
5112 unsigned diagID = diag::warn_unusual_main_decl;
5113 if (isInline || getLangOptions().CPlusPlus)
5114 diagID = diag::err_unusual_main_decl;
5115
5116 int which = isStatic + (isInline << 1) - 1;
5117 Diag(FD->getLocation(), diagID) << which;
5118 }
5119
5120 QualType T = FD->getType();
5121 assert(T->isFunctionType() && "function decl is not of function type");
John McCall9dd450b2009-09-21 23:43:11 +00005122 const FunctionType* FT = T->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00005123
John McCall02dee0a2009-07-25 04:36:53 +00005124 if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
Douglas Gregorf05c0952011-02-19 19:04:23 +00005125 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
John McCall02dee0a2009-07-25 04:36:53 +00005126 FD->setInvalidDecl(true);
5127 }
5128
5129 // Treat protoless main() as nullary.
5130 if (isa<FunctionNoProtoType>(FT)) return;
5131
5132 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
5133 unsigned nparams = FTP->getNumArgs();
5134 assert(FD->getNumParams() == nparams);
5135
John McCall0e21fcc2009-12-24 09:58:38 +00005136 bool HasExtraParameters = (nparams > 3);
5137
5138 // Darwin passes an undocumented fourth argument of type char**. If
5139 // other platforms start sprouting these, the logic below will start
5140 // getting shifty.
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00005141 if (nparams == 4 && Context.Target.getTriple().isOSDarwin())
John McCall0e21fcc2009-12-24 09:58:38 +00005142 HasExtraParameters = false;
5143
5144 if (HasExtraParameters) {
John McCall02dee0a2009-07-25 04:36:53 +00005145 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
5146 FD->setInvalidDecl(true);
5147 nparams = 3;
5148 }
5149
5150 // FIXME: a lot of the following diagnostics would be improved
5151 // if we had some location information about types.
5152
5153 QualType CharPP =
5154 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall0e21fcc2009-12-24 09:58:38 +00005155 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall02dee0a2009-07-25 04:36:53 +00005156
5157 for (unsigned i = 0; i < nparams; ++i) {
5158 QualType AT = FTP->getArgType(i);
5159
5160 bool mismatch = true;
5161
5162 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
5163 mismatch = false;
5164 else if (Expected[i] == CharPP) {
5165 // As an extension, the following forms are okay:
5166 // char const **
5167 // char const * const *
5168 // char * const *
5169
John McCall8ccfcb52009-09-24 19:53:00 +00005170 QualifierCollector qs;
John McCall02dee0a2009-07-25 04:36:53 +00005171 const PointerType* PT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005172 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
5173 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
John McCall02dee0a2009-07-25 04:36:53 +00005174 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
5175 qs.removeConst();
5176 mismatch = !qs.empty();
5177 }
5178 }
5179
5180 if (mismatch) {
5181 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
5182 // TODO: suggest replacing given type with expected type
5183 FD->setInvalidDecl(true);
5184 }
5185 }
5186
5187 if (nparams == 1 && !FD->isInvalidDecl()) {
5188 Diag(FD->getLocation(), diag::warn_main_one_arg);
5189 }
Douglas Gregorbff62032010-10-21 16:57:46 +00005190
5191 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
5192 Diag(FD->getLocation(), diag::err_main_template_decl);
5193 FD->setInvalidDecl();
5194 }
John McCalld9baf6a2009-07-24 03:03:21 +00005195}
5196
Eli Friedmand5a55bd2008-05-20 13:48:25 +00005197bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00005198 // FIXME: Need strict checking. In C89, we need to check for
5199 // any assignment, increment, decrement, function-calls, or
5200 // commas outside of a sizeof. In C99, it's the same list,
5201 // except that the aforementioned are allowed in unevaluated
5202 // expressions. Everything else falls under the
5203 // "may accept other forms of constant expressions" exception.
5204 // (We never end up here for C++, so the constant expression
5205 // rules there don't matter.)
John McCall8b0f4ff2010-08-02 21:13:48 +00005206 if (Init->isConstantInitializer(Context, false))
Eli Friedman7bfab362009-02-22 06:45:27 +00005207 return false;
Eli Friedman4f294cf2009-02-26 04:47:58 +00005208 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
5209 << Init->getSourceRange();
Eli Friedmand5a55bd2008-05-20 13:48:25 +00005210 return true;
Steve Naroff98f72032008-01-10 22:15:12 +00005211}
5212
Chandler Carruth33bf3e72011-03-27 09:46:56 +00005213namespace {
5214 // Visits an initialization expression to see if OrigDecl is evaluated in
5215 // its own initialization and throws a warning if it does.
5216 class SelfReferenceChecker
5217 : public EvaluatedExprVisitor<SelfReferenceChecker> {
5218 Sema &S;
5219 Decl *OrigDecl;
5220
5221 public:
5222 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
5223
5224 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
5225 S(S), OrigDecl(OrigDecl) { }
5226
5227 void VisitExpr(Expr *E) {
5228 if (isa<ObjCMessageExpr>(*E)) return;
5229 Inherited::VisitExpr(E);
5230 }
5231
5232 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
5233 CheckForSelfReference(E);
5234 Inherited::VisitImplicitCastExpr(E);
5235 }
5236
5237 void CheckForSelfReference(ImplicitCastExpr *E) {
5238 if (E->getCastKind() != CK_LValueToRValue) return;
5239 Expr* SubExpr = E->getSubExpr()->IgnoreParenImpCasts();
5240 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr);
5241 if (!DRE) return;
5242 Decl* ReferenceDecl = DRE->getDecl();
5243 if (OrigDecl != ReferenceDecl) return;
5244 LookupResult Result(S, DRE->getNameInfo(), Sema::LookupOrdinaryName,
5245 Sema::NotForRedeclaration);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005246 S.DiagRuntimeBehavior(SubExpr->getLocStart(), SubExpr,
5247 S.PDiag(diag::warn_uninit_self_reference_in_init)
5248 << Result.getLookupName()
5249 << OrigDecl->getLocation()
5250 << SubExpr->getSourceRange());
Chandler Carruth33bf3e72011-03-27 09:46:56 +00005251 }
5252 };
5253}
5254
Douglas Gregor5fb53972009-01-14 15:45:31 +00005255/// AddInitializerToDecl - Adds the initializer Init to the
5256/// declaration dcl. If DirectInit is true, this is C++ direct
5257/// initialization rather than copy initialization.
Richard Smith30482bc2011-02-20 03:19:35 +00005258void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
5259 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner8beb9de2007-10-19 20:10:30 +00005260 // If there is no declaration, there was an error parsing it. Just ignore
5261 // the initializer.
Richard Smith30482bc2011-02-20 03:19:35 +00005262 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner8beb9de2007-10-19 20:10:30 +00005263 return;
Mike Stump11289f42009-09-09 15:08:12 +00005264
Ted Kremenek37881932011-04-04 23:29:12 +00005265 // Check for self-references within variable initializers.
5266 if (VarDecl *vd = dyn_cast<VarDecl>(RealDecl)) {
5267 // Variables declared within a function/method body are handled
5268 // by a dataflow analysis.
5269 if (!vd->hasLocalStorage() && !vd->isStaticLocal())
5270 SelfReferenceChecker(*this, RealDecl).VisitExpr(Init);
5271 }
5272 else {
5273 SelfReferenceChecker(*this, RealDecl).VisitExpr(Init);
5274 }
Chandler Carruth33bf3e72011-03-27 09:46:56 +00005275
Douglas Gregor0c880302009-03-11 23:00:04 +00005276 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
5277 // With declarators parsed the way they are, the parser cannot
5278 // distinguish between a normal initializer and a pure-specifier.
5279 // Thus this grotesque test.
5280 IntegerLiteral *IL;
Douglas Gregor0c880302009-03-11 23:00:04 +00005281 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor21920e372009-12-01 17:24:26 +00005282 Context.getCanonicalType(IL->getType()) == Context.IntTy)
5283 CheckPureMethod(Method, Init->getSourceRange());
5284 else {
Douglas Gregor0c880302009-03-11 23:00:04 +00005285 Diag(Method->getLocation(), diag::err_member_function_initialization)
5286 << Method->getDeclName() << Init->getSourceRange();
5287 Method->setInvalidDecl();
5288 }
5289 return;
5290 }
5291
Steve Naroff437b4d82007-09-12 20:13:48 +00005292 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5293 if (!VDecl) {
Richard Smith4a4beec2011-06-12 11:43:46 +00005294 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
5295 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +00005296 RealDecl->setInvalidDecl();
5297 return;
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00005298 }
5299
Richard Smith30482bc2011-02-20 03:19:35 +00005300 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
5301 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith9647d3c2011-03-17 16:11:59 +00005302 TypeSourceInfo *DeducedType = 0;
5303 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith30482bc2011-02-20 03:19:35 +00005304 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
5305 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
5306 << Init->getSourceRange();
Richard Smith9647d3c2011-03-17 16:11:59 +00005307 if (!DeducedType) {
Richard Smith30482bc2011-02-20 03:19:35 +00005308 RealDecl->setInvalidDecl();
5309 return;
5310 }
Richard Smith9647d3c2011-03-17 16:11:59 +00005311 VDecl->setTypeSourceInfo(DeducedType);
5312 VDecl->setType(DeducedType->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00005313
John McCall31168b02011-06-15 23:02:42 +00005314 // In ARC, infer lifetime.
5315 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
5316 VDecl->setInvalidDecl();
5317
Richard Smith30482bc2011-02-20 03:19:35 +00005318 // If this is a redeclaration, check that the type we just deduced matches
5319 // the previously declared type.
5320 if (VarDecl *Old = VDecl->getPreviousDeclaration())
5321 MergeVarDeclTypes(VDecl, Old);
5322 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00005323
5324
Eli Friedmanc9827d12009-11-14 03:40:14 +00005325 // A definition must end up with a complete type, which means it must be
5326 // complete with the restriction that an array type might be completed by the
5327 // initializer; note that later code assumes this restriction.
5328 QualType BaseDeclType = VDecl->getType();
5329 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
5330 BaseDeclType = Array->getElementType();
5331 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
Eli Friedman337cd3a2009-04-13 21:28:54 +00005332 diag::err_typecheck_decl_incomplete_type)) {
5333 RealDecl->setInvalidDecl();
5334 return;
5335 }
5336
Douglas Gregorc99f1552009-12-03 18:33:45 +00005337 // The variable can not have an abstract class type.
5338 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5339 diag::err_abstract_type_in_decl,
5340 AbstractVariableType))
5341 VDecl->setInvalidDecl();
5342
Sebastian Redl5ca79842010-02-01 20:16:42 +00005343 const VarDecl *Def;
5344 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00005345 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor0760fa12009-03-10 23:43:53 +00005346 << VDecl->getDeclName();
5347 Diag(Def->getLocation(), diag::note_previous_definition);
5348 VDecl->setInvalidDecl();
5349 return;
5350 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00005351
Douglas Gregorf0f83692010-08-24 05:27:49 +00005352 const VarDecl* PrevInit = 0;
Douglas Gregor71f39c92010-12-16 01:31:22 +00005353 if (getLangOptions().CPlusPlus) {
5354 // C++ [class.static.data]p4
5355 // If a static data member is of const integral or const
5356 // enumeration type, its declaration in the class definition can
5357 // specify a constant-initializer which shall be an integral
5358 // constant expression (5.19). In that case, the member can appear
5359 // in integral constant expressions. The member shall still be
5360 // defined in a namespace scope if it is used in the program and the
5361 // namespace scope definition shall not contain an initializer.
5362 //
5363 // We already performed a redefinition check above, but for static
5364 // data members we also need to check whether there was an in-class
5365 // declaration with an initializer.
5366 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5367 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5368 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5369 return;
5370 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00005371
Douglas Gregor71f39c92010-12-16 01:31:22 +00005372 if (VDecl->hasLocalStorage())
5373 getCurFunction()->setHasBranchProtectedScope();
5374
5375 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
5376 VDecl->setInvalidDecl();
5377 return;
5378 }
5379 }
John McCalld4e1b762010-08-01 01:24:59 +00005380
Douglas Gregor85dabae2009-12-16 01:38:02 +00005381 // Capture the variable that is being initialized and the style of
5382 // initialization.
5383 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5384
5385 // FIXME: Poor source location information.
5386 InitializationKind Kind
5387 = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(),
5388 Init->getLocStart(),
5389 Init->getLocEnd())
5390 : InitializationKind::CreateCopy(VDecl->getLocation(),
5391 Init->getLocStart());
5392
Steve Naroff61091402007-09-12 14:07:44 +00005393 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +00005394 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +00005395 QualType DclT = VDecl->getType(), SavT = DclT;
John McCall1c9c3fd2010-10-15 04:57:14 +00005396 if (VDecl->isLocalVarDecl()) {
Daniel Dunbar0ca16602009-04-14 02:25:56 +00005397 if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
Steve Naroff437b4d82007-09-12 20:13:48 +00005398 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff08899ff2008-04-15 22:42:06 +00005399 VDecl->setInvalidDecl();
5400 } else if (!VDecl->isInvalidDecl()) {
Eli Friedman78275202009-12-19 08:11:05 +00005401 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
John McCalldadc5752010-08-24 06:29:42 +00005402 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00005403 MultiExprArg(*this, &Init, 1),
Eli Friedman463e5232009-12-22 02:10:53 +00005404 &DclT);
5405 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00005406 VDecl->setInvalidDecl();
Eli Friedman78275202009-12-19 08:11:05 +00005407 return;
5408 }
Mike Stump11289f42009-09-09 15:08:12 +00005409
Eli Friedman463e5232009-12-22 02:10:53 +00005410 Init = Result.takeAs<Expr>();
5411
Anders Carlsson41e08812008-08-22 05:00:02 +00005412 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmance982572009-02-20 01:34:21 +00005413 // Don't check invalid declarations to avoid emitting useless diagnostics.
5414 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
John McCall8e7d6562010-08-26 03:08:43 +00005415 if (VDecl->getStorageClass() == SC_Static) // C99 6.7.8p4.
Anders Carlsson41e08812008-08-22 05:00:02 +00005416 CheckForConstantInitializer(Init, DclT);
5417 }
Steve Naroff61091402007-09-12 14:07:44 +00005418 }
Mike Stump11289f42009-09-09 15:08:12 +00005419 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor0c880302009-03-11 23:00:04 +00005420 VDecl->getLexicalDeclContext()->isRecord()) {
5421 // This is an in-class initialization for a static data member, e.g.,
5422 //
5423 // struct S {
5424 // static const int value = 17;
5425 // };
5426
John McCalldb768922010-09-10 23:21:22 +00005427 // Try to perform the initialization regardless.
5428 if (!VDecl->isInvalidDecl()) {
5429 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
5430 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
5431 MultiExprArg(*this, &Init, 1),
5432 &DclT);
5433 if (Result.isInvalid()) {
5434 VDecl->setInvalidDecl();
5435 return;
5436 }
5437
5438 Init = Result.takeAs<Expr>();
5439 }
Douglas Gregor0c880302009-03-11 23:00:04 +00005440
5441 // C++ [class.mem]p4:
5442 // A member-declarator can contain a constant-initializer only
5443 // if it declares a static member (9.4) of const integral or
5444 // const enumeration type, see 9.4.2.
5445 QualType T = VDecl->getType();
John McCalldb768922010-09-10 23:21:22 +00005446
5447 // Do nothing on dependent types.
5448 if (T->isDependentType()) {
5449
5450 // Require constness.
5451 } else if (!T.isConstQualified()) {
5452 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
5453 << Init->getSourceRange();
Douglas Gregor0c880302009-03-11 23:00:04 +00005454 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00005455
5456 // We allow integer constant expressions in all cases.
5457 } else if (T->isIntegralOrEnumerationType()) {
Chris Lattner9925ec82011-06-14 05:46:29 +00005458 // Check whether the expression is a constant expression.
5459 SourceLocation Loc;
5460 if (Init->isValueDependent())
5461 ; // Nothing to check.
5462 else if (Init->isIntegerConstantExpr(Context, &Loc))
5463 ; // Ok, it's an ICE!
5464 else if (Init->isEvaluatable(Context)) {
5465 // If we can constant fold the initializer through heroics, accept it,
5466 // but report this as a use of an extension for -pedantic.
5467 Diag(Loc, diag::ext_in_class_initializer_non_constant)
5468 << Init->getSourceRange();
5469 } else {
5470 // Otherwise, this is some crazy unknown case. Report the issue at the
5471 // location provided by the isIntegerConstantExpr failed check.
5472 Diag(Loc, diag::err_in_class_initializer_non_constant)
5473 << Init->getSourceRange();
5474 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00005475 }
5476
5477 // We allow floating-point constants as an extension in C++03, and
5478 // C++0x has far more complicated rules that we don't really
5479 // implement fully.
5480 } else {
5481 bool Allowed = false;
5482 if (getLangOptions().CPlusPlus0x) {
5483 Allowed = T->isLiteralType();
5484 } else if (T->isFloatingType()) { // also permits complex, which is ok
5485 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
5486 << T << Init->getSourceRange();
5487 Allowed = true;
5488 }
5489
5490 if (!Allowed) {
5491 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
5492 << T << Init->getSourceRange();
5493 VDecl->setInvalidDecl();
5494
5495 // TODO: there are probably expressions that pass here that shouldn't.
5496 } else if (!Init->isValueDependent() &&
5497 !Init->isConstantInitializer(Context, false)) {
5498 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
5499 << Init->getSourceRange();
5500 VDecl->setInvalidDecl();
Douglas Gregor0c880302009-03-11 23:00:04 +00005501 }
5502 }
Steve Naroff08899ff2008-04-15 22:42:06 +00005503 } else if (VDecl->isFileVarDecl()) {
Douglas Gregord4e1fb52010-10-15 01:21:46 +00005504 if (VDecl->getStorageClassAsWritten() == SC_Extern &&
Douglas Gregorfceea362010-04-22 14:36:26 +00005505 (!getLangOptions().CPlusPlus ||
5506 !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
Steve Naroff437b4d82007-09-12 20:13:48 +00005507 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedman463e5232009-12-22 02:10:53 +00005508 if (!VDecl->isInvalidDecl()) {
5509 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
John McCalldadc5752010-08-24 06:29:42 +00005510 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00005511 MultiExprArg(*this, &Init, 1),
Eli Friedman463e5232009-12-22 02:10:53 +00005512 &DclT);
5513 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00005514 VDecl->setInvalidDecl();
Eli Friedman463e5232009-12-22 02:10:53 +00005515 return;
5516 }
5517
5518 Init = Result.takeAs<Expr>();
5519 }
Mike Stump11289f42009-09-09 15:08:12 +00005520
Anders Carlsson41e08812008-08-22 05:00:02 +00005521 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmance982572009-02-20 01:34:21 +00005522 // Don't check invalid declarations to avoid emitting useless diagnostics.
5523 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
Anders Carlsson41e08812008-08-22 05:00:02 +00005524 // C99 6.7.8p4. All file scoped initializers need to be constant.
5525 CheckForConstantInitializer(Init, DclT);
5526 }
Steve Naroff61091402007-09-12 14:07:44 +00005527 }
5528 // If the type changed, it means we had an incomplete type that was
Mike Stump11289f42009-09-09 15:08:12 +00005529 // completed by the initializer. For example:
Steve Naroff61091402007-09-12 14:07:44 +00005530 // int ary[] = { 1, 3, 5 };
5531 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb2ed9afd2007-11-29 19:09:19 +00005532 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff437b4d82007-09-12 20:13:48 +00005533 VDecl->setType(DclT);
Christopher Lamb2ed9afd2007-11-29 19:09:19 +00005534 Init->setType(DclT);
5535 }
Mike Stump11289f42009-09-09 15:08:12 +00005536
Chris Lattner88fdea82010-10-10 18:16:20 +00005537
5538 // If this variable is a local declaration with record type, make sure it
5539 // doesn't have a flexible member initialization. We only support this as a
5540 // global/static definition.
5541 if (VDecl->hasLocalStorage())
5542 if (const RecordType *RT = VDecl->getType()->getAs<RecordType>())
Douglas Gregor1f81ced2010-10-15 23:53:28 +00005543 if (RT->getDecl()->hasFlexibleArrayMember()) {
5544 // Check whether the initializer tries to initialize the flexible
5545 // array member itself to anything other than an empty initializer list.
5546 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5547 unsigned Index = std::distance(RT->getDecl()->field_begin(),
5548 RT->getDecl()->field_end()) - 1;
5549 if (Index < ILE->getNumInits() &&
5550 !(isa<InitListExpr>(ILE->getInit(Index)) &&
5551 cast<InitListExpr>(ILE->getInit(Index))->getNumInits() == 0)) {
5552 Diag(VDecl->getLocation(), diag::err_nonstatic_flexible_variable);
5553 VDecl->setInvalidDecl();
5554 }
5555 }
Chris Lattner88fdea82010-10-10 18:16:20 +00005556 }
5557
John McCallacf0ee52010-10-08 02:01:28 +00005558 // Check any implicit conversions within the expression.
5559 CheckImplicitConversions(Init, VDecl->getLocation());
John McCall31168b02011-06-15 23:02:42 +00005560
5561 if (!VDecl->isInvalidDecl())
5562 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
5563
John McCall5d413782010-12-06 08:20:24 +00005564 Init = MaybeCreateExprWithCleanups(Init);
Steve Naroff61091402007-09-12 14:07:44 +00005565 // Attach the initializer to the decl.
Douglas Gregord5058122010-02-11 01:19:42 +00005566 VDecl->setInit(Init);
Douglas Gregorbeecd582009-04-21 17:11:58 +00005567
John McCall8b7fd8f12011-01-19 11:48:09 +00005568 CheckCompleteVariableDeclaration(VDecl);
Steve Naroff61091402007-09-12 14:07:44 +00005569}
5570
John McCalleae5acb2010-03-31 02:13:20 +00005571/// ActOnInitializerError - Given that there was an error parsing an
5572/// initializer for the given declaration, try to return to some form
5573/// of sanity.
John McCall48871652010-08-21 09:40:31 +00005574void Sema::ActOnInitializerError(Decl *D) {
John McCalleae5acb2010-03-31 02:13:20 +00005575 // Our main concern here is re-establishing invariants like "a
5576 // variable's type is either dependent or complete".
John McCalleae5acb2010-03-31 02:13:20 +00005577 if (!D || D->isInvalidDecl()) return;
5578
5579 VarDecl *VD = dyn_cast<VarDecl>(D);
5580 if (!VD) return;
5581
Richard Smith30482bc2011-02-20 03:19:35 +00005582 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smithb2bc2e62011-02-21 20:05:19 +00005583 if (ParsingInitForAutoVars.count(D)) {
5584 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00005585 return;
5586 }
5587
John McCalleae5acb2010-03-31 02:13:20 +00005588 QualType Ty = VD->getType();
5589 if (Ty->isDependentType()) return;
5590
5591 // Require a complete type.
5592 if (RequireCompleteType(VD->getLocation(),
5593 Context.getBaseElementType(Ty),
5594 diag::err_typecheck_decl_incomplete_type)) {
5595 VD->setInvalidDecl();
5596 return;
5597 }
5598
5599 // Require an abstract type.
5600 if (RequireNonAbstractType(VD->getLocation(), Ty,
5601 diag::err_abstract_type_in_decl,
5602 AbstractVariableType)) {
5603 VD->setInvalidDecl();
5604 return;
5605 }
5606
5607 // Don't bother complaining about constructors or destructors,
5608 // though.
5609}
5610
John McCall48871652010-08-21 09:40:31 +00005611void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith30482bc2011-02-20 03:19:35 +00005612 bool TypeMayContainAuto) {
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00005613 // If there is no declaration, there was an error parsing it. Just ignore it.
5614 if (RealDecl == 0)
5615 return;
5616
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005617 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
5618 QualType Type = Var->getType();
Douglas Gregorbeecd582009-04-21 17:11:58 +00005619
Anders Carlssonae019932009-07-11 00:34:39 +00005620 // C++0x [dcl.spec.auto]p3
Richard Smith30482bc2011-02-20 03:19:35 +00005621 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlssonae019932009-07-11 00:34:39 +00005622 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
5623 << Var->getDeclName() << Type;
5624 Var->setInvalidDecl();
5625 return;
5626 }
Mike Stump11289f42009-09-09 15:08:12 +00005627
Douglas Gregore6565622010-02-09 07:26:29 +00005628 switch (Var->isThisDeclarationADefinition()) {
5629 case VarDecl::Definition:
5630 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
5631 break;
5632
5633 // We have an out-of-line definition of a static data member
5634 // that has an in-class initializer, so we type-check this like
5635 // a declaration.
5636 //
5637 // Fall through
5638
5639 case VarDecl::DeclarationOnly:
5640 // It's only a declaration.
5641
5642 // Block scope. C99 6.7p7: If an identifier for an object is
5643 // declared with no linkage (C99 6.2.2p6), the type for the
5644 // object shall be complete.
John McCall1c9c3fd2010-10-15 04:57:14 +00005645 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Douglas Gregore6565622010-02-09 07:26:29 +00005646 !Var->getLinkage() && !Var->isInvalidDecl() &&
5647 RequireCompleteType(Var->getLocation(), Type,
5648 diag::err_typecheck_decl_incomplete_type))
5649 Var->setInvalidDecl();
5650
5651 // Make sure that the type is not abstract.
5652 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
5653 RequireNonAbstractType(Var->getLocation(), Type,
5654 diag::err_abstract_type_in_decl,
5655 AbstractVariableType))
5656 Var->setInvalidDecl();
5657 return;
5658
5659 case VarDecl::TentativeDefinition:
5660 // File scope. C99 6.9.2p2: A declaration of an identifier for an
5661 // object that has file scope without an initializer, and without a
5662 // storage-class specifier or with the storage-class specifier "static",
5663 // constitutes a tentative definition. Note: A tentative definition with
5664 // external linkage is valid (C99 6.2.2p5).
5665 if (!Var->isInvalidDecl()) {
5666 if (const IncompleteArrayType *ArrayT
5667 = Context.getAsIncompleteArrayType(Type)) {
5668 if (RequireCompleteType(Var->getLocation(),
5669 ArrayT->getElementType(),
5670 diag::err_illegal_decl_array_incomplete_type))
5671 Var->setInvalidDecl();
John McCall8e7d6562010-08-26 03:08:43 +00005672 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregore6565622010-02-09 07:26:29 +00005673 // C99 6.9.2p3: If the declaration of an identifier for an object is
5674 // a tentative definition and has internal linkage (C99 6.2.2p3), the
5675 // declared type shall not be an incomplete type.
5676 // NOTE: code such as the following
5677 // static struct s;
5678 // struct s { int a; };
5679 // is accepted by gcc. Hence here we issue a warning instead of
5680 // an error and we do not invalidate the static declaration.
5681 // NOTE: to avoid multiple warnings, only check the first declaration.
5682 if (Var->getPreviousDeclaration() == 0)
5683 RequireCompleteType(Var->getLocation(), Type,
5684 diag::ext_typecheck_decl_incomplete_type);
5685 }
5686 }
5687
5688 // Record the tentative definition; we're done.
5689 if (!Var->isInvalidDecl())
5690 TentativeDefinitions.push_back(Var);
5691 return;
5692 }
5693
5694 // Provide a specific diagnostic for uninitialized variable
5695 // definitions with incomplete array type.
5696 if (Type->isIncompleteArrayType()) {
Sebastian Redl10600672009-11-05 19:47:47 +00005697 Diag(Var->getLocation(),
5698 diag::err_typecheck_incomplete_array_needs_initializer);
5699 Var->setInvalidDecl();
5700 return;
5701 }
5702
John McCalla755f0f2010-08-01 01:25:24 +00005703 // Provide a specific diagnostic for uninitialized variable
5704 // definitions with reference type.
5705 if (Type->isReferenceType()) {
5706 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
5707 << Var->getDeclName()
5708 << SourceRange(Var->getLocation(), Var->getLocation());
5709 Var->setInvalidDecl();
5710 return;
5711 }
Douglas Gregore6565622010-02-09 07:26:29 +00005712
5713 // Do not attempt to type-check the default initializer for a
5714 // variable with dependent type.
5715 if (Type->isDependentType())
Douglas Gregor86d142a2009-10-08 07:24:58 +00005716 return;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005717
Douglas Gregore6565622010-02-09 07:26:29 +00005718 if (Var->isInvalidDecl())
5719 return;
Douglas Gregorc99f1552009-12-03 18:33:45 +00005720
Douglas Gregore6565622010-02-09 07:26:29 +00005721 if (RequireCompleteType(Var->getLocation(),
5722 Context.getBaseElementType(Type),
5723 diag::err_typecheck_decl_incomplete_type)) {
5724 Var->setInvalidDecl();
5725 return;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00005726 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005727
Douglas Gregore6565622010-02-09 07:26:29 +00005728 // The variable can not have an abstract class type.
5729 if (RequireNonAbstractType(Var->getLocation(), Type,
5730 diag::err_abstract_type_in_decl,
5731 AbstractVariableType)) {
5732 Var->setInvalidDecl();
5733 return;
5734 }
5735
Douglas Gregor9574af62011-05-21 17:52:48 +00005736 // Check for jumps past the implicit initializer. C++0x
5737 // clarifies that this applies to a "variable with automatic
5738 // storage duration", not a "local variable".
5739 // C++0x [stmt.dcl]p3
5740 // A program that jumps from a point where a variable with automatic
5741 // storage duration is not in scope to a point where it is in scope is
5742 // ill-formed unless the variable has scalar type, class type with a
5743 // trivial default constructor and a trivial destructor, a cv-qualified
5744 // version of one of these types, or an array of one of the preceding
5745 // types and is declared without an initializer.
5746 if (getLangOptions().CPlusPlus && Var->hasLocalStorage()) {
5747 if (const RecordType *Record
5748 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Alexis Hunt466627c2011-05-11 22:50:12 +00005749 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor9574af62011-05-21 17:52:48 +00005750 if ((!getLangOptions().CPlusPlus0x && !CXXRecord->isPOD()) ||
5751 (getLangOptions().CPlusPlus0x &&
5752 (!CXXRecord->hasTrivialDefaultConstructor() ||
Douglas Gregor22ae6962011-05-27 21:28:00 +00005753 !CXXRecord->hasTrivialDestructor())))
Alexis Hunt466627c2011-05-11 22:50:12 +00005754 getCurFunction()->setHasBranchProtectedScope();
5755 }
Douglas Gregore6565622010-02-09 07:26:29 +00005756 }
Douglas Gregor9574af62011-05-21 17:52:48 +00005757
5758 // C++03 [dcl.init]p9:
5759 // If no initializer is specified for an object, and the
5760 // object is of (possibly cv-qualified) non-POD class type (or
5761 // array thereof), the object shall be default-initialized; if
5762 // the object is of const-qualified type, the underlying class
5763 // type shall have a user-declared default
5764 // constructor. Otherwise, if no initializer is specified for
5765 // a non- static object, the object and its subobjects, if
5766 // any, have an indeterminate initial value); if the object
5767 // or any of its subobjects are of const-qualified type, the
5768 // program is ill-formed.
5769 // C++0x [dcl.init]p11:
5770 // If no initializer is specified for an object, the object is
5771 // default-initialized; [...].
5772 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
5773 InitializationKind Kind
5774 = InitializationKind::CreateDefault(Var->getLocation());
5775
5776 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
5777 ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
5778 MultiExprArg(*this, 0, 0));
5779 if (Init.isInvalid())
5780 Var->setInvalidDecl();
5781 else if (Init.get())
5782 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Douglas Gregor589973b2010-03-08 02:45:10 +00005783
John McCall8b7fd8f12011-01-19 11:48:09 +00005784 CheckCompleteVariableDeclaration(Var);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005785 }
5786}
5787
Richard Smith02e85f32011-04-14 22:09:26 +00005788void Sema::ActOnCXXForRangeDecl(Decl *D) {
5789 VarDecl *VD = dyn_cast<VarDecl>(D);
5790 if (!VD) {
5791 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
5792 D->setInvalidDecl();
5793 return;
5794 }
5795
5796 VD->setCXXForRangeDecl(true);
5797
5798 // for-range-declaration cannot be given a storage class specifier.
5799 int Error = -1;
5800 switch (VD->getStorageClassAsWritten()) {
5801 case SC_None:
5802 break;
5803 case SC_Extern:
5804 Error = 0;
5805 break;
5806 case SC_Static:
5807 Error = 1;
5808 break;
5809 case SC_PrivateExtern:
5810 Error = 2;
5811 break;
5812 case SC_Auto:
5813 Error = 3;
5814 break;
5815 case SC_Register:
5816 Error = 4;
5817 break;
5818 }
5819 // FIXME: constexpr isn't allowed here.
5820 //if (DS.isConstexprSpecified())
5821 // Error = 5;
5822 if (Error != -1) {
5823 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
5824 << VD->getDeclName() << Error;
5825 D->setInvalidDecl();
5826 }
5827}
5828
John McCall8b7fd8f12011-01-19 11:48:09 +00005829void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
5830 if (var->isInvalidDecl()) return;
5831
John McCall31168b02011-06-15 23:02:42 +00005832 // In ARC, don't allow jumps past the implicit initialization of a
5833 // local retaining variable.
5834 if (getLangOptions().ObjCAutoRefCount &&
5835 var->hasLocalStorage()) {
5836 switch (var->getType().getObjCLifetime()) {
5837 case Qualifiers::OCL_None:
5838 case Qualifiers::OCL_ExplicitNone:
5839 case Qualifiers::OCL_Autoreleasing:
5840 break;
5841
5842 case Qualifiers::OCL_Weak:
5843 case Qualifiers::OCL_Strong:
5844 getCurFunction()->setHasBranchProtectedScope();
5845 break;
5846 }
5847 }
5848
John McCall8b7fd8f12011-01-19 11:48:09 +00005849 // All the following checks are C++ only.
5850 if (!getLangOptions().CPlusPlus) return;
5851
5852 QualType baseType = Context.getBaseElementType(var->getType());
5853 if (baseType->isDependentType()) return;
5854
5855 // __block variables might require us to capture a copy-initializer.
5856 if (var->hasAttr<BlocksAttr>()) {
5857 // It's currently invalid to ever have a __block variable with an
5858 // array type; should we diagnose that here?
5859
5860 // Regardless, we don't want to ignore array nesting when
5861 // constructing this copy.
5862 QualType type = var->getType();
5863
5864 if (type->isStructureOrClassType()) {
5865 SourceLocation poi = var->getLocation();
5866 Expr *varRef = new (Context) DeclRefExpr(var, type, VK_LValue, poi);
5867 ExprResult result =
5868 PerformCopyInitialization(
5869 InitializedEntity::InitializeBlock(poi, type, false),
5870 poi, Owned(varRef));
5871 if (!result.isInvalid()) {
5872 result = MaybeCreateExprWithCleanups(result);
5873 Expr *init = result.takeAs<Expr>();
5874 Context.setBlockVarCopyInits(var, init);
5875 }
5876 }
5877 }
5878
5879 // Check for global constructors.
5880 if (!var->getDeclContext()->isDependentContext() &&
5881 var->hasGlobalStorage() &&
5882 !var->isStaticLocal() &&
5883 var->getInit() &&
5884 !var->getInit()->isConstantInitializer(Context,
5885 baseType->isReferenceType()))
5886 Diag(var->getLocation(), diag::warn_global_constructor)
5887 << var->getInit()->getSourceRange();
5888
5889 // Require the destructor.
5890 if (const RecordType *recordType = baseType->getAs<RecordType>())
5891 FinalizeVarWithDestructor(var, recordType);
5892}
5893
Richard Smithb2bc2e62011-02-21 20:05:19 +00005894/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
5895/// any semantic actions necessary after any initializer has been attached.
5896void
5897Sema::FinalizeDeclaration(Decl *ThisDecl) {
5898 // Note that we are no longer parsing the initializer for this declaration.
5899 ParsingInitForAutoVars.erase(ThisDecl);
5900}
5901
John McCallba7bf592010-08-24 05:47:05 +00005902Sema::DeclGroupPtrTy
5903Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
5904 Decl **Group, unsigned NumDecls) {
Chris Lattner5bbb3c82009-03-29 16:50:03 +00005905 llvm::SmallVector<Decl*, 8> Decls;
Eli Friedman55b9ecb2009-05-29 01:49:24 +00005906
5907 if (DS.isTypeSpecOwned())
John McCallba7bf592010-08-24 05:47:05 +00005908 Decls.push_back(DS.getRepAsDecl());
Eli Friedman55b9ecb2009-05-29 01:49:24 +00005909
Richard Smith2abf6762011-02-23 00:37:57 +00005910 for (unsigned i = 0; i != NumDecls; ++i)
5911 if (Decl *D = Group[i])
5912 Decls.push_back(D);
5913
Chandler Carruth33bf3e72011-03-27 09:46:56 +00005914 return BuildDeclaratorGroup(Decls.data(), Decls.size(),
Richard Smith2abf6762011-02-23 00:37:57 +00005915 DS.getTypeSpecType() == DeclSpec::TST_auto);
5916}
5917
5918/// BuildDeclaratorGroup - convert a list of declarations into a declaration
5919/// group, performing any necessary semantic checking.
5920Sema::DeclGroupPtrTy
5921Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
5922 bool TypeMayContainAuto) {
Richard Smith30482bc2011-02-20 03:19:35 +00005923 // C++0x [dcl.spec.auto]p7:
5924 // If the type deduced for the template parameter U is not the same in each
5925 // deduction, the program is ill-formed.
5926 // FIXME: When initializer-list support is added, a distinction is needed
5927 // between the deduced type U and the deduced type which 'auto' stands for.
5928 // auto a = 0, b = { 1, 2, 3 };
5929 // is legal because the deduced type U is 'int' in both cases.
Richard Smith2abf6762011-02-23 00:37:57 +00005930 if (TypeMayContainAuto && NumDecls > 1) {
Richard Smith30482bc2011-02-20 03:19:35 +00005931 QualType Deduced;
5932 CanQualType DeducedCanon;
5933 VarDecl *DeducedDecl = 0;
5934 for (unsigned i = 0; i != NumDecls; ++i) {
5935 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
5936 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith2abf6762011-02-23 00:37:57 +00005937 // Don't reissue diagnostics when instantiating a template.
5938 if (AT && D->isInvalidDecl())
5939 break;
Richard Smith30482bc2011-02-20 03:19:35 +00005940 if (AT && AT->isDeduced()) {
5941 QualType U = AT->getDeducedType();
5942 CanQualType UCanon = Context.getCanonicalType(U);
5943 if (Deduced.isNull()) {
5944 Deduced = U;
5945 DeducedCanon = UCanon;
5946 DeducedDecl = D;
5947 } else if (DeducedCanon != UCanon) {
Richard Smith2abf6762011-02-23 00:37:57 +00005948 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
5949 diag::err_auto_different_deductions)
Richard Smith30482bc2011-02-20 03:19:35 +00005950 << Deduced << DeducedDecl->getDeclName()
5951 << U << D->getDeclName()
5952 << DeducedDecl->getInit()->getSourceRange()
5953 << D->getInit()->getSourceRange();
Richard Smith2abf6762011-02-23 00:37:57 +00005954 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00005955 break;
5956 }
5957 }
5958 }
5959 }
5960 }
5961
Richard Smith2abf6762011-02-23 00:37:57 +00005962 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls));
Chris Lattner776fac82007-06-09 00:53:06 +00005963}
Steve Naroff7e6f7c22007-08-28 03:03:08 +00005964
Chris Lattner5bbb3c82009-03-29 16:50:03 +00005965
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005966/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
5967/// to introduce parameters into function prototype scope.
John McCall48871652010-08-21 09:40:31 +00005968Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattnercf31de32008-06-26 06:49:43 +00005969 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorad590502008-12-15 23:53:10 +00005970
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005971 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
John McCall8e7d6562010-08-26 03:08:43 +00005972 VarDecl::StorageClass StorageClass = SC_None;
5973 VarDecl::StorageClass StorageClassAsWritten = SC_None;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00005974 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCall8e7d6562010-08-26 03:08:43 +00005975 StorageClass = SC_Register;
5976 StorageClassAsWritten = SC_Register;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00005977 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005978 Diag(DS.getStorageClassSpecLoc(),
5979 diag::err_invalid_storage_class_in_func_decl);
Chris Lattnercf31de32008-06-26 06:49:43 +00005980 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005981 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005982
5983 if (D.getDeclSpec().isThreadSpecified())
5984 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
5985
Eli Friedman574c7452009-04-07 19:37:57 +00005986 DiagnoseFunctionSpecifiers(D);
5987
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00005988 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00005989 QualType parmDeclType = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005990
Douglas Gregor27b4c162010-12-23 22:44:42 +00005991 if (getLangOptions().CPlusPlus) {
5992 // Check that there are no default arguments inside the type of this
5993 // parameter.
5994 CheckExtraCXXDefaultArguments(D);
Douglas Gregor27b4c162010-12-23 22:44:42 +00005995
5996 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
5997 if (D.getCXXScopeSpec().isSet()) {
5998 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
5999 << D.getCXXScopeSpec().getRange();
6000 D.getCXXScopeSpec().clear();
6001 }
Douglas Gregord6ab8742009-05-28 23:31:59 +00006002 }
6003
Alexis Hunta56cbcc2010-11-03 01:07:06 +00006004 // Ensure we have a valid name
6005 IdentifierInfo *II = 0;
6006 if (D.hasName()) {
6007 II = D.getIdentifier();
6008 if (!II) {
6009 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
6010 << GetNameForDeclarator(D).getName().getAsString();
6011 D.setInvalidType(true);
6012 }
6013 }
6014
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00006015 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnerd9773512009-01-21 02:38:50 +00006016 if (II) {
John McCall84f02672010-03-18 06:42:38 +00006017 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
6018 ForRedeclaration);
6019 LookupName(R, S);
6020 if (R.isSingleResult()) {
6021 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnerd9773512009-01-21 02:38:50 +00006022 if (PrevDecl->isTemplateParameter()) {
6023 // Maybe we will complain about the shadowed template parameter.
6024 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
6025 // Just pretend that we didn't see the previous declaration.
6026 PrevDecl = 0;
John McCall48871652010-08-21 09:40:31 +00006027 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerd9773512009-01-21 02:38:50 +00006028 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00006029 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006030
Chris Lattnerd9773512009-01-21 02:38:50 +00006031 // Recover by removing the name
6032 II = 0;
6033 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00006034 D.setInvalidType(true);
Chris Lattnerd9773512009-01-21 02:38:50 +00006035 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006036 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00006037 }
Steve Naroff773df5c2007-08-07 22:44:21 +00006038
John McCallf7b2fb52010-01-22 00:28:27 +00006039 // Temporarily put parameter variables in the translation unit, not
6040 // the enclosing context. This prevents them from accidentally
6041 // looking like class members in C++.
Douglas Gregor940bca72010-04-12 07:48:19 +00006042 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00006043 D.getSourceRange().getBegin(),
6044 D.getIdentifierLoc(), II,
6045 parmDeclType, TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00006046 StorageClass, StorageClassAsWritten);
Mike Stump11289f42009-09-09 15:08:12 +00006047
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006048 if (D.isInvalidType())
John McCall8fb0d9d2011-05-01 22:35:37 +00006049 New->setInvalidDecl();
6050
6051 assert(S->isFunctionPrototypeScope());
6052 assert(S->getFunctionPrototypeDepth() >= 1);
6053 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
6054 S->getNextFunctionPrototypeIndex());
Douglas Gregor940bca72010-04-12 07:48:19 +00006055
Douglas Gregor91f84212008-12-11 16:49:14 +00006056 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00006057 S->AddDecl(New);
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00006058 if (II)
Douglas Gregor91f84212008-12-11 16:49:14 +00006059 IdResolver.AddDecl(New);
Nate Begemand8c41562008-02-17 21:20:31 +00006060
Douglas Gregor758a8692009-06-17 21:51:59 +00006061 ProcessDeclAttributes(S, New, D);
Mike Stumpe9efa802009-04-30 00:19:40 +00006062
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006063 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00006064 Diag(New->getLocation(), diag::err_block_on_nonlocal);
6065 }
John McCall48871652010-08-21 09:40:31 +00006066 return New;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00006067}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +00006068
John McCalla3ccba02010-06-04 11:21:44 +00006069/// \brief Synthesizes a variable for a parameter arising from a
6070/// typedef.
6071ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
6072 SourceLocation Loc,
6073 QualType T) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00006074 /* FIXME: setting StartLoc == Loc.
6075 Would it be worth to modify callers so as to provide proper source
6076 location for the unnamed parameters, embedding the parameter's type? */
6077 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCalla3ccba02010-06-04 11:21:44 +00006078 T, Context.getTrivialTypeSourceInfo(T, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00006079 SC_None, SC_None, 0);
John McCalla3ccba02010-06-04 11:21:44 +00006080 Param->setImplicit();
6081 return Param;
6082}
6083
John McCallc5990642010-08-24 09:05:15 +00006084void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
6085 ParmVarDecl * const *ParamEnd) {
John McCallc5990642010-08-24 09:05:15 +00006086 // Don't diagnose unused-parameter errors in template instantiations; we
6087 // will already have done so in the template itself.
6088 if (!ActiveTemplateInstantiations.empty())
6089 return;
6090
6091 for (; Param != ParamEnd; ++Param) {
6092 if (!(*Param)->isUsed() && (*Param)->getDeclName() &&
6093 !(*Param)->hasAttr<UnusedAttr>()) {
6094 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
6095 << (*Param)->getDeclName();
6096 }
6097 }
6098}
6099
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006100void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
6101 ParmVarDecl * const *ParamEnd,
6102 QualType ReturnTy,
6103 NamedDecl *D) {
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00006104 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006105 return;
6106
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00006107 // Warn if the return value is pass-by-value and larger than the specified
6108 // threshold.
John McCall31168b02011-06-15 23:02:42 +00006109 if (ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006110 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00006111 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006112 Diag(D->getLocation(), diag::warn_return_value_size)
6113 << D->getDeclName() << Size;
6114 }
6115
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00006116 // Warn if any parameter is pass-by-value and larger than the specified
6117 // threshold.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006118 for (; Param != ParamEnd; ++Param) {
6119 QualType T = (*Param)->getType();
John McCall31168b02011-06-15 23:02:42 +00006120 if (!T.isPODType(Context))
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006121 continue;
6122 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00006123 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006124 Diag((*Param)->getLocation(), diag::warn_parameter_size)
6125 << (*Param)->getDeclName() << Size;
6126 }
6127}
6128
Abramo Bagnaradff19302011-03-08 08:55:46 +00006129ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
6130 SourceLocation NameLoc, IdentifierInfo *Name,
6131 QualType T, TypeSourceInfo *TSInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00006132 VarDecl::StorageClass StorageClass,
6133 VarDecl::StorageClass StorageClassAsWritten) {
John McCall31168b02011-06-15 23:02:42 +00006134 // In ARC, infer a lifetime qualifier for appropriate parameter types.
6135 if (getLangOptions().ObjCAutoRefCount &&
6136 T.getObjCLifetime() == Qualifiers::OCL_None &&
6137 T->isObjCLifetimeType()) {
6138
6139 Qualifiers::ObjCLifetime lifetime;
6140
6141 // Special cases for arrays:
6142 // - if it's const, use __unsafe_unretained
6143 // - otherwise, it's an error
6144 if (T->isArrayType()) {
6145 if (!T.isConstQualified()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00006146 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
John McCall31168b02011-06-15 23:02:42 +00006147 << TSInfo->getTypeLoc().getSourceRange();
6148 }
6149 lifetime = Qualifiers::OCL_ExplicitNone;
6150 } else {
6151 lifetime = T->getObjCARCImplicitLifetime();
6152 }
6153 T = Context.getLifetimeQualifiedType(T, lifetime);
6154 }
6155
Abramo Bagnaradff19302011-03-08 08:55:46 +00006156 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
6157 adjustParameterType(T), TSInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00006158 StorageClass, StorageClassAsWritten,
6159 0);
Douglas Gregor940bca72010-04-12 07:48:19 +00006160
6161 // Parameters can not be abstract class types.
6162 // For record types, this is done by the AbstractClassUsageDiagnoser once
6163 // the class has been completely parsed.
6164 if (!CurContext->isRecord() &&
6165 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
6166 AbstractParamType))
6167 New->setInvalidDecl();
6168
6169 // Parameter declarators cannot be interface types. All ObjC objects are
6170 // passed by reference.
John McCall8b07ec22010-05-15 11:32:37 +00006171 if (T->isObjCObjectType()) {
Douglas Gregor940bca72010-04-12 07:48:19 +00006172 Diag(NameLoc,
6173 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
6174 New->setInvalidDecl();
6175 }
6176
6177 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
6178 // duration shall not be qualified by an address-space qualifier."
6179 // Since all parameters have automatic store duration, they can not have
6180 // an address space.
6181 if (T.getAddressSpace() != 0) {
6182 Diag(NameLoc, diag::err_arg_with_address_space);
6183 New->setInvalidDecl();
6184 }
6185
6186 return New;
6187}
6188
Douglas Gregor170512f2009-04-01 23:51:29 +00006189void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
6190 SourceLocation LocAfterDecls) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006191 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006192
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00006193 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
6194 // for a K&R function.
6195 if (!FTI.hasPrototype) {
Douglas Gregor862ffb12009-04-02 03:14:12 +00006196 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
6197 --i;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006198 if (FTI.ArgInfo[i].Param == 0) {
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00006199 llvm::SmallString<256> Code;
6200 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar07d07852009-10-18 21:17:35 +00006201 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00006202 << ";\n";
Chris Lattner4bd8dd82008-11-19 08:23:25 +00006203 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregor170512f2009-04-01 23:51:29 +00006204 << FTI.ArgInfo[i].Ident
Douglas Gregora771f462010-03-31 17:46:05 +00006205 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregor170512f2009-04-01 23:51:29 +00006206
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00006207 // Implicitly declare the argument as type 'int' for lack of a better
6208 // type.
John McCall084e83d2011-03-24 11:26:52 +00006209 AttributeFactory attrs;
6210 DeclSpec DS(attrs);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006211 const char* PrevSpec; // unused
John McCall49bfce42009-08-03 20:12:06 +00006212 unsigned DiagID; // unused
Mike Stump11289f42009-09-09 15:08:12 +00006213 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCall49bfce42009-08-03 20:12:06 +00006214 PrevSpec, DiagID);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006215 Declarator ParamD(DS, Declarator::KNRTypeListContext);
6216 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregor9aa89042009-01-23 16:23:13 +00006217 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00006218 }
6219 }
Mike Stump11289f42009-09-09 15:08:12 +00006220 }
Douglas Gregor9aa89042009-01-23 16:23:13 +00006221}
6222
John McCall48871652010-08-21 09:40:31 +00006223Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
6224 Declarator &D) {
Douglas Gregor9aa89042009-01-23 16:23:13 +00006225 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006226 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregorad590502008-12-15 23:53:10 +00006227 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +00006228
John McCall48871652010-08-21 09:40:31 +00006229 Decl *DP = HandleDeclarator(ParentScope, D,
6230 MultiTemplateParamsArg(*this),
6231 /*IsFunctionDefinition=*/true);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00006232 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006233}
6234
Anders Carlsson31c7e882009-12-09 03:30:09 +00006235static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
6236 // Don't warn about invalid declarations.
6237 if (FD->isInvalidDecl())
6238 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00006239
Anders Carlsson31c7e882009-12-09 03:30:09 +00006240 // Or declarations that aren't global.
6241 if (!FD->isGlobal())
6242 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00006243
Anders Carlsson31c7e882009-12-09 03:30:09 +00006244 // Don't warn about C++ member functions.
6245 if (isa<CXXMethodDecl>(FD))
6246 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00006247
Anders Carlsson31c7e882009-12-09 03:30:09 +00006248 // Don't warn about 'main'.
6249 if (FD->isMain())
6250 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00006251
Anders Carlsson31c7e882009-12-09 03:30:09 +00006252 // Don't warn about inline functions.
John McCall30cd20a2011-03-22 07:16:37 +00006253 if (FD->isInlined())
Anders Carlsson31c7e882009-12-09 03:30:09 +00006254 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00006255
6256 // Don't warn about function templates.
6257 if (FD->getDescribedFunctionTemplate())
6258 return false;
6259
6260 // Don't warn about function template specializations.
6261 if (FD->isFunctionTemplateSpecialization())
6262 return false;
6263
Anders Carlsson31c7e882009-12-09 03:30:09 +00006264 bool MissingPrototype = true;
6265 for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
6266 Prev; Prev = Prev->getPreviousDeclaration()) {
6267 // Ignore any declarations that occur in function or method
6268 // scope, because they aren't visible from the header.
6269 if (Prev->getDeclContext()->isFunctionOrMethod())
6270 continue;
6271
6272 MissingPrototype = !Prev->getType()->isFunctionProtoType();
6273 break;
6274 }
6275
6276 return MissingPrototype;
6277}
6278
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00006279void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) {
6280 // Don't complain if we're in GNU89 mode and the previous definition
6281 // was an extern inline function.
6282 const FunctionDecl *Definition;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00006283 if (FD->isDefined(Definition) &&
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00006284 !canRedefineFunction(Definition, getLangOptions())) {
6285 if (getLangOptions().GNUMode && Definition->isInlineSpecified() &&
6286 Definition->getStorageClass() == SC_Extern)
6287 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
6288 << FD->getDeclName() << getLangOptions().CPlusPlus;
6289 else
6290 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
6291 Diag(Definition->getLocation(), diag::note_previous_definition);
6292 }
6293}
6294
John McCall48871652010-08-21 09:40:31 +00006295Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson561f7932009-10-29 15:46:07 +00006296 // Clear the last template instantiation error context.
6297 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
6298
Douglas Gregor17a7c122009-06-24 00:54:41 +00006299 if (!D)
6300 return D;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00006301 FunctionDecl *FD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00006302
John McCall48871652010-08-21 09:40:31 +00006303 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregorc45a40a2009-08-22 00:34:47 +00006304 FD = FunTmpl->getTemplatedDecl();
6305 else
John McCall48871652010-08-21 09:40:31 +00006306 FD = cast<FunctionDecl>(D);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00006307
Douglas Gregor9a28e842010-03-01 23:15:13 +00006308 // Enter a new function scope
6309 PushFunctionScope();
Mike Stump11289f42009-09-09 15:08:12 +00006310
Douglas Gregorcad304ba2008-10-29 15:10:40 +00006311 // See if this is a redefinition.
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00006312 if (!FD->isLateTemplateParsed())
6313 CheckForFunctionRedefinition(FD);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00006314
Douglas Gregor75a45ba2009-02-16 17:45:42 +00006315 // Builtin functions cannot be defined.
Douglas Gregor15fc9562009-09-12 00:22:50 +00006316 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor7a0febe2009-02-17 16:03:01 +00006317 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00006318 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor7a0febe2009-02-17 16:03:01 +00006319 FD->setInvalidDecl();
6320 }
Douglas Gregor75a45ba2009-02-16 17:45:42 +00006321 }
6322
Eli Friedman9ad72442009-03-04 07:30:59 +00006323 // The return type of a function definition must be complete
Douglas Gregorac1fb652009-03-24 19:52:54 +00006324 // (C99 6.9.1p3, C++ [dcl.fct]p6).
6325 QualType ResultType = FD->getResultType();
6326 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner0f94c5a2009-04-29 05:12:23 +00006327 !FD->isInvalidDecl() &&
Douglas Gregorac1fb652009-03-24 19:52:54 +00006328 RequireCompleteType(FD->getLocation(), ResultType,
6329 diag::err_func_def_incomplete_result))
Eli Friedman9ad72442009-03-04 07:30:59 +00006330 FD->setInvalidDecl();
Eli Friedman9ad72442009-03-04 07:30:59 +00006331
Douglas Gregorf1b876d2009-03-31 16:35:03 +00006332 // GNU warning -Wmissing-prototypes:
6333 // Warn if a global function is defined without a previous
6334 // prototype declaration. This warning is issued even if the
6335 // definition itself provides a prototype. The aim is to detect
6336 // global functions that fail to be declared in header files.
Anders Carlsson31c7e882009-12-09 03:30:09 +00006337 if (ShouldWarnAboutMissingPrototype(FD))
6338 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Douglas Gregorf1b876d2009-03-31 16:35:03 +00006339
Douglas Gregor67da0d92009-05-15 17:59:04 +00006340 if (FnBodyScope)
6341 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00006342
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006343 // Check the validity of our function parameters
Douglas Gregorb524d902010-11-01 18:37:59 +00006344 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
6345 /*CheckParameterNames=*/true);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006346
6347 // Introduce our parameters into the function scope
6348 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
6349 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc72e6452009-01-09 18:51:29 +00006350 Param->setOwningFunction(FD);
6351
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006352 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00006353 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00006354 CheckShadow(FnBodyScope, Param);
John McCalldf8b37c2010-03-22 09:20:08 +00006355
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00006356 PushOnScopeChains(Param, FnBodyScope);
John McCalldf8b37c2010-03-22 09:20:08 +00006357 }
Chris Lattnerf61c8a82007-01-21 19:04:43 +00006358 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006359
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00006360 // Checking attributes of current function definition
6361 // dllimport attribute.
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006362 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
6363 if (DA && (!FD->getAttr<DLLExportAttr>())) {
6364 // dllimport attribute cannot be directly applied to definition.
Francois Pichet3096d202011-03-29 10:39:17 +00006365 // Microsoft accepts dllimport for functions defined within class scope.
6366 if (!DA->isInherited() &&
6367 !(LangOpts.Microsoft && FD->getLexicalDeclContext()->isRecord())) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00006368 Diag(FD->getLocation(),
6369 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
6370 << "dllimport";
6371 FD->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +00006372 return FD;
Ted Kremeneka3cfc4d2010-02-21 05:12:53 +00006373 }
6374
6375 // Visual C++ appears to not think this is an issue, so only issue
6376 // a warning when Microsoft extensions are disabled.
6377 if (!LangOpts.Microsoft) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00006378 // If a symbol previously declared dllimport is later defined, the
6379 // attribute is ignored in subsequent references, and a warning is
6380 // emitted.
6381 Diag(FD->getLocation(),
6382 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Daniel Dunbar56df9772010-08-17 22:39:59 +00006383 << FD->getName() << "dllimport";
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00006384 }
6385 }
John McCall48871652010-08-21 09:40:31 +00006386 return FD;
Chris Lattnere168f762006-11-10 05:29:30 +00006387}
6388
Douglas Gregor6fd1b182010-05-15 06:01:05 +00006389/// \brief Given the set of return statements within a function body,
6390/// compute the variables that are subject to the named return value
6391/// optimization.
6392///
6393/// Each of the variables that is subject to the named return value
6394/// optimization will be marked as NRVO variables in the AST, and any
6395/// return statement that has a marked NRVO variable as its NRVO candidate can
6396/// use the named return value optimization.
6397///
6398/// This function applies a very simplistic algorithm for NRVO: if every return
6399/// statement in the function has the same NRVO candidate, that candidate is
6400/// the NRVO variable.
6401///
6402/// FIXME: Employ a smarter algorithm that accounts for multiple return
6403/// statements and the lifetimes of the NRVO candidates. We should be able to
6404/// find a maximal set of NRVO variables.
John McCallaab3e412010-08-25 08:40:02 +00006405static void ComputeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
6406 ReturnStmt **Returns = Scope->Returns.data();
6407
Douglas Gregor6fd1b182010-05-15 06:01:05 +00006408 const VarDecl *NRVOCandidate = 0;
John McCallaab3e412010-08-25 08:40:02 +00006409 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00006410 if (!Returns[I]->getNRVOCandidate())
6411 return;
6412
6413 if (!NRVOCandidate)
6414 NRVOCandidate = Returns[I]->getNRVOCandidate();
6415 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
6416 return;
6417 }
6418
6419 if (NRVOCandidate)
6420 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
6421}
6422
John McCallfaf5fb42010-08-26 23:41:50 +00006423Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Douglas Gregor67da0d92009-05-15 17:59:04 +00006424 return ActOnFinishFunctionBody(D, move(BodyArg), false);
6425}
6426
John McCallb268a282010-08-23 23:25:46 +00006427Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
6428 bool IsInstantiation) {
Douglas Gregorc45a40a2009-08-22 00:34:47 +00006429 FunctionDecl *FD = 0;
6430 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
6431 if (FunTmpl)
6432 FD = FunTmpl->getTemplatedDecl();
6433 else
6434 FD = dyn_cast_or_null<FunctionDecl>(dcl);
6435
Ted Kremenek0b405322010-03-23 00:13:23 +00006436 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek1767a272011-02-23 01:51:48 +00006437 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenek918fe842010-03-20 21:06:02 +00006438
Douglas Gregorc45a40a2009-08-22 00:34:47 +00006439 if (FD) {
Chris Lattner960cc522009-04-18 09:36:27 +00006440 FD->setBody(Body);
Ted Kremenek918fe842010-03-20 21:06:02 +00006441 if (FD->isMain()) {
Mike Stump8e79f992009-07-24 02:49:01 +00006442 // C and C++ allow for main to automagically return 0.
John McCallcaa19452009-07-28 01:00:58 +00006443 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
6444 FD->setHasImplicitReturnZero(true);
Ted Kremenek0b405322010-03-23 00:13:23 +00006445 WP.disableCheckFallThrough();
Ted Kremenek918fe842010-03-20 21:06:02 +00006446 }
Mike Stump11289f42009-09-09 15:08:12 +00006447
Francois Pichet3abc9b82011-05-11 02:14:46 +00006448 // MSVC permits the use of pure specifier (=0) on function definition,
6449 // defined at class scope, warn about this non standard construct.
6450 if (getLangOptions().Microsoft && FD->isPure())
6451 Diag(FD->getLocation(), diag::warn_pure_function_definition);
6452
Douglas Gregor88d292c2010-05-13 16:44:06 +00006453 if (!FD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006454 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006455 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
6456 FD->getResultType(), FD);
Douglas Gregor88d292c2010-05-13 16:44:06 +00006457
6458 // If this is a constructor, we need a vtable.
6459 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
6460 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor6fd1b182010-05-15 06:01:05 +00006461
John McCallaab3e412010-08-25 08:40:02 +00006462 ComputeNRVO(Body, getCurFunction());
Douglas Gregor88d292c2010-05-13 16:44:06 +00006463 }
6464
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00006465 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff542cd5d2008-07-25 17:57:26 +00006466 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattner1598a3a2009-02-16 19:27:54 +00006467 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattner960cc522009-04-18 09:36:27 +00006468 MD->setBody(Body);
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00006469 if (Body)
6470 MD->setEndLoc(Body->getLocEnd());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006471 if (!MD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006472 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006473 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
6474 MD->getResultType(), MD);
6475 }
Ted Kremenek5a201952009-02-07 01:47:29 +00006476 } else {
John McCall48871652010-08-21 09:40:31 +00006477 return 0;
Ted Kremenek5a201952009-02-07 01:47:29 +00006478 }
Douglas Gregor67da0d92009-05-15 17:59:04 +00006479
Chris Lattnere2473062007-05-28 06:28:18 +00006480 // Verify and clean out per-function state.
Douglas Gregor9a28e842010-03-01 23:15:13 +00006481 if (Body) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00006482 // C++ constructors that have function-try-blocks can't have return
6483 // statements in the handlers of that block. (C++ [except.handle]p14)
6484 // Verify this.
6485 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
6486 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
6487
Ted Kremenek918fe842010-03-20 21:06:02 +00006488 // Verify that that gotos and switch cases don't jump into scopes illegally.
6489 // Verify that that gotos and switch cases don't jump into scopes illegally.
John McCallaab3e412010-08-25 08:40:02 +00006490 if (getCurFunction()->NeedsScopeChecking() &&
John McCall58efb8e2010-05-20 07:13:26 +00006491 !dcl->isInvalidDecl() &&
John McCall31168b02011-06-15 23:02:42 +00006492 !hasAnyUnrecoverableErrorsInThisFunction())
Douglas Gregor9a28e842010-03-01 23:15:13 +00006493 DiagnoseInvalidJumps(Body);
Mike Stump11289f42009-09-09 15:08:12 +00006494
John McCalldeb646e2010-08-04 01:04:25 +00006495 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
6496 if (!Destructor->getParent()->isDependentType())
6497 CheckDestructor(Destructor);
6498
John McCalla6309952010-03-16 21:39:52 +00006499 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6500 Destructor->getParent());
John McCalldeb646e2010-08-04 01:04:25 +00006501 }
Douglas Gregor9a28e842010-03-01 23:15:13 +00006502
6503 // If any errors have occurred, clear out any temporaries that may have
6504 // been leftover. This ensures that these temporaries won't be picked up for
6505 // deletion in some later function.
Douglas Gregor550b98b2011-03-04 23:08:02 +00006506 if (PP.getDiagnostics().hasErrorOccurred() ||
John McCall31168b02011-06-15 23:02:42 +00006507 PP.getDiagnostics().getSuppressAllDiagnostics()) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00006508 ExprTemporaries.clear();
John McCall31168b02011-06-15 23:02:42 +00006509 ExprNeedsCleanups = false;
6510 } else if (!isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenek918fe842010-03-20 21:06:02 +00006511 // Since the body is valid, issue any analysis-based warnings that are
6512 // enabled.
Ted Kremenek1767a272011-02-23 01:51:48 +00006513 ActivePolicy = &WP;
Ted Kremenek918fe842010-03-20 21:06:02 +00006514 }
6515
Douglas Gregor9a28e842010-03-01 23:15:13 +00006516 assert(ExprTemporaries.empty() && "Leftover temporaries in function");
John McCall31168b02011-06-15 23:02:42 +00006517 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Douglas Gregor9a28e842010-03-01 23:15:13 +00006518 }
6519
John McCalle99d5f32010-03-25 22:08:03 +00006520 if (!IsInstantiation)
6521 PopDeclContext();
6522
Ted Kremenek1767a272011-02-23 01:51:48 +00006523 PopFunctionOrBlockScope(ActivePolicy, dcl);
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00006524
Douglas Gregora7e3ea32009-11-15 07:07:58 +00006525 // If any errors have occurred, clear out any temporaries that may have
6526 // been leftover. This ensures that these temporaries won't be picked up for
6527 // deletion in some later function.
John McCall31168b02011-06-15 23:02:42 +00006528 if (getDiagnostics().hasErrorOccurred()) {
Douglas Gregora7e3ea32009-11-15 07:07:58 +00006529 ExprTemporaries.clear();
John McCall31168b02011-06-15 23:02:42 +00006530 ExprNeedsCleanups = false;
6531 }
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00006532
John McCall48871652010-08-21 09:40:31 +00006533 return dcl;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +00006534}
6535
Chris Lattnerac18be92006-11-20 06:49:47 +00006536/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
6537/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump11289f42009-09-09 15:08:12 +00006538NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00006539 IdentifierInfo &II, Scope *S) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00006540 // Before we produce a declaration for an implicitly defined
6541 // function, see whether there was a locally-scoped declaration of
6542 // this name as a function or variable. If so, use that
6543 // (non-visible) declaration, and complain about it.
6544 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
6545 = LocallyScopedExternalDecls.find(&II);
6546 if (Pos != LocallyScopedExternalDecls.end()) {
6547 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
6548 Diag(Pos->second->getLocation(), diag::note_previous_declaration);
6549 return Pos->second;
6550 }
6551
Chris Lattner00e26072008-05-05 21:18:06 +00006552 // Extension in C99. Legal in C90, but warn about it.
Daniel Dunbar07d07852009-10-18 21:17:35 +00006553 if (II.getName().startswith("__builtin_"))
Douglas Gregor56fbc372009-09-28 21:14:19 +00006554 Diag(Loc, diag::warn_builtin_unknown) << &II;
6555 else if (getLangOptions().C99)
Chris Lattner4bd8dd82008-11-19 08:23:25 +00006556 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner00e26072008-05-05 21:18:06 +00006557 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +00006558 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Mike Stump11289f42009-09-09 15:08:12 +00006559
Chris Lattnerac18be92006-11-20 06:49:47 +00006560 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +00006561 const char *Dummy;
John McCall084e83d2011-03-24 11:26:52 +00006562 AttributeFactory attrFactory;
6563 DeclSpec DS(attrFactory);
John McCall49bfce42009-08-03 20:12:06 +00006564 unsigned DiagID;
6565 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00006566 (void)Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +00006567 assert(!Error && "Error setting up implicit decl!");
Chris Lattnerac18be92006-11-20 06:49:47 +00006568 Declarator D(DS, Declarator::BlockContext);
John McCall084e83d2011-03-24 11:26:52 +00006569 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
Douglas Gregor54992352011-01-26 03:43:54 +00006570 0, 0, true, SourceLocation(),
Sebastian Redl802a4532011-03-05 22:42:13 +00006571 EST_None, SourceLocation(),
6572 0, 0, 0, 0, Loc, Loc, D),
John McCall084e83d2011-03-24 11:26:52 +00006573 DS.getAttributes(),
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006574 SourceLocation());
Chris Lattnerac18be92006-11-20 06:49:47 +00006575 D.SetIdentifier(&II, Loc);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006576
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00006577 // Insert this function into translation-unit scope.
6578
6579 DeclContext *PrevDC = CurContext;
6580 CurContext = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006581
John McCall48871652010-08-21 09:40:31 +00006582 FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroff3913ea42008-04-04 14:32:09 +00006583 FD->setImplicit();
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00006584
6585 CurContext = PrevDC;
6586
Douglas Gregore711f702009-02-14 18:57:46 +00006587 AddKnownFunctionAttributes(FD);
6588
Steve Naroff3913ea42008-04-04 14:32:09 +00006589 return FD;
Chris Lattnerac18be92006-11-20 06:49:47 +00006590}
6591
Douglas Gregore711f702009-02-14 18:57:46 +00006592/// \brief Adds any function attributes that we know a priori based on
6593/// the declaration of this function.
6594///
6595/// These attributes can apply both to implicitly-declared builtins
6596/// (like __builtin___printf_chk) or to library-declared functions
6597/// like NSLog or printf.
Douglas Gregor88336832011-06-15 05:45:11 +00006598///
6599/// We need to check for duplicate attributes both here and where user-written
6600/// attributes are applied to declarations.
Douglas Gregore711f702009-02-14 18:57:46 +00006601void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
6602 if (FD->isInvalidDecl())
6603 return;
6604
6605 // If this is a built-in function, map its builtin attributes to
6606 // actual attributes.
Douglas Gregor15fc9562009-09-12 00:22:50 +00006607 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregore711f702009-02-14 18:57:46 +00006608 // Handle printf-formatting attributes.
6609 unsigned FormatIdx;
6610 bool HasVAListArg;
6611 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006612 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006613 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
6614 "printf", FormatIdx+1,
Ted Kremenek7f4945a2010-02-11 05:28:37 +00006615 HasVAListArg ? 0 : FormatIdx+2));
Douglas Gregore711f702009-02-14 18:57:46 +00006616 }
Ted Kremenek5932c352010-07-16 02:11:15 +00006617 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
6618 HasVAListArg)) {
6619 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006620 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
6621 "scanf", FormatIdx+1,
Ted Kremenek5932c352010-07-16 02:11:15 +00006622 HasVAListArg ? 0 : FormatIdx+2));
6623 }
Daniel Dunbar8eb018a2009-02-16 22:43:43 +00006624
6625 // Mark const if we don't care about errno and that is the only
6626 // thing preventing the function from being const. This allows
6627 // IRgen to use LLVM intrinsics for such functions.
6628 if (!getLangOptions().MathErrno &&
6629 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006630 if (!FD->getAttr<ConstAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006631 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Daniel Dunbar8eb018a2009-02-16 22:43:43 +00006632 }
Mike Stumpca6c8752009-07-27 19:14:18 +00006633
Douglas Gregor88336832011-06-15 05:45:11 +00006634 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006635 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
Douglas Gregor88336832011-06-15 05:45:11 +00006636 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006637 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Douglas Gregore711f702009-02-14 18:57:46 +00006638 }
6639
6640 IdentifierInfo *Name = FD->getIdentifier();
6641 if (!Name)
6642 return;
Mike Stump11289f42009-09-09 15:08:12 +00006643 if ((!getLangOptions().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +00006644 FD->getDeclContext()->isTranslationUnit()) ||
6645 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +00006646 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregore711f702009-02-14 18:57:46 +00006647 LinkageSpecDecl::lang_c)) {
6648 // Okay: this could be a libc/libm/Objective-C function we know
6649 // about.
6650 } else
6651 return;
6652
Douglas Gregorfedd4282009-04-22 20:56:09 +00006653 if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
Mike Stump82a9e442009-07-28 00:07:08 +00006654 // FIXME: NSLog and NSLogv should be target specific
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006655 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
Douglas Gregore711f702009-02-14 18:57:46 +00006656 // FIXME: We known better than our headers.
Ted Kremenek7f4945a2010-02-11 05:28:37 +00006657 const_cast<FormatAttr *>(Format)->setType(Context, "printf");
Mike Stump11289f42009-09-09 15:08:12 +00006658 } else
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006659 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
6660 "printf", 1,
Eli Friedmanf4799842009-06-10 04:01:38 +00006661 Name->isStr("NSLogv") ? 0 : 2));
Douglas Gregorfedd4282009-04-22 20:56:09 +00006662 } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump82a9e442009-07-28 00:07:08 +00006663 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump11289f42009-09-09 15:08:12 +00006664 // target-specific builtins, perhaps?
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006665 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006666 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
6667 "printf", 2,
Eli Friedmanf4799842009-06-10 04:01:38 +00006668 Name->isStr("vasprintf") ? 0 : 3));
Mike Stumpa4de80b2009-07-28 02:25:19 +00006669 }
Douglas Gregore711f702009-02-14 18:57:46 +00006670}
Chris Lattner302b4be2006-11-19 02:31:38 +00006671
John McCall703a3f82009-10-24 08:00:42 +00006672TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCallbcd03502009-12-07 02:54:59 +00006673 TypeSourceInfo *TInfo) {
Chris Lattner776fac82007-06-09 00:53:06 +00006674 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +00006675 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump11289f42009-09-09 15:08:12 +00006676
John McCallbcd03502009-12-07 02:54:59 +00006677 if (!TInfo) {
John McCall703a3f82009-10-24 08:00:42 +00006678 assert(D.isInvalidType() && "no declarator info for valid type");
John McCallbcd03502009-12-07 02:54:59 +00006679 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCall703a3f82009-10-24 08:00:42 +00006680 }
6681
Chris Lattner18b19622007-01-22 07:39:13 +00006682 // Scope manipulation handled by caller.
Chris Lattnerc5ffed42008-04-04 06:12:32 +00006683 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00006684 D.getSourceRange().getBegin(),
Chris Lattnerc5ffed42008-04-04 06:12:32 +00006685 D.getIdentifierLoc(),
Mike Stump11289f42009-09-09 15:08:12 +00006686 D.getIdentifier(),
John McCallbcd03502009-12-07 02:54:59 +00006687 TInfo);
Mike Stump11289f42009-09-09 15:08:12 +00006688
John McCall04fcd0d2011-02-01 08:20:08 +00006689 // Bail out immediately if we have an invalid declaration.
6690 if (D.isInvalidType()) {
6691 NewTD->setInvalidDecl();
6692 return NewTD;
Anders Carlsson02751152009-03-10 17:07:44 +00006693 }
6694
John McCall04fcd0d2011-02-01 08:20:08 +00006695 // C++ [dcl.typedef]p8:
6696 // If the typedef declaration defines an unnamed class (or
6697 // enum), the first typedef-name declared by the declaration
6698 // to be that class type (or enum type) is used to denote the
6699 // class type (or enum type) for linkage purposes only.
6700 // We need to check whether the type was declared in the declaration.
6701 switch (D.getDeclSpec().getTypeSpecType()) {
6702 case TST_enum:
6703 case TST_struct:
6704 case TST_union:
6705 case TST_class: {
6706 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
6707
6708 // Do nothing if the tag is not anonymous or already has an
6709 // associated typedef (from an earlier typedef in this decl group).
6710 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smithdda56e42011-04-15 14:24:37 +00006711 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCall04fcd0d2011-02-01 08:20:08 +00006712
6713 // A well-formed anonymous tag must always be a TUK_Definition.
6714 assert(tagFromDeclSpec->isThisDeclarationADefinition());
6715
6716 // The type must match the tag exactly; no qualifiers allowed.
6717 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
6718 break;
6719
6720 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smithdda56e42011-04-15 14:24:37 +00006721 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCall04fcd0d2011-02-01 08:20:08 +00006722 break;
6723 }
6724
6725 default:
6726 break;
6727 }
6728
Steve Narofff93b6722007-08-28 20:14:24 +00006729 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +00006730}
6731
Douglas Gregord9034f02009-05-14 16:41:31 +00006732
6733/// \brief Determine whether a tag with a given kind is acceptable
6734/// as a redeclaration of the given tag declaration.
6735///
6736/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00006737bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieucaa33d32011-06-10 03:11:26 +00006738 TagTypeKind NewTag, bool isDefinition,
Douglas Gregord9034f02009-05-14 16:41:31 +00006739 SourceLocation NewTagLoc,
6740 const IdentifierInfo &Name) {
6741 // C++ [dcl.type.elab]p3:
6742 // The class-key or enum keyword present in the
6743 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara6150c882010-05-11 21:36:43 +00006744 // declaration to which the name in the elaborated-type-specifier
Douglas Gregord9034f02009-05-14 16:41:31 +00006745 // refers. This rule also applies to the form of
6746 // elaborated-type-specifier that declares a class-name or
6747 // friend class since it can be construed as referring to the
6748 // definition of the class. Thus, in any
6749 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara6150c882010-05-11 21:36:43 +00006750 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregord9034f02009-05-14 16:41:31 +00006751 // used to refer to a union (clause 9), and either the class or
6752 // struct class-key shall be used to refer to a class (clause 9)
6753 // declared using the class or struct class-key.
Abramo Bagnara6150c882010-05-11 21:36:43 +00006754 TagTypeKind OldTag = Previous->getTagKind();
Richard Trieucaa33d32011-06-10 03:11:26 +00006755 if (!isDefinition || (NewTag != TTK_Class && NewTag != TTK_Struct))
6756 if (OldTag == NewTag)
6757 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006758
Abramo Bagnara6150c882010-05-11 21:36:43 +00006759 if ((OldTag == TTK_Struct || OldTag == TTK_Class) &&
6760 (NewTag == TTK_Struct || NewTag == TTK_Class)) {
Douglas Gregord9034f02009-05-14 16:41:31 +00006761 // Warn about the struct/class tag mismatch.
6762 bool isTemplate = false;
6763 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
6764 isTemplate = Record->getDescribedClassTemplate();
6765
Richard Trieucaa33d32011-06-10 03:11:26 +00006766 if (!ActiveTemplateInstantiations.empty()) {
6767 // In a template instantiation, do not offer fix-its for tag mismatches
6768 // since they usually mess up the template instead of fixing the problem.
6769 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
6770 << (NewTag == TTK_Class) << isTemplate << &Name;
6771 return true;
6772 }
6773
6774 if (isDefinition) {
6775 // On definitions, check previous tags and issue a fix-it for each
6776 // one that doesn't match the current tag.
6777 if (Previous->getDefinition()) {
6778 // Don't suggest fix-its for redefinitions.
6779 return true;
6780 }
6781
6782 bool previousMismatch = false;
6783 for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
6784 E(Previous->redecls_end()); I != E; ++I) {
6785 if (I->getTagKind() != NewTag) {
6786 if (!previousMismatch) {
6787 previousMismatch = true;
6788 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
6789 << (NewTag == TTK_Class) << isTemplate << &Name;
6790 }
6791 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
6792 << (NewTag == TTK_Class)
6793 << FixItHint::CreateReplacement(I->getInnerLocStart(),
6794 NewTag == TTK_Class?
6795 "class" : "struct");
6796 }
6797 }
6798 return true;
6799 }
6800
6801 // Check for a previous definition. If current tag and definition
6802 // are same type, do nothing. If no definition, but disagree with
6803 // with previous tag type, give a warning, but no fix-it.
6804 const TagDecl *Redecl = Previous->getDefinition() ?
6805 Previous->getDefinition() : Previous;
6806 if (Redecl->getTagKind() == NewTag) {
6807 return true;
6808 }
6809
Douglas Gregord9034f02009-05-14 16:41:31 +00006810 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Abramo Bagnara6150c882010-05-11 21:36:43 +00006811 << (NewTag == TTK_Class)
Richard Trieucaa33d32011-06-10 03:11:26 +00006812 << isTemplate << &Name;
6813 Diag(Redecl->getLocation(), diag::note_previous_use);
6814
6815 // If there is a previous defintion, suggest a fix-it.
6816 if (Previous->getDefinition()) {
6817 Diag(NewTagLoc, diag::note_struct_class_suggestion)
6818 << (Redecl->getTagKind() == TTK_Class)
6819 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
6820 Redecl->getTagKind() == TTK_Class? "class" : "struct");
6821 }
6822
Douglas Gregord9034f02009-05-14 16:41:31 +00006823 return true;
6824 }
6825 return false;
6826}
6827
Steve Naroff30d242c2007-09-15 18:49:24 +00006828/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +00006829/// former case, Name will be non-null. In the later case, Name will be null.
John McCall9bb74a52009-07-31 02:45:11 +00006830/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Chris Lattner1300fb92007-01-23 23:42:53 +00006831/// reference/declaration/definition of a tag.
John McCall48871652010-08-21 09:40:31 +00006832Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor009f6992010-09-16 23:58:57 +00006833 SourceLocation KWLoc, CXXScopeSpec &SS,
6834 IdentifierInfo *Name, SourceLocation NameLoc,
6835 AttributeList *Attr, AccessSpecifier AS,
6836 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00006837 bool &OwnedDecl, bool &IsDependent,
6838 bool ScopedEnum, bool ScopedEnumUsesClassTag,
Douglas Gregor0bf31402010-10-08 23:50:27 +00006839 TypeResult UnderlyingType) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006840 // If this is not a definition, it must have a name.
John McCall9bb74a52009-07-31 02:45:11 +00006841 assert((Name != 0 || TUK == TUK_Definition) &&
Chris Lattner7b9ace62007-01-23 20:11:08 +00006842 "Nameless record must be a definition!");
John McCallace48cd2010-10-19 01:40:49 +00006843 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregorded2d7b2009-02-04 19:02:06 +00006844
Douglas Gregord6ab8742009-05-28 23:31:59 +00006845 OwnedDecl = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +00006846 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00006847
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006848 // FIXME: Check explicit specializations more carefully.
6849 bool isExplicitSpecialization = false;
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006850 bool Invalid = false;
John McCallace48cd2010-10-19 01:40:49 +00006851
6852 // We only need to do this matching if we have template parameters
6853 // or a scope specifier, which also conveniently avoids this work
6854 // for non-C++ cases.
Abramo Bagnara60804e12011-03-18 15:16:37 +00006855 if (TemplateParameterLists.size() > 0 ||
John McCallace48cd2010-10-19 01:40:49 +00006856 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Douglas Gregore93e46c2009-07-22 23:48:44 +00006857 if (TemplateParameterList *TemplateParams
Douglas Gregor972fe532011-05-10 18:27:06 +00006858 = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS,
John McCallc9739e32010-10-16 07:23:36 +00006859 TemplateParameterLists.get(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00006860 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00006861 TUK == TUK_Friend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006862 isExplicitSpecialization,
6863 Invalid)) {
Douglas Gregor3dad8422009-09-26 06:47:28 +00006864 if (TemplateParams->size() > 0) {
Douglas Gregore93e46c2009-07-22 23:48:44 +00006865 // This is a declaration or definition of a class template (which may
6866 // be a member of another template).
Abramo Bagnara60804e12011-03-18 15:16:37 +00006867
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006868 if (Invalid)
John McCall48871652010-08-21 09:40:31 +00006869 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00006870
Douglas Gregore93e46c2009-07-22 23:48:44 +00006871 OwnedDecl = false;
John McCall9bb74a52009-07-31 02:45:11 +00006872 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +00006873 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00006874 TemplateParams, AS,
Abramo Bagnara60804e12011-03-18 15:16:37 +00006875 TemplateParameterLists.size() - 1,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00006876 (TemplateParameterList**) TemplateParameterLists.release());
Douglas Gregore93e46c2009-07-22 23:48:44 +00006877 return Result.get();
6878 } else {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006879 // The "template<>" header is extraneous.
6880 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara6150c882010-05-11 21:36:43 +00006881 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006882 isExplicitSpecialization = true;
Douglas Gregore93e46c2009-07-22 23:48:44 +00006883 }
Mike Stump11289f42009-09-09 15:08:12 +00006884 }
6885 }
6886
Douglas Gregor0bf31402010-10-08 23:50:27 +00006887 // Figure out the underlying type if this a enum declaration. We need to do
6888 // this early, because it's needed to detect if this is an incompatible
6889 // redeclaration.
6890 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
6891
6892 if (Kind == TTK_Enum) {
6893 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
6894 // No underlying type explicitly specified, or we failed to parse the
6895 // type, default to int.
6896 EnumUnderlying = Context.IntTy.getTypePtr();
6897 else if (UnderlyingType.get()) {
6898 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
6899 // integral type; any cv-qualification is ignored.
6900 TypeSourceInfo *TI = 0;
6901 QualType T = GetTypeFromParser(UnderlyingType.get(), &TI);
6902 EnumUnderlying = TI;
6903
6904 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
6905
6906 if (!T->isDependentType() && !T->isIntegralType(Context)) {
6907 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
6908 << T;
6909 // Recover by falling back to int.
6910 EnumUnderlying = Context.IntTy.getTypePtr();
6911 }
Douglas Gregor2b988fd2010-12-16 00:24:44 +00006912
6913 if (DiagnoseUnexpandedParameterPack(UnderlyingLoc, TI,
6914 UPPC_FixedUnderlyingType))
6915 EnumUnderlying = Context.IntTy.getTypePtr();
6916
Francois Picheta3108062010-10-18 15:01:13 +00006917 } else if (getLangOptions().Microsoft)
6918 // Microsoft enums are always of int type.
6919 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006920 }
6921
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00006922 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00006923 DeclContext *DC = CurContext;
Douglas Gregor87f54062009-09-15 22:30:29 +00006924 bool isStdBadAlloc = false;
Douglas Gregordee1be82009-01-17 00:42:38 +00006925
Chandler Carrutha419dbb2010-03-01 21:17:36 +00006926 RedeclarationKind Redecl = ForRedeclaration;
6927 if (TUK == TUK_Friend || TUK == TUK_Reference)
6928 Redecl = NotForRedeclaration;
John McCall1f82f242009-11-18 22:49:29 +00006929
6930 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
John McCall6538c932009-10-10 05:48:19 +00006931
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00006932 if (Name && SS.isNotEmpty()) {
6933 // We have a nested-name tag ('struct foo::bar').
6934
6935 // Check for invalid 'foo::'.
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00006936 if (SS.isInvalid()) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00006937 Name = 0;
6938 goto CreateNewDecl;
6939 }
6940
John McCall7f41d982009-09-11 04:59:25 +00006941 // If this is a friend or a reference to a class in a dependent
6942 // context, don't try to make a decl for it.
6943 if (TUK == TUK_Friend || TUK == TUK_Reference) {
6944 DC = computeDeclContext(SS, false);
6945 if (!DC) {
6946 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +00006947 return 0;
John McCall7f41d982009-09-11 04:59:25 +00006948 }
John McCall0b66eb32010-05-01 00:40:08 +00006949 } else {
6950 DC = computeDeclContext(SS, true);
6951 if (!DC) {
6952 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
6953 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00006954 return 0;
John McCall0b66eb32010-05-01 00:40:08 +00006955 }
John McCall7f41d982009-09-11 04:59:25 +00006956 }
6957
John McCall0b66eb32010-05-01 00:40:08 +00006958 if (RequireCompleteDeclContext(SS, DC))
John McCall48871652010-08-21 09:40:31 +00006959 return 0;
Douglas Gregor2ec748c2009-05-14 00:28:11 +00006960
Douglas Gregor8761da52009-02-03 00:34:39 +00006961 SearchDC = DC;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00006962 // Look-up name inside 'foo::'.
John McCall1f82f242009-11-18 22:49:29 +00006963 LookupQualifiedName(Previous, DC);
John McCall6538c932009-10-10 05:48:19 +00006964
John McCall1f82f242009-11-18 22:49:29 +00006965 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006966 return 0;
John McCall6538c932009-10-10 05:48:19 +00006967
John McCall1f82f242009-11-18 22:49:29 +00006968 if (Previous.empty()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00006969 // Name lookup did not find anything. However, if the
6970 // nested-name-specifier refers to the current instantiation,
6971 // and that current instantiation has any dependent base
6972 // classes, we might find something at instantiation time: treat
6973 // this as a dependent elaborated-type-specifier.
John McCallace48cd2010-10-19 01:40:49 +00006974 // But this only makes any sense for reference-like lookups.
6975 if (Previous.wasNotFoundInCurrentInstantiation() &&
6976 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00006977 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +00006978 return 0;
Douglas Gregord2e6a452010-01-14 17:47:39 +00006979 }
6980
6981 // A tag 'foo::bar' must already exist.
Douglas Gregorf5af3582010-03-31 23:17:41 +00006982 Diag(NameLoc, diag::err_not_tag_in_scope)
6983 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00006984 Name = 0;
Douglas Gregorb8006faf2009-05-27 17:30:49 +00006985 Invalid = true;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00006986 goto CreateNewDecl;
6987 }
Chris Lattnerd9773512009-01-21 02:38:50 +00006988 } else if (Name) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00006989 // If this is a named struct, check to see if there was a previous forward
6990 // declaration or definition.
Douglas Gregor889ceb72009-02-03 19:21:40 +00006991 // FIXME: We're looking into outer scopes here, even when we
6992 // shouldn't be. Doing so can result in ambiguities that we
6993 // shouldn't be diagnosing.
John McCall1f82f242009-11-18 22:49:29 +00006994 LookupName(Previous, S);
6995
Douglas Gregor5d1d9e32011-05-09 21:46:33 +00006996 if (Previous.isAmbiguous() &&
6997 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregored8a29b2011-05-04 00:25:33 +00006998 LookupResult::Filter F = Previous.makeFilter();
6999 while (F.hasNext()) {
7000 NamedDecl *ND = F.next();
7001 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
7002 F.erase();
7003 }
7004 F.done();
Douglas Gregored8a29b2011-05-04 00:25:33 +00007005 }
7006
John McCall1f82f242009-11-18 22:49:29 +00007007 // Note: there used to be some attempt at recovery here.
7008 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00007009 return 0;
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007010
John McCall9bb74a52009-07-31 02:45:11 +00007011 if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007012 // FIXME: This makes sure that we ignore the contexts associated
7013 // with C structs, unions, and enums when looking for a matching
7014 // tag declaration or definition. See the similar lookup tweak
Douglas Gregored8f2882009-01-30 01:04:22 +00007015 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00007016 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
7017 SearchDC = SearchDC->getParent();
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007018 }
Douglas Gregor009f6992010-09-16 23:58:57 +00007019 } else if (S->isFunctionPrototypeScope()) {
7020 // If this is an enum declaration in function prototype scope, set its
7021 // initial context to the translation unit.
7022 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00007023 }
7024
John McCall1f82f242009-11-18 22:49:29 +00007025 if (Previous.isSingleResult() &&
7026 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00007027 // Maybe we will complain about the shadowed template parameter.
John McCall1f82f242009-11-18 22:49:29 +00007028 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor5101c242008-12-05 18:15:24 +00007029 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00007030 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00007031 }
7032
Douglas Gregor87f54062009-09-15 22:30:29 +00007033 if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007034 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor87f54062009-09-15 22:30:29 +00007035 // This is a declaration of or a reference to "std::bad_alloc".
7036 isStdBadAlloc = true;
7037
John McCall1f82f242009-11-18 22:49:29 +00007038 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor87f54062009-09-15 22:30:29 +00007039 // std::bad_alloc has been implicitly declared (but made invisible to
7040 // name lookup). Fill in this implicit declaration as the previous
7041 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007042 Previous.addDecl(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +00007043 }
7044 }
John McCall1f82f242009-11-18 22:49:29 +00007045
John McCalle9eaf8e2010-03-25 21:28:06 +00007046 // If we didn't find a previous declaration, and this is a reference
7047 // (or friend reference), move to the correct scope. In C++, we
7048 // also need to do a redeclaration lookup there, just in case
7049 // there's a shadow friend decl.
7050 if (Name && Previous.empty() &&
7051 (TUK == TUK_Reference || TUK == TUK_Friend)) {
7052 if (Invalid) goto CreateNewDecl;
7053 assert(SS.isEmpty());
7054
7055 if (TUK == TUK_Reference) {
7056 // C++ [basic.scope.pdecl]p5:
7057 // -- for an elaborated-type-specifier of the form
7058 //
7059 // class-key identifier
7060 //
7061 // if the elaborated-type-specifier is used in the
7062 // decl-specifier-seq or parameter-declaration-clause of a
7063 // function defined in namespace scope, the identifier is
7064 // declared as a class-name in the namespace that contains
7065 // the declaration; otherwise, except as a friend
7066 // declaration, the identifier is declared in the smallest
7067 // non-class, non-function-prototype scope that contains the
7068 // declaration.
7069 //
7070 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
7071 // C structs and unions.
7072 //
7073 // It is an error in C++ to declare (rather than define) an enum
7074 // type, including via an elaborated type specifier. We'll
7075 // diagnose that later; for now, declare the enum in the same
7076 // scope as we would have picked for any other tag type.
7077 //
7078 // GNU C also supports this behavior as part of its incomplete
7079 // enum types extension, while GNU C++ does not.
7080 //
7081 // Find the context where we'll be declaring the tag.
7082 // FIXME: We would like to maintain the current DeclContext as the
7083 // lexical context,
Rafael Espindola9e976dc2011-01-20 02:26:24 +00007084 while (SearchDC->isRecord() || SearchDC->isTransparentContext())
John McCalle9eaf8e2010-03-25 21:28:06 +00007085 SearchDC = SearchDC->getParent();
7086
7087 // Find the scope where we'll be declaring the tag.
7088 while (S->isClassScope() ||
7089 (getLangOptions().CPlusPlus &&
7090 S->isFunctionPrototypeScope()) ||
7091 ((S->getFlags() & Scope::DeclScope) == 0) ||
7092 (S->getEntity() &&
7093 ((DeclContext *)S->getEntity())->isTransparentContext()))
7094 S = S->getParent();
7095 } else {
7096 assert(TUK == TUK_Friend);
7097 // C++ [namespace.memdef]p3:
7098 // If a friend declaration in a non-local class first declares a
7099 // class or function, the friend class or function is a member of
7100 // the innermost enclosing namespace.
7101 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCalle9eaf8e2010-03-25 21:28:06 +00007102 }
7103
John McCalle87beb22010-04-23 18:46:30 +00007104 // In C++, we need to do a redeclaration lookup to properly
7105 // diagnose some problems.
John McCalle9eaf8e2010-03-25 21:28:06 +00007106 if (getLangOptions().CPlusPlus) {
7107 Previous.setRedeclarationKind(ForRedeclaration);
7108 LookupQualifiedName(Previous, SearchDC);
7109 }
7110 }
7111
John McCall1f82f242009-11-18 22:49:29 +00007112 if (!Previous.empty()) {
Douglas Gregorce40e2e2010-04-12 16:00:01 +00007113 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
John McCalle87beb22010-04-23 18:46:30 +00007114
7115 // It's okay to have a tag decl in the same scope as a typedef
7116 // which hides a tag decl in the same scope. Finding this
7117 // insanity with a redeclaration lookup can only actually happen
7118 // in C++.
7119 //
7120 // This is also okay for elaborated-type-specifiers, which is
7121 // technically forbidden by the current standard but which is
7122 // okay according to the likely resolution of an open issue;
7123 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
7124 if (getLangOptions().CPlusPlus) {
Richard Smithdda56e42011-04-15 14:24:37 +00007125 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCalle87beb22010-04-23 18:46:30 +00007126 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
7127 TagDecl *Tag = TT->getDecl();
7128 if (Tag->getDeclName() == Name &&
Sebastian Redl50c68252010-08-31 00:36:30 +00007129 Tag->getDeclContext()->getRedeclContext()
7130 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCalle87beb22010-04-23 18:46:30 +00007131 PrevDecl = Tag;
7132 Previous.clear();
7133 Previous.addDecl(Tag);
Douglas Gregorfcee9462010-08-27 22:55:10 +00007134 Previous.resolveKind();
John McCalle87beb22010-04-23 18:46:30 +00007135 }
7136 }
7137 }
7138 }
7139
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007140 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +00007141 // If this is a use of a previous tag, or if the tag is already declared
7142 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007143 // rementions the tag), reuse the decl.
John McCall07e91c02009-08-06 02:15:43 +00007144 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Douglas Gregordb446112011-03-07 16:54:27 +00007145 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +00007146 // Make sure that this wasn't declared as an enum and now used as a
7147 // struct or something similar.
Richard Trieucaa33d32011-06-10 03:11:26 +00007148 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
7149 TUK == TUK_Definition, KWLoc,
7150 *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00007151 bool SafeToContinue
Abramo Bagnara6150c882010-05-11 21:36:43 +00007152 = (PrevTagDecl->getTagKind() != TTK_Enum &&
7153 Kind != TTK_Enum);
Douglas Gregor170512f2009-04-01 23:51:29 +00007154 if (SafeToContinue)
Mike Stump11289f42009-09-09 15:08:12 +00007155 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00007156 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00007157 << FixItHint::CreateReplacement(SourceRange(KWLoc),
7158 PrevTagDecl->getKindName());
Douglas Gregor170512f2009-04-01 23:51:29 +00007159 else
7160 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall1f82f242009-11-18 22:49:29 +00007161 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00007162
Mike Stump11289f42009-09-09 15:08:12 +00007163 if (SafeToContinue)
Douglas Gregor170512f2009-04-01 23:51:29 +00007164 Kind = PrevTagDecl->getTagKind();
7165 else {
7166 // Recover by making this an anonymous redefinition.
7167 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00007168 Previous.clear();
Douglas Gregor170512f2009-04-01 23:51:29 +00007169 Invalid = true;
7170 }
7171 }
7172
Douglas Gregor0bf31402010-10-08 23:50:27 +00007173 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
7174 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
7175
7176 // All conflicts with previous declarations are recovered by
7177 // returning the previous declaration.
7178 if (ScopedEnum != PrevEnum->isScoped()) {
7179 Diag(KWLoc, diag::err_enum_redeclare_scoped_mismatch)
7180 << PrevEnum->isScoped();
7181 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
7182 return PrevTagDecl;
7183 }
7184 else if (EnumUnderlying && PrevEnum->isFixed()) {
7185 QualType T;
7186 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
7187 T = TI->getType();
7188 else
7189 T = QualType(EnumUnderlying.get<const Type*>(), 0);
7190
7191 if (!Context.hasSameUnqualifiedType(T, PrevEnum->getIntegerType())) {
Douglas Gregor1a099ba2010-12-01 16:10:38 +00007192 Diag(NameLoc.isValid() ? NameLoc : KWLoc,
7193 diag::err_enum_redeclare_type_mismatch)
7194 << T
7195 << PrevEnum->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007196 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
7197 return PrevTagDecl;
7198 }
7199 }
7200 else if (!EnumUnderlying.isNull() != PrevEnum->isFixed()) {
7201 Diag(KWLoc, diag::err_enum_redeclare_fixed_mismatch)
7202 << PrevEnum->isFixed();
7203 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
7204 return PrevTagDecl;
7205 }
7206 }
7207
Douglas Gregor170512f2009-04-01 23:51:29 +00007208 if (!Invalid) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007209 // If this is a use, just return the declaration we found.
Chris Lattner9ff58d72008-07-03 03:30:58 +00007210
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007211 // FIXME: In the future, return a variant or some other clue
7212 // for the consumer of this Decl to know it doesn't own it.
7213 // For our current ASTs this shouldn't be a problem, but will
7214 // need to be changed with DeclGroups.
Francois Pichete37eeba2011-06-01 04:14:20 +00007215 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
7216 getLangOptions().Microsoft)) || TUK == TUK_Friend)
John McCall48871652010-08-21 09:40:31 +00007217 return PrevTagDecl;
Douglas Gregorded2d7b2009-02-04 19:02:06 +00007218
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007219 // Diagnose attempts to redefine a tag.
John McCall9bb74a52009-07-31 02:45:11 +00007220 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007221 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00007222 // If we're defining a specialization and the previous definition
7223 // is from an implicit instantiation, don't emit an error
7224 // here; we'll catch this in the general case below.
7225 if (!isExplicitSpecialization ||
7226 !isa<CXXRecordDecl>(Def) ||
7227 cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
7228 == TSK_ExplicitSpecialization) {
7229 Diag(NameLoc, diag::err_redefinition) << Name;
7230 Diag(Def->getLocation(), diag::note_previous_definition);
7231 // If this is a redefinition, recover by making this
7232 // struct be anonymous, which will make any later
7233 // references get the previous definition.
7234 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00007235 Previous.clear();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007236 Invalid = true;
7237 }
Douglas Gregordee1be82009-01-17 00:42:38 +00007238 } else {
7239 // If the type is currently being defined, complain
7240 // about a nested redefinition.
John McCall424cec92011-01-19 06:33:43 +00007241 const TagType *Tag
7242 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregordee1be82009-01-17 00:42:38 +00007243 if (Tag->isBeingDefined()) {
7244 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump11289f42009-09-09 15:08:12 +00007245 Diag(PrevTagDecl->getLocation(),
Douglas Gregordee1be82009-01-17 00:42:38 +00007246 diag::note_previous_definition);
7247 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00007248 Previous.clear();
Douglas Gregordee1be82009-01-17 00:42:38 +00007249 Invalid = true;
7250 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007251 }
Douglas Gregordee1be82009-01-17 00:42:38 +00007252
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007253 // Okay, this is definition of a previously declared or referenced
7254 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregordee1be82009-01-17 00:42:38 +00007255 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007256 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007257 // If we get here we have (another) forward declaration or we
John McCall07e91c02009-08-06 02:15:43 +00007258 // have a definition. Just create a new decl.
7259
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007260 } else {
7261 // If we get here, this is a definition of a new tag type in a nested
Mike Stump11289f42009-09-09 15:08:12 +00007262 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007263 // new decl/type. We set PrevDecl to NULL so that the entities
7264 // have distinct types.
John McCall1f82f242009-11-18 22:49:29 +00007265 Previous.clear();
Chris Lattner7b9ace62007-01-23 20:11:08 +00007266 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007267 // If we get here, we're going to create a new Decl. If PrevDecl
7268 // is non-NULL, it's a definition of the tag declared by
7269 // PrevDecl. If it's NULL, we have a new definition.
John McCalle87beb22010-04-23 18:46:30 +00007270
7271
7272 // Otherwise, PrevDecl is not a tag, but was found with tag
7273 // lookup. This is only actually possible in C++, where a few
7274 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007275 } else {
John McCalle87beb22010-04-23 18:46:30 +00007276 assert(getLangOptions().CPlusPlus);
7277
7278 // Use a better diagnostic if an elaborated-type-specifier
7279 // found the wrong kind of type on the first
7280 // (non-redeclaration) lookup.
7281 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
7282 !Previous.isForRedeclaration()) {
7283 unsigned Kind = 0;
7284 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +00007285 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
7286 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +00007287 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
7288 Diag(PrevDecl->getLocation(), diag::note_declared_at);
7289 Invalid = true;
7290
7291 // Otherwise, only diagnose if the declaration is in scope.
Douglas Gregordb446112011-03-07 16:54:27 +00007292 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
7293 isExplicitSpecialization)) {
John McCalle87beb22010-04-23 18:46:30 +00007294 // do nothing
7295
7296 // Diagnose implicit declarations introduced by elaborated types.
7297 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
7298 unsigned Kind = 0;
7299 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +00007300 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
7301 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +00007302 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
7303 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
7304 Invalid = true;
7305
7306 // Otherwise it's a declaration. Call out a particularly common
7307 // case here.
Richard Smithdda56e42011-04-15 14:24:37 +00007308 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
7309 unsigned Kind = 0;
7310 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCalle87beb22010-04-23 18:46:30 +00007311 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smithdda56e42011-04-15 14:24:37 +00007312 << Name << Kind << TND->getUnderlyingType();
John McCalle87beb22010-04-23 18:46:30 +00007313 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
7314 Invalid = true;
7315
7316 // Otherwise, diagnose.
7317 } else {
7318 // The tag name clashes with something else in the target scope,
7319 // issue an error and recover by making this tag be anonymous.
Chris Lattner4bd8dd82008-11-19 08:23:25 +00007320 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner0369c572008-11-23 23:12:31 +00007321 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +00007322 Name = 0;
Douglas Gregordee1be82009-01-17 00:42:38 +00007323 Invalid = true;
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +00007324 }
John McCalle87beb22010-04-23 18:46:30 +00007325
7326 // The existing declaration isn't relevant to us; we're in a
7327 // new scope, so clear out the previous declaration.
7328 Previous.clear();
Chris Lattner8799cf22007-01-23 01:57:16 +00007329 }
Chris Lattner18b19622007-01-22 07:39:13 +00007330 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00007331
Chris Lattner438e5012008-12-17 07:13:27 +00007332CreateNewDecl:
Mike Stump11289f42009-09-09 15:08:12 +00007333
John McCall1f82f242009-11-18 22:49:29 +00007334 TagDecl *PrevDecl = 0;
7335 if (Previous.isSingleResult())
7336 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
7337
Chris Lattnerbf0b7982007-01-23 04:27:41 +00007338 // If there is an identifier, use the location of the identifier as the
7339 // location of the decl, otherwise use the location of the struct/union
7340 // keyword.
7341 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump11289f42009-09-09 15:08:12 +00007342
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007343 // Otherwise, create a new declaration. If there is a previous
7344 // declaration of the same entity, the two will be linked via
7345 // PrevDecl.
Chris Lattner7b9ace62007-01-23 20:11:08 +00007346 TagDecl *New;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00007347
Douglas Gregor0bf31402010-10-08 23:50:27 +00007348 bool IsForwardReference = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +00007349 if (Kind == TTK_Enum) {
Chris Lattner776fac82007-06-09 00:53:06 +00007350 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
7351 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007352 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor0bf31402010-10-08 23:50:27 +00007353 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00007354 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Chris Lattner5f521502007-01-25 06:27:24 +00007355 // If this is an undefined enum, warn.
Douglas Gregorc9ea2d52010-06-22 14:26:35 +00007356 if (TUK != TUK_Definition && !Invalid) {
7357 TagDecl *Def;
Douglas Gregor0bf31402010-10-08 23:50:27 +00007358 if (getLangOptions().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) {
7359 // C++0x: 7.2p2: opaque-enum-declaration.
7360 // Conflicts are diagnosed above. Do nothing.
7361 }
7362 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorc9ea2d52010-06-22 14:26:35 +00007363 Diag(Loc, diag::ext_forward_ref_enum_def)
7364 << New;
7365 Diag(Def->getLocation(), diag::note_previous_definition);
7366 } else {
Francois Pichet488b4a72010-09-12 05:06:55 +00007367 unsigned DiagID = diag::ext_forward_ref_enum;
7368 if (getLangOptions().Microsoft)
7369 DiagID = diag::ext_ms_forward_ref_enum;
7370 else if (getLangOptions().CPlusPlus)
7371 DiagID = diag::err_forward_ref_enum;
7372 Diag(Loc, DiagID);
Douglas Gregor0bf31402010-10-08 23:50:27 +00007373
7374 // If this is a forward-declared reference to an enumeration, make a
7375 // note of it; we won't actually be introducing the declaration into
7376 // the declaration context.
7377 if (TUK == TUK_Reference)
7378 IsForwardReference = true;
Douglas Gregorc9ea2d52010-06-22 14:26:35 +00007379 }
Douglas Gregord45b93b2009-03-06 18:34:03 +00007380 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00007381
7382 if (EnumUnderlying) {
7383 EnumDecl *ED = cast<EnumDecl>(New);
7384 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
7385 ED->setIntegerTypeSourceInfo(TI);
7386 else
7387 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
7388 ED->setPromotionType(ED->getIntegerType());
7389 }
7390
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00007391 } else {
7392 // struct/union/class
7393
Chris Lattner776fac82007-06-09 00:53:06 +00007394 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
7395 // struct X { int A; } D; D should chain to X.
Douglas Gregor87f54062009-09-15 22:30:29 +00007396 if (getLangOptions().CPlusPlus) {
Ted Kremenek6ddf53e2008-09-05 17:39:33 +00007397 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007398 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007399 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007400
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007401 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor87f54062009-09-15 22:30:29 +00007402 StdBadAlloc = cast<CXXRecordDecl>(New);
7403 } else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007404 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007405 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007406 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007407
John McCall3e11ebe2010-03-15 10:12:16 +00007408 // Maybe add qualifier info.
7409 if (SS.isNotEmpty()) {
Fariborz Jahanian862fac92010-05-14 21:35:02 +00007410 if (SS.isSet()) {
Douglas Gregor14454802011-02-25 02:25:35 +00007411 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara60804e12011-03-18 15:16:37 +00007412 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00007413 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00007414 TemplateParameterLists.size(),
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007415 (TemplateParameterList**) TemplateParameterLists.release());
7416 }
Fariborz Jahanian862fac92010-05-14 21:35:02 +00007417 }
7418 else
7419 Invalid = true;
John McCall3e11ebe2010-03-15 10:12:16 +00007420 }
7421
Daniel Dunbar8804f2e2010-05-27 01:53:40 +00007422 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
7423 // Add alignment attributes if necessary; these attributes are checked when
7424 // the ASTContext lays out the structure.
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007425 //
7426 // It is important for implementing the correct semantics that this
7427 // happen here (in act on tag decl). The #pragma pack stack is
7428 // maintained as a result of parser callbacks which can occur at
7429 // many points during the parsing of a struct declaration (because
7430 // the #pragma tokens are effectively skipped over during the
7431 // parsing of the struct).
Daniel Dunbar8804f2e2010-05-27 01:53:40 +00007432 AddAlignmentAttributesForRecord(RD);
Fariborz Jahanian6b4e26b2011-04-26 17:54:40 +00007433
7434 AddMsStructLayoutForRecord(RD);
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007435 }
7436
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007437 // If this is a specialization of a member class (of a class template),
7438 // check the specialization.
John McCall1f82f242009-11-18 22:49:29 +00007439 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007440 Invalid = true;
Daniel Dunbar8804f2e2010-05-27 01:53:40 +00007441
Douglas Gregordee1be82009-01-17 00:42:38 +00007442 if (Invalid)
7443 New->setInvalidDecl();
7444
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007445 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00007446 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007447
Douglas Gregordee1be82009-01-17 00:42:38 +00007448 // If we're declaring or defining a tag in function prototype scope
7449 // in C, note that this type can only be used within the function.
Douglas Gregor658b9552009-01-09 22:42:13 +00007450 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
7451 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
7452
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007453 // Set the lexical context. If the tag has a C++ scope specifier, the
7454 // lexical context will be different from the semantic context.
Douglas Gregor8761da52009-02-03 00:34:39 +00007455 New->setLexicalDeclContext(CurContext);
Douglas Gregordee1be82009-01-17 00:42:38 +00007456
John McCallaa74a0c2009-08-28 07:59:38 +00007457 // Mark this as a friend decl if applicable.
Francois Pichete37eeba2011-06-01 04:14:20 +00007458 // In Microsoft mode, a friend declaration also acts as a forward
7459 // declaration so we always pass true to setObjectOfFriendDecl to make
7460 // the tag name visible.
John McCallaa74a0c2009-08-28 07:59:38 +00007461 if (TUK == TUK_Friend)
Francois Pichete37eeba2011-06-01 04:14:20 +00007462 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() ||
7463 getLangOptions().Microsoft);
John McCallaa74a0c2009-08-28 07:59:38 +00007464
Anders Carlsson5558ca12009-03-26 01:19:02 +00007465 // Set the access specifier.
John McCalle9eaf8e2010-03-25 21:28:06 +00007466 if (!Invalid && SearchDC->isRecord())
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007467 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor6c2adff2009-03-25 22:00:53 +00007468
John McCall9bb74a52009-07-31 02:45:11 +00007469 if (TUK == TUK_Definition)
Douglas Gregordee1be82009-01-17 00:42:38 +00007470 New->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00007471
Chris Lattner18b19622007-01-22 07:39:13 +00007472 // If this has an identifier, add it to the scope stack.
John McCall2dc078f2009-09-02 00:55:30 +00007473 if (TUK == TUK_Friend) {
John McCallf8bd8612009-09-02 19:32:14 +00007474 // We might be replacing an existing declaration in the lookup tables;
7475 // if so, borrow its access specifier.
7476 if (PrevDecl)
7477 New->setAccess(PrevDecl->getAccess());
7478
Sebastian Redl50c68252010-08-31 00:36:30 +00007479 DeclContext *DC = New->getDeclContext()->getRedeclContext();
John McCalle9eaf8e2010-03-25 21:28:06 +00007480 DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
7481 if (Name) // can be null along some error paths
John McCall2dc078f2009-09-02 00:55:30 +00007482 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
7483 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCall2dc078f2009-09-02 00:55:30 +00007484 } else if (Name) {
Douglas Gregor45a33ec2009-01-12 18:45:55 +00007485 S = getNonFieldDeclScope(S);
Douglas Gregor0bf31402010-10-08 23:50:27 +00007486 PushOnScopeChains(New, S, !IsForwardReference);
7487 if (IsForwardReference)
7488 SearchDC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
7489
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00007490 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007491 CurContext->addDecl(New);
Chris Lattner18b19622007-01-22 07:39:13 +00007492 }
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00007493
Douglas Gregor27821ce2009-07-07 16:35:42 +00007494 // If this is the C FILE type, notify the AST context.
7495 if (IdentifierInfo *II = New->getIdentifier())
7496 if (!New->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00007497 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor27821ce2009-07-07 16:35:42 +00007498 II->isStr("FILE"))
7499 Context.setFILEDecl(New);
Mike Stump11289f42009-09-09 15:08:12 +00007500
Douglas Gregord6ab8742009-05-28 23:31:59 +00007501 OwnedDecl = true;
John McCall48871652010-08-21 09:40:31 +00007502 return New;
Chris Lattner18b19622007-01-22 07:39:13 +00007503}
Chris Lattner1300fb92007-01-23 23:42:53 +00007504
John McCall48871652010-08-21 09:40:31 +00007505void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00007506 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00007507 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregorba41d012010-04-24 16:38:41 +00007508
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007509 // Enter the tag context.
7510 PushDeclContext(S, Tag);
John McCall1c7e6ec2009-12-20 07:58:13 +00007511}
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007512
John McCall48871652010-08-21 09:40:31 +00007513void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson30f29442011-03-25 14:31:08 +00007514 SourceLocation FinalLoc,
John McCall1c7e6ec2009-12-20 07:58:13 +00007515 SourceLocation LBraceLoc) {
7516 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00007517 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007518
John McCall1c7e6ec2009-12-20 07:58:13 +00007519 FieldCollector->StartClass();
7520
7521 if (!Record->getIdentifier())
7522 return;
7523
Anders Carlsson30f29442011-03-25 14:31:08 +00007524 if (FinalLoc.isValid())
7525 Record->addAttr(new (Context) FinalAttr(FinalLoc, Context));
Anders Carlssonfc1eef42011-01-22 17:51:53 +00007526
John McCall1c7e6ec2009-12-20 07:58:13 +00007527 // C++ [class]p2:
7528 // [...] The class-name is also inserted into the scope of the
7529 // class itself; this is known as the injected-class-name. For
7530 // purposes of access checking, the injected-class-name is treated
7531 // as if it were a public member name.
7532 CXXRecordDecl *InjectedClassName
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007533 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
7534 Record->getLocStart(), Record->getLocation(),
John McCall1c7e6ec2009-12-20 07:58:13 +00007535 Record->getIdentifier(),
Argyrios Kyrtzidis470c4542010-10-14 20:14:21 +00007536 /*PrevDecl=*/0,
7537 /*DelayTypeCreation=*/true);
7538 Context.getTypeDeclType(InjectedClassName, Record);
John McCall1c7e6ec2009-12-20 07:58:13 +00007539 InjectedClassName->setImplicit();
7540 InjectedClassName->setAccess(AS_public);
7541 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
7542 InjectedClassName->setDescribedClassTemplate(Template);
7543 PushOnScopeChains(InjectedClassName, S);
7544 assert(InjectedClassName->isInjectedClassName() &&
7545 "Broken injected-class-name");
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007546}
7547
John McCall48871652010-08-21 09:40:31 +00007548void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +00007549 SourceLocation RBraceLoc) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00007550 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00007551 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +00007552 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007553
7554 if (isa<CXXRecordDecl>(Tag))
7555 FieldCollector->FinishClass();
7556
7557 // Exit this scope of this tag's definition.
7558 PopDeclContext();
Douglas Gregor859f0ae2010-01-06 17:00:51 +00007559
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007560 // Notify the consumer that we've defined a tag.
7561 Consumer.HandleTagDeclDefinition(Tag);
7562}
Chris Lattner535b8302008-06-21 19:39:06 +00007563
John McCall48871652010-08-21 09:40:31 +00007564void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCall2ff380a2010-03-17 00:38:33 +00007565 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00007566 TagDecl *Tag = cast<TagDecl>(TagD);
John McCall2ff380a2010-03-17 00:38:33 +00007567 Tag->setInvalidDecl();
7568
John McCall71ba5f22010-03-17 19:25:57 +00007569 // We're undoing ActOnTagStartDefinition here, not
7570 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
7571 // the FieldCollector.
John McCall2ff380a2010-03-17 00:38:33 +00007572
7573 PopDeclContext();
7574}
7575
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007576// Note that FieldName may be null for anonymous bitfields.
Mike Stump11289f42009-09-09 15:08:12 +00007577bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Eli Friedmanc96d4962009-08-15 21:55:26 +00007578 QualType FieldTy, const Expr *BitWidth,
7579 bool *ZeroWidth) {
7580 // Default to true; that shouldn't confuse checks for emptiness
7581 if (ZeroWidth)
7582 *ZeroWidth = true;
7583
Chris Lattner73bf7b42009-03-05 22:45:59 +00007584 // C99 6.7.2.1p4 - verify the field type.
Chris Lattnerd26760a2009-03-05 23:01:03 +00007585 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregorb90df602010-06-16 00:17:44 +00007586 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner73bf7b42009-03-05 22:45:59 +00007587 // Handle incomplete types with specific error.
Douglas Gregor81457422009-03-10 21:58:27 +00007588 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
7589 return true;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007590 if (FieldName)
7591 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
7592 << FieldName << FieldTy << BitWidth->getSourceRange();
7593 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
7594 << FieldTy << BitWidth->getSourceRange();
Douglas Gregora02a72a2010-12-15 23:18:36 +00007595 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
7596 UPPC_BitFieldWidth))
7597 return true;
Douglas Gregor1efa4372009-03-11 18:59:21 +00007598
7599 // If the bit-width is type- or value-dependent, don't try to check
7600 // it now.
7601 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
7602 return false;
7603
Anders Carlsson5df391e2008-12-06 20:33:04 +00007604 llvm::APSInt Value;
7605 if (VerifyIntegerConstantExpression(BitWidth, &Value))
7606 return true;
7607
Eli Friedmanc96d4962009-08-15 21:55:26 +00007608 if (Value != 0 && ZeroWidth)
7609 *ZeroWidth = false;
7610
Chris Lattner81ed6802008-12-12 04:56:04 +00007611 // Zero-width bitfield is ok for anonymous field.
7612 if (Value == 0 && FieldName)
7613 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00007614
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007615 if (Value.isSigned() && Value.isNegative()) {
7616 if (FieldName)
Mike Stump11289f42009-09-09 15:08:12 +00007617 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007618 << FieldName << Value.toString(10);
7619 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
7620 << Value.toString(10);
7621 }
Anders Carlsson5df391e2008-12-06 20:33:04 +00007622
Douglas Gregor1efa4372009-03-11 18:59:21 +00007623 if (!FieldTy->isDependentType()) {
7624 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007625 if (Value.getZExtValue() > TypeSize) {
Anders Carlssond5635fe2010-04-16 15:16:32 +00007626 if (!getLangOptions().CPlusPlus) {
7627 if (FieldName)
7628 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
7629 << FieldName << (unsigned)Value.getZExtValue()
7630 << (unsigned)TypeSize;
7631
7632 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
7633 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
7634 }
7635
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007636 if (FieldName)
Anders Carlssond5635fe2010-04-16 15:16:32 +00007637 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
7638 << FieldName << (unsigned)Value.getZExtValue()
7639 << (unsigned)TypeSize;
7640 else
7641 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
7642 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007643 }
Douglas Gregor1efa4372009-03-11 18:59:21 +00007644 }
Anders Carlsson5df391e2008-12-06 20:33:04 +00007645
7646 return false;
7647}
7648
Richard Smith938f40b2011-06-11 17:19:42 +00007649/// ActOnField - Each field of a C struct/union is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +00007650/// to create a FieldDecl object for it.
Richard Smith938f40b2011-06-11 17:19:42 +00007651Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
7652 Declarator &D, ExprTy *BitfieldWidth) {
John McCall48871652010-08-21 09:40:31 +00007653 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattner83f095c2009-03-28 19:18:32 +00007654 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smith938f40b2011-06-11 17:19:42 +00007655 /*HasInit=*/false, AS_public);
John McCall48871652010-08-21 09:40:31 +00007656 return Res;
Chris Lattner73bf7b42009-03-05 22:45:59 +00007657}
7658
7659/// HandleField - Analyze a field of a C struct or a C++ data member.
7660///
7661FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
7662 SourceLocation DeclStart,
Richard Smith938f40b2011-06-11 17:19:42 +00007663 Declarator &D, Expr *BitWidth, bool HasInit,
Douglas Gregor4261e4c2009-03-11 20:50:30 +00007664 AccessSpecifier AS) {
Chris Lattner1300fb92007-01-23 23:42:53 +00007665 IdentifierInfo *II = D.getIdentifier();
Chris Lattner1300fb92007-01-23 23:42:53 +00007666 SourceLocation Loc = DeclStart;
7667 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +00007668
John McCall8cb7bdf2010-06-04 23:28:52 +00007669 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
7670 QualType T = TInfo->getType();
Douglas Gregora02a72a2010-12-15 23:18:36 +00007671 if (getLangOptions().CPlusPlus) {
Douglas Gregor1efa4372009-03-11 18:59:21 +00007672 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00007673
Douglas Gregora02a72a2010-12-15 23:18:36 +00007674 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
7675 UPPC_DataMemberType)) {
7676 D.setInvalidType();
7677 T = Context.IntTy;
7678 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
7679 }
7680 }
7681
Eli Friedman574c7452009-04-07 19:37:57 +00007682 DiagnoseFunctionSpecifiers(D);
7683
Eli Friedmand5c0eed2009-04-19 20:27:55 +00007684 if (D.getDeclSpec().isThreadSpecified())
7685 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
Douglas Gregor2c7d9292010-08-30 14:32:14 +00007686
7687 // Check to see if this name was declared as a member previously
7688 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
7689 LookupName(Previous, S);
7690 assert((Previous.empty() || Previous.isOverloadedResult() ||
7691 Previous.isSingleResult())
7692 && "Lookup of member name should be either overloaded, single or null");
Eli Friedmand5c0eed2009-04-19 20:27:55 +00007693
Douglas Gregor2c7d9292010-08-30 14:32:14 +00007694 // If the name is overloaded then get any declaration else get the single result
7695 NamedDecl *PrevDecl = Previous.isOverloadedResult() ?
7696 Previous.getRepresentativeDecl() : Previous.getAsSingle<NamedDecl>();
Douglas Gregorf187420f2009-06-17 23:37:01 +00007697
7698 if (PrevDecl && PrevDecl->isTemplateParameter()) {
7699 // Maybe we will complain about the shadowed template parameter.
7700 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
7701 // Just pretend that we didn't see the previous declaration.
7702 PrevDecl = 0;
7703 }
7704
Douglas Gregor1efa4372009-03-11 18:59:21 +00007705 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
7706 PrevDecl = 0;
7707
Steve Naroff5ec6ff72009-07-14 14:58:18 +00007708 bool Mutable
7709 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
7710 SourceLocation TSSL = D.getSourceRange().getBegin();
7711 FieldDecl *NewFD
Richard Smith938f40b2011-06-11 17:19:42 +00007712 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, HasInit,
7713 TSSL, AS, PrevDecl, &D);
Rafael Espindola568586f2010-03-21 22:56:43 +00007714
7715 if (NewFD->isInvalidDecl())
7716 Record->setInvalidDecl();
7717
Douglas Gregor1efa4372009-03-11 18:59:21 +00007718 if (NewFD->isInvalidDecl() && PrevDecl) {
7719 // Don't introduce NewFD into scope; there's already something
7720 // with the same name in the same scope.
7721 } else if (II) {
7722 PushOnScopeChains(NewFD, S);
7723 } else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007724 Record->addDecl(NewFD);
Douglas Gregor1efa4372009-03-11 18:59:21 +00007725
7726 return NewFD;
7727}
7728
7729/// \brief Build a new FieldDecl and check its well-formedness.
7730///
7731/// This routine builds a new FieldDecl given the fields name, type,
7732/// record, etc. \p PrevDecl should refer to any previous declaration
7733/// with the same name and in the same scope as the field to be
7734/// created.
7735///
7736/// \returns a new FieldDecl.
7737///
Mike Stump11289f42009-09-09 15:08:12 +00007738/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00007739FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCallbcd03502009-12-07 02:54:59 +00007740 TypeSourceInfo *TInfo,
Douglas Gregor1efa4372009-03-11 18:59:21 +00007741 RecordDecl *Record, SourceLocation Loc,
Richard Smith938f40b2011-06-11 17:19:42 +00007742 bool Mutable, Expr *BitWidth, bool HasInit,
Steve Naroff5ec6ff72009-07-14 14:58:18 +00007743 SourceLocation TSSL,
Douglas Gregor4261e4c2009-03-11 20:50:30 +00007744 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor1efa4372009-03-11 18:59:21 +00007745 Declarator *D) {
7746 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Narofff93b6722007-08-28 20:14:24 +00007747 bool InvalidDecl = false;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007748 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redlbaad4e72009-01-05 20:52:13 +00007749
Douglas Gregor1efa4372009-03-11 18:59:21 +00007750 // If we receive a broken type, recover by assuming 'int' and
7751 // marking this declaration as invalid.
7752 if (T.isNull()) {
7753 InvalidDecl = true;
7754 T = Context.IntTy;
7755 }
7756
Eli Friedmand0e8de22009-12-07 00:22:08 +00007757 QualType EltTy = Context.getBaseElementType(T);
7758 if (!EltTy->isDependentType() &&
John McCall2677e102010-08-16 23:42:35 +00007759 RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
7760 // Fields of incomplete type force their record to be invalid.
7761 Record->setInvalidDecl();
Eli Friedmand0e8de22009-12-07 00:22:08 +00007762 InvalidDecl = true;
John McCall2677e102010-08-16 23:42:35 +00007763 }
Eli Friedmand0e8de22009-12-07 00:22:08 +00007764
Steve Naroff8eeeb132007-05-08 21:09:37 +00007765 // C99 6.7.2.1p8: A member of a structure or union may have any type other
7766 // than a variably modified type.
Eli Friedmand0e8de22009-12-07 00:22:08 +00007767 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00007768 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00007769 llvm::APSInt Oversized;
Eli Friedmana3b1d032009-02-21 00:44:51 +00007770 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00007771 SizeIsNegative,
7772 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00007773 if (!FixedTy.isNull()) {
7774 Diag(Loc, diag::warn_illegal_constant_array_size);
7775 T = FixedTy;
7776 } else {
7777 if (SizeIsNegative)
7778 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00007779 else if (Oversized.getBoolValue())
7780 Diag(Loc, diag::err_array_too_large)
7781 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00007782 else
7783 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00007784 InvalidDecl = true;
7785 }
Steve Naroff8eeeb132007-05-08 21:09:37 +00007786 }
Mike Stump11289f42009-09-09 15:08:12 +00007787
Anders Carlsson576cc6f2009-03-22 20:18:17 +00007788 // Fields can not have abstract class types
Eli Friedmand0e8de22009-12-07 00:22:08 +00007789 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
7790 diag::err_abstract_type_in_decl,
7791 AbstractFieldType))
Anders Carlsson576cc6f2009-03-22 20:18:17 +00007792 InvalidDecl = true;
Mike Stump11289f42009-09-09 15:08:12 +00007793
Eli Friedmanc96d4962009-08-15 21:55:26 +00007794 bool ZeroWidth = false;
Douglas Gregor1efa4372009-03-11 18:59:21 +00007795 // If this is declared as a bit-field, check the bit-field.
Eli Friedmand0e8de22009-12-07 00:22:08 +00007796 if (!InvalidDecl && BitWidth &&
7797 VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
Douglas Gregor1efa4372009-03-11 18:59:21 +00007798 InvalidDecl = true;
Douglas Gregor1efa4372009-03-11 18:59:21 +00007799 BitWidth = 0;
Eli Friedmanc96d4962009-08-15 21:55:26 +00007800 ZeroWidth = false;
Anders Carlsson5df391e2008-12-06 20:33:04 +00007801 }
Mike Stump11289f42009-09-09 15:08:12 +00007802
John McCallb1cd7da2010-06-04 08:34:12 +00007803 // Check that 'mutable' is consistent with the type of the declaration.
7804 if (!InvalidDecl && Mutable) {
7805 unsigned DiagID = 0;
7806 if (T->isReferenceType())
7807 DiagID = diag::err_mutable_reference;
7808 else if (T.isConstQualified())
7809 DiagID = diag::err_mutable_const;
7810
7811 if (DiagID) {
7812 SourceLocation ErrLoc = Loc;
7813 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
7814 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
7815 Diag(ErrLoc, DiagID);
7816 Mutable = false;
7817 InvalidDecl = true;
7818 }
7819 }
7820
Abramo Bagnaradff19302011-03-08 08:55:46 +00007821 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00007822 BitWidth, Mutable, HasInit);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007823 if (InvalidDecl)
7824 NewFD->setInvalidDecl();
Douglas Gregor91f84212008-12-11 16:49:14 +00007825
Douglas Gregor1efa4372009-03-11 18:59:21 +00007826 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
7827 Diag(Loc, diag::err_duplicate_member) << II;
7828 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
7829 NewFD->setInvalidDecl();
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007830 }
7831
John McCall67da35c2010-02-04 22:26:26 +00007832 if (!InvalidDecl && getLangOptions().CPlusPlus) {
Anders Carlsson2ceb3472010-11-07 19:13:55 +00007833 if (Record->isUnion()) {
7834 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
7835 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
7836 if (RDecl->getDefinition()) {
7837 // C++ [class.union]p1: An object of a class with a non-trivial
7838 // constructor, a non-trivial copy constructor, a non-trivial
7839 // destructor, or a non-trivial copy assignment operator
7840 // cannot be a member of a union, nor can an array of such
7841 // objects.
Alexis Hunt97ab5542011-05-16 22:41:40 +00007842 if (!getLangOptions().CPlusPlus0x && CheckNontrivialField(NewFD))
Anders Carlsson2ceb3472010-11-07 19:13:55 +00007843 NewFD->setInvalidDecl();
7844 }
7845 }
7846
7847 // C++ [class.union]p1: If a union contains a member of reference type,
7848 // the program is ill-formed.
7849 if (EltTy->isReferenceType()) {
7850 Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
7851 << NewFD->getDeclName() << EltTy;
7852 NewFD->setInvalidDecl();
Douglas Gregor8a273912009-07-22 18:25:24 +00007853 }
7854 }
7855 }
7856
Douglas Gregor1efa4372009-03-11 18:59:21 +00007857 // FIXME: We need to pass in the attributes given an AST
7858 // representation, not a parser representation.
7859 if (D)
Douglas Gregor758a8692009-06-17 21:51:59 +00007860 // FIXME: What to pass instead of TUScope?
7861 ProcessDeclAttributes(TUScope, NewFD, *D);
Douglas Gregor1efa4372009-03-11 18:59:21 +00007862
John McCall31168b02011-06-15 23:02:42 +00007863 // In auto-retain/release, infer strong retension for fields of
7864 // retainable type.
7865 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
7866 NewFD->setInvalidDecl();
7867
Fariborz Jahaniand29fecd2009-02-19 00:22:47 +00007868 if (T.isObjCGCWeak())
Fariborz Jahaniand35c7922009-02-18 18:14:41 +00007869 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlsson28e71082008-02-16 00:29:18 +00007870
Douglas Gregor4261e4c2009-03-11 20:50:30 +00007871 NewFD->setAccess(AS);
Steve Narofff93b6722007-08-28 20:14:24 +00007872 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +00007873}
7874
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00007875bool Sema::CheckNontrivialField(FieldDecl *FD) {
7876 assert(FD);
7877 assert(getLangOptions().CPlusPlus && "valid check only for C++");
7878
7879 if (FD->isInvalidDecl())
7880 return true;
7881
7882 QualType EltTy = Context.getBaseElementType(FD->getType());
7883 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
7884 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
7885 if (RDecl->getDefinition()) {
7886 // We check for copy constructors before constructors
7887 // because otherwise we'll never get complaints about
7888 // copy constructors.
7889
7890 CXXSpecialMember member = CXXInvalid;
7891 if (!RDecl->hasTrivialCopyConstructor())
7892 member = CXXCopyConstructor;
Alexis Huntf479f1b2011-05-09 18:22:59 +00007893 else if (!RDecl->hasTrivialDefaultConstructor())
Alexis Hunt80f00ff2011-05-10 19:08:14 +00007894 member = CXXDefaultConstructor;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00007895 else if (!RDecl->hasTrivialCopyAssignment())
7896 member = CXXCopyAssignment;
7897 else if (!RDecl->hasTrivialDestructor())
7898 member = CXXDestructor;
7899
7900 if (member != CXXInvalid) {
John McCall31168b02011-06-15 23:02:42 +00007901 if (getLangOptions().ObjCAutoRefCount && RDecl->hasObjectMember()) {
7902 // Objective-C++ ARC: it is an error to have a non-trivial field of
7903 // a union. However, system headers in Objective-C programs
7904 // occasionally have Objective-C lifetime objects within unions,
7905 // and rather than cause the program to fail, we make those
7906 // members unavailable.
7907 SourceLocation Loc = FD->getLocation();
7908 if (getSourceManager().isInSystemHeader(Loc)) {
7909 if (!FD->hasAttr<UnavailableAttr>())
7910 FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00007911 "this system field has retaining ownership"));
John McCall31168b02011-06-15 23:02:42 +00007912 return false;
7913 }
7914 }
7915
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00007916 Diag(FD->getLocation(), diag::err_illegal_union_or_anon_struct_member)
7917 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
7918 DiagnoseNontrivial(RT, member);
7919 return true;
7920 }
7921 }
7922 }
7923
7924 return false;
7925}
7926
Douglas Gregor8a273912009-07-22 18:25:24 +00007927/// DiagnoseNontrivial - Given that a class has a non-trivial
7928/// special member, figure out why.
7929void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
7930 QualType QT(T, 0U);
7931 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
7932
7933 // Check whether the member was user-declared.
7934 switch (member) {
Douglas Gregorfceea362010-04-22 14:36:26 +00007935 case CXXInvalid:
7936 break;
7937
Alexis Hunt80f00ff2011-05-10 19:08:14 +00007938 case CXXDefaultConstructor:
Douglas Gregor8a273912009-07-22 18:25:24 +00007939 if (RD->hasUserDeclaredConstructor()) {
7940 typedef CXXRecordDecl::ctor_iterator ctor_iter;
Sebastian Redle24b1622009-10-25 22:31:45 +00007941 for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
7942 const FunctionDecl *body = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007943 ci->hasBody(body);
Anders Carlssonb7229932010-04-20 23:32:58 +00007944 if (!body || !cast<CXXConstructorDecl>(body)->isImplicitlyDefined()) {
Douglas Gregor8a273912009-07-22 18:25:24 +00007945 SourceLocation CtorLoc = ci->getLocation();
7946 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
7947 return;
7948 }
Sebastian Redle24b1622009-10-25 22:31:45 +00007949 }
Douglas Gregor8a273912009-07-22 18:25:24 +00007950
7951 assert(0 && "found no user-declared constructors");
7952 return;
7953 }
7954 break;
7955
7956 case CXXCopyConstructor:
7957 if (RD->hasUserDeclaredCopyConstructor()) {
7958 SourceLocation CtorLoc =
Alexis Huntfcaeae42011-05-25 20:50:04 +00007959 RD->getCopyConstructor(0)->getLocation();
7960 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
7961 return;
7962 }
7963 break;
7964
7965 case CXXMoveConstructor:
7966 if (RD->hasUserDeclaredMoveConstructor()) {
7967 SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation();
Douglas Gregor8a273912009-07-22 18:25:24 +00007968 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
7969 return;
7970 }
7971 break;
7972
7973 case CXXCopyAssignment:
7974 if (RD->hasUserDeclaredCopyAssignment()) {
7975 // FIXME: this should use the location of the copy
7976 // assignment, not the type.
7977 SourceLocation TyLoc = RD->getSourceRange().getBegin();
7978 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
7979 return;
7980 }
7981 break;
7982
Alexis Huntfcaeae42011-05-25 20:50:04 +00007983 case CXXMoveAssignment:
7984 if (RD->hasUserDeclaredMoveAssignment()) {
7985 SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation();
7986 Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member;
7987 return;
7988 }
7989 break;
7990
Douglas Gregor8a273912009-07-22 18:25:24 +00007991 case CXXDestructor:
7992 if (RD->hasUserDeclaredDestructor()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00007993 SourceLocation DtorLoc = LookupDestructor(RD)->getLocation();
Douglas Gregor8a273912009-07-22 18:25:24 +00007994 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
7995 return;
7996 }
7997 break;
7998 }
7999
8000 typedef CXXRecordDecl::base_class_iterator base_iter;
8001
8002 // Virtual bases and members inhibit trivial copying/construction,
8003 // but not trivial destruction.
8004 if (member != CXXDestructor) {
8005 // Check for virtual bases. vbases includes indirect virtual bases,
8006 // so we just iterate through the direct bases.
8007 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
8008 if (bi->isVirtual()) {
8009 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
8010 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
8011 return;
8012 }
8013
8014 // Check for virtual methods.
8015 typedef CXXRecordDecl::method_iterator meth_iter;
8016 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
8017 ++mi) {
8018 if (mi->isVirtual()) {
8019 SourceLocation MLoc = mi->getSourceRange().getBegin();
8020 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
8021 return;
8022 }
8023 }
8024 }
Mike Stump11289f42009-09-09 15:08:12 +00008025
Douglas Gregor8a273912009-07-22 18:25:24 +00008026 bool (CXXRecordDecl::*hasTrivial)() const;
8027 switch (member) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008028 case CXXDefaultConstructor:
Alexis Huntf479f1b2011-05-09 18:22:59 +00008029 hasTrivial = &CXXRecordDecl::hasTrivialDefaultConstructor; break;
Douglas Gregor8a273912009-07-22 18:25:24 +00008030 case CXXCopyConstructor:
8031 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
8032 case CXXCopyAssignment:
8033 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
8034 case CXXDestructor:
8035 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
8036 default:
8037 assert(0 && "unexpected special member"); return;
8038 }
8039
8040 // Check for nontrivial bases (and recurse).
8041 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008042 const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
Sebastian Redl1054fae2009-10-25 17:03:50 +00008043 assert(BaseRT && "Don't know how to handle dependent bases");
Douglas Gregor8a273912009-07-22 18:25:24 +00008044 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
8045 if (!(BaseRecTy->*hasTrivial)()) {
8046 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
8047 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
8048 DiagnoseNontrivial(BaseRT, member);
8049 return;
8050 }
8051 }
Mike Stump11289f42009-09-09 15:08:12 +00008052
Douglas Gregor8a273912009-07-22 18:25:24 +00008053 // Check for nontrivial members (and recurse).
8054 typedef RecordDecl::field_iterator field_iter;
8055 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
8056 ++fi) {
Douglas Gregor79f83ed2009-07-23 23:49:00 +00008057 QualType EltTy = Context.getBaseElementType((*fi)->getType());
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008058 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
Douglas Gregor8a273912009-07-22 18:25:24 +00008059 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
8060
8061 if (!(EltRD->*hasTrivial)()) {
8062 SourceLocation FLoc = (*fi)->getLocation();
8063 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
8064 DiagnoseNontrivial(EltRT, member);
8065 return;
8066 }
8067 }
John McCall31168b02011-06-15 23:02:42 +00008068
8069 if (EltTy->isObjCLifetimeType()) {
8070 switch (EltTy.getObjCLifetime()) {
8071 case Qualifiers::OCL_None:
8072 case Qualifiers::OCL_ExplicitNone:
8073 break;
8074
8075 case Qualifiers::OCL_Autoreleasing:
8076 case Qualifiers::OCL_Weak:
8077 case Qualifiers::OCL_Strong:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008078 Diag((*fi)->getLocation(), diag::note_nontrivial_objc_ownership)
John McCall31168b02011-06-15 23:02:42 +00008079 << QT << EltTy.getObjCLifetime();
8080 return;
8081 }
8082 }
Douglas Gregor8a273912009-07-22 18:25:24 +00008083 }
8084
8085 assert(0 && "found no explanation for non-trivial member");
8086}
8087
Mike Stump11289f42009-09-09 15:08:12 +00008088/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00008089/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00008090static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00008091TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +00008092 switch (ivarVisibility) {
Chris Lattner79ef8432008-10-12 00:28:42 +00008093 default: assert(0 && "Unknown visitibility kind");
8094 case tok::objc_private: return ObjCIvarDecl::Private;
8095 case tok::objc_public: return ObjCIvarDecl::Public;
8096 case tok::objc_protected: return ObjCIvarDecl::Protected;
8097 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroff2e688fd2007-09-14 23:09:53 +00008098 }
8099}
8100
Mike Stump11289f42009-09-09 15:08:12 +00008101/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian96376742008-04-11 16:55:42 +00008102/// in order to create an IvarDecl object for it.
John McCall48871652010-08-21 09:40:31 +00008103Decl *Sema::ActOnIvar(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00008104 SourceLocation DeclStart,
John McCall48871652010-08-21 09:40:31 +00008105 Decl *IntfDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00008106 Declarator &D, ExprTy *BitfieldWidth,
8107 tok::ObjCKeywordKind Visibility) {
Mike Stump11289f42009-09-09 15:08:12 +00008108
Fariborz Jahaniande615832008-04-10 23:32:45 +00008109 IdentifierInfo *II = D.getIdentifier();
8110 Expr *BitWidth = (Expr*)BitfieldWidth;
8111 SourceLocation Loc = DeclStart;
8112 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +00008113
Fariborz Jahaniande615832008-04-10 23:32:45 +00008114 // FIXME: Unnamed fields can be handled in various different ways, for
8115 // example, unnamed unions inject all members into the struct namespace!
Mike Stump11289f42009-09-09 15:08:12 +00008116
John McCall8cb7bdf2010-06-04 23:28:52 +00008117 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8118 QualType T = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00008119
Fariborz Jahaniande615832008-04-10 23:32:45 +00008120 if (BitWidth) {
Steve Naroff17b2f5d2009-02-20 17:57:11 +00008121 // 6.7.2.1p3, 6.7.2.1p4
Chris Lattner73bf7b42009-03-05 22:45:59 +00008122 if (VerifyBitField(Loc, II, T, BitWidth)) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008123 D.setInvalidType();
Chris Lattner73bf7b42009-03-05 22:45:59 +00008124 BitWidth = 0;
8125 }
Fariborz Jahaniande615832008-04-10 23:32:45 +00008126 } else {
8127 // Not a bitfield.
Mike Stump11289f42009-09-09 15:08:12 +00008128
Fariborz Jahaniande615832008-04-10 23:32:45 +00008129 // validate II.
Mike Stump11289f42009-09-09 15:08:12 +00008130
Fariborz Jahaniande615832008-04-10 23:32:45 +00008131 }
Fariborz Jahanian0103d672010-04-26 22:07:03 +00008132 if (T->isReferenceType()) {
8133 Diag(Loc, diag::err_ivar_reference_type);
8134 D.setInvalidType();
8135 }
Fariborz Jahaniande615832008-04-10 23:32:45 +00008136 // C99 6.7.2.1p8: A member of a structure or union may have any type other
8137 // than a variably modified type.
Fariborz Jahanian0103d672010-04-26 22:07:03 +00008138 else if (T->isVariablyModifiedType()) {
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +00008139 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008140 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +00008141 }
Mike Stump11289f42009-09-09 15:08:12 +00008142
Ted Kremenek73295fa2008-07-23 18:04:17 +00008143 // Get the visibility (access control) for this ivar.
Mike Stump11289f42009-09-09 15:08:12 +00008144 ObjCIvarDecl::AccessControl ac =
Ted Kremenek73295fa2008-07-23 18:04:17 +00008145 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
8146 : ObjCIvarDecl::None;
Fariborz Jahanian68453832009-06-05 18:16:35 +00008147 // Must set ivar's DeclContext to its enclosing interface.
John McCall48871652010-08-21 09:40:31 +00008148 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(IntfDecl);
Daniel Dunbar229385c2010-04-02 18:29:09 +00008149 ObjCContainerDecl *EnclosingContext;
Mike Stump11289f42009-09-09 15:08:12 +00008150 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian68453832009-06-05 18:16:35 +00008151 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +00008152 if (!LangOpts.ObjCNonFragileABI2) {
Fariborz Jahanian68453832009-06-05 18:16:35 +00008153 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +00008154 EnclosingContext = IMPDecl->getClassInterface();
8155 assert(EnclosingContext && "Implementation has no class interface!");
8156 }
8157 else
8158 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00008159 } else {
8160 if (ObjCCategoryDecl *CDecl =
8161 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
8162 if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) {
8163 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCall48871652010-08-21 09:40:31 +00008164 return 0;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00008165 }
8166 }
Daniel Dunbar229385c2010-04-02 18:29:09 +00008167 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00008168 }
Mike Stump11289f42009-09-09 15:08:12 +00008169
Ted Kremenek73295fa2008-07-23 18:04:17 +00008170 // Construct the decl.
Abramo Bagnaradff19302011-03-08 08:55:46 +00008171 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
8172 DeclStart, Loc, II, T,
John McCallbcd03502009-12-07 02:54:59 +00008173 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump11289f42009-09-09 15:08:12 +00008174
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008175 if (II) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00008176 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall5cebab12009-11-18 07:57:50 +00008177 ForRedeclaration);
Fariborz Jahanian68453832009-06-05 18:16:35 +00008178 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008179 && !isa<TagDecl>(PrevDecl)) {
8180 Diag(Loc, diag::err_duplicate_member) << II;
8181 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
8182 NewID->setInvalidDecl();
8183 }
8184 }
8185
Ted Kremenek73295fa2008-07-23 18:04:17 +00008186 // Process attributes attached to the ivar.
Douglas Gregor758a8692009-06-17 21:51:59 +00008187 ProcessDeclAttributes(S, NewID, D);
Mike Stump11289f42009-09-09 15:08:12 +00008188
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008189 if (D.isInvalidType())
Fariborz Jahaniande615832008-04-10 23:32:45 +00008190 NewID->setInvalidDecl();
Ted Kremenek73295fa2008-07-23 18:04:17 +00008191
John McCall31168b02011-06-15 23:02:42 +00008192 // In ARC, infer 'retaining' for ivars of retainable type.
8193 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
8194 NewID->setInvalidDecl();
8195
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008196 if (II) {
8197 // FIXME: When interfaces are DeclContexts, we'll need to add
8198 // these to the interface.
John McCall48871652010-08-21 09:40:31 +00008199 S->AddDecl(NewID);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008200 IdResolver.AddDecl(NewID);
8201 }
8202
John McCall48871652010-08-21 09:40:31 +00008203 return NewID;
Fariborz Jahaniande615832008-04-10 23:32:45 +00008204}
8205
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00008206/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
8207/// class and class extensions. For every class @interface and class
8208/// extension @interface, if the last ivar is a bitfield of any type,
8209/// then add an implicit `char :0` ivar to the end of that interface.
8210void Sema::ActOnLastBitfield(SourceLocation DeclLoc, Decl *EnclosingDecl,
8211 llvm::SmallVectorImpl<Decl *> &AllIvarDecls) {
8212 if (!LangOpts.ObjCNonFragileABI2 || AllIvarDecls.empty())
8213 return;
8214
8215 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
8216 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
8217
8218 if (!Ivar->isBitField())
8219 return;
8220 uint64_t BitFieldSize =
8221 Ivar->getBitWidth()->EvaluateAsInt(Context).getZExtValue();
8222 if (BitFieldSize == 0)
8223 return;
8224 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl);
8225 if (!ID) {
8226 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
8227 if (!CD->IsClassExtension())
8228 return;
8229 }
8230 // No need to add this to end of @implementation.
8231 else
8232 return;
8233 }
8234 // All conditions are met. Add a new bitfield to the tail end of ivars.
8235 llvm::APInt Zero(Context.getTypeSize(Context.CharTy), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00008236 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.CharTy, DeclLoc);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00008237
8238 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(EnclosingDecl),
Abramo Bagnaradff19302011-03-08 08:55:46 +00008239 DeclLoc, DeclLoc, 0,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00008240 Context.CharTy,
8241 Context.CreateTypeSourceInfo(Context.CharTy),
8242 ObjCIvarDecl::Private, BW,
8243 true);
8244 AllIvarDecls.push_back(Ivar);
8245}
8246
Fariborz Jahanian343f7092007-09-29 00:54:24 +00008247void Sema::ActOnFields(Scope* S,
John McCall48871652010-08-21 09:40:31 +00008248 SourceLocation RecLoc, Decl *EnclosingDecl,
8249 Decl **Fields, unsigned NumFields,
Daniel Dunbar15619c72008-10-03 02:03:53 +00008250 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar325601a2008-10-03 17:33:35 +00008251 AttributeList *Attr) {
Steve Naroffdb47ee22007-09-14 22:20:54 +00008252 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump11289f42009-09-09 15:08:12 +00008253
Chris Lattnerd13b8b52009-02-23 22:00:08 +00008254 // If the decl this is being inserted into is invalid, then it may be a
8255 // redeclaration or some other bogus case. Don't try to add fields to it.
8256 if (EnclosingDecl->isInvalidDecl()) {
8257 // FIXME: Deallocate fields?
8258 return;
8259 }
8260
Mike Stump11289f42009-09-09 15:08:12 +00008261
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00008262 // Verify that all the fields are okay.
Chris Lattner82625602007-01-24 02:26:21 +00008263 unsigned NumNamedMembers = 0;
Chris Lattner23b7eb62007-06-15 23:05:46 +00008264 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorf4d33272009-01-07 19:46:03 +00008265
Chris Lattnerd13b8b52009-02-23 22:00:08 +00008266 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
John McCall31168b02011-06-15 23:02:42 +00008267 bool ARCErrReported = false;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00008268 for (unsigned i = 0; i != NumFields; ++i) {
John McCall48871652010-08-21 09:40:31 +00008269 FieldDecl *FD = cast<FieldDecl>(Fields[i]);
Mike Stump11289f42009-09-09 15:08:12 +00008270
Chris Lattner720a0542007-01-25 00:44:24 +00008271 // Get the type for the field.
John McCall424cec92011-01-19 06:33:43 +00008272 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorf4d33272009-01-07 19:46:03 +00008273
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008274 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00008275 // Remember all fields written by the user.
8276 RecFields.push_back(FD);
8277 }
Mike Stump11289f42009-09-09 15:08:12 +00008278
Chris Lattner73bf7b42009-03-05 22:45:59 +00008279 // If the field is already invalid for some reason, don't emit more
8280 // diagnostics about it.
Eli Friedmand0e8de22009-12-07 00:22:08 +00008281 if (FD->isInvalidDecl()) {
8282 EnclosingDecl->setInvalidDecl();
Chris Lattner73bf7b42009-03-05 22:45:59 +00008283 continue;
Eli Friedmand0e8de22009-12-07 00:22:08 +00008284 }
Mike Stump11289f42009-09-09 15:08:12 +00008285
Douglas Gregorac1fb652009-03-24 19:52:54 +00008286 // C99 6.7.2.1p2:
8287 // A structure or union shall not contain a member with
8288 // incomplete or function type (hence, a structure shall not
8289 // contain an instance of itself, but may contain a pointer to
8290 // an instance of itself), except that the last member of a
8291 // structure with more than one named member may have incomplete
8292 // array type; such a structure (and any union containing,
8293 // possibly recursively, a member that is such a structure)
8294 // shall not be a member of a structure or an element of an
8295 // array.
Chris Lattner0fd893e2007-07-31 21:33:24 +00008296 if (FDTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00008297 // Field declared as a function.
Chris Lattner651d42d2008-11-20 06:38:18 +00008298 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00008299 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +00008300 FD->setInvalidDecl();
8301 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00008302 continue;
Francois Pichetf657b632010-09-15 00:14:08 +00008303 } else if (FDTy->isIncompleteArrayType() && Record &&
8304 ((i == NumFields - 1 && !Record->isUnion()) ||
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00008305 ((getLangOptions().Microsoft || getLangOptions().CPlusPlus) &&
Francois Pichetf657b632010-09-15 00:14:08 +00008306 (i == NumFields - 1 || Record->isUnion())))) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00008307 // Flexible array member.
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00008308 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichetf657b632010-09-15 00:14:08 +00008309 // It will accept flexible array in union and also
Anders Carlsson0ea10472010-10-17 23:36:12 +00008310 // as the sole element of a struct/class.
Francois Pichetf657b632010-09-15 00:14:08 +00008311 if (getLangOptions().Microsoft) {
8312 if (Record->isUnion())
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00008313 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
Francois Pichetf657b632010-09-15 00:14:08 +00008314 << FD->getDeclName();
8315 else if (NumFields == 1)
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00008316 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
Francois Pichetf657b632010-09-15 00:14:08 +00008317 << FD->getDeclName() << Record->getTagKind();
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00008318 } else if (getLangOptions().CPlusPlus) {
8319 if (Record->isUnion())
8320 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
8321 << FD->getDeclName();
8322 else if (NumFields == 1)
8323 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
8324 << FD->getDeclName() << Record->getTagKind();
8325 } else if (NumNamedMembers < 1) {
Chris Lattner651d42d2008-11-20 06:38:18 +00008326 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00008327 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +00008328 FD->setInvalidDecl();
8329 EnclosingDecl->setInvalidDecl();
Chris Lattner82625602007-01-24 02:26:21 +00008330 continue;
8331 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00008332 if (!FD->getType()->isDependentType() &&
John McCall31168b02011-06-15 23:02:42 +00008333 !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00008334 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
Fariborz Jahanianb0e28472010-05-26 20:46:24 +00008335 << FD->getDeclName() << FD->getType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00008336 FD->setInvalidDecl();
8337 EnclosingDecl->setInvalidDecl();
8338 continue;
8339 }
Chris Lattner720a0542007-01-25 00:44:24 +00008340 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00008341 if (Record)
8342 Record->setHasFlexibleArrayMember(true);
Douglas Gregorac1fb652009-03-24 19:52:54 +00008343 } else if (!FDTy->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00008344 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregorac1fb652009-03-24 19:52:54 +00008345 diag::err_field_incomplete)) {
8346 // Incomplete type
8347 FD->setInvalidDecl();
8348 EnclosingDecl->setInvalidDecl();
8349 continue;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008350 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Chris Lattner720a0542007-01-25 00:44:24 +00008351 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
8352 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00008353 if (Record && Record->isUnion()) {
Chris Lattner41943152007-01-25 04:52:46 +00008354 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00008355 } else {
8356 // If this is a struct/class and this is not the last element, reject
8357 // it. Note that GCC supports variable sized arrays in the middle of
8358 // structures.
Douglas Gregor3e06dbf2009-03-06 23:41:27 +00008359 if (i != NumFields-1)
8360 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattnerb28fe9e2009-04-25 18:52:45 +00008361 << FD->getDeclName() << FD->getType();
Douglas Gregor3e06dbf2009-03-06 23:41:27 +00008362 else {
8363 // We support flexible arrays at the end of structs in
8364 // other structs as an extension.
8365 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
8366 << FD->getDeclName();
8367 if (Record)
8368 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00008369 }
Chris Lattner720a0542007-01-25 00:44:24 +00008370 }
8371 }
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00008372 if (Record && FDTTy->getDecl()->hasObjectMember())
8373 Record->setHasObjectMember(true);
John McCall8b07ec22010-05-15 11:32:37 +00008374 } else if (FDTy->isObjCObjectType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00008375 /// A field cannot be an Objective-c object
Steve Naroff32606412009-02-20 22:59:16 +00008376 Diag(FD->getLocation(), diag::err_statically_allocated_object);
Fariborz Jahanianecfe4f12007-10-12 22:10:42 +00008377 FD->setInvalidDecl();
8378 EnclosingDecl->setInvalidDecl();
8379 continue;
John McCall31168b02011-06-15 23:02:42 +00008380 }
8381 else if (!getLangOptions().CPlusPlus) {
8382 if (getLangOptions().ObjCAutoRefCount && Record && !ARCErrReported) {
8383 // It's an error in ARC if a field has lifetime.
8384 // We don't want to report this in a system header, though,
8385 // so we just make the field unavailable.
8386 // FIXME: that's really not sufficient; we need to make the type
8387 // itself invalid to, say, initialize or copy.
8388 QualType T = FD->getType();
8389 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
8390 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
8391 SourceLocation loc = FD->getLocation();
8392 if (getSourceManager().isInSystemHeader(loc)) {
8393 if (!FD->hasAttr<UnavailableAttr>()) {
8394 FD->addAttr(new (Context) UnavailableAttr(loc, Context,
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008395 "this system field has retaining ownership"));
John McCall31168b02011-06-15 23:02:42 +00008396 }
8397 } else {
8398 Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct);
8399 }
8400 ARCErrReported = true;
8401 }
8402 }
8403 else if (getLangOptions().ObjC1 &&
Mike Stump12b8ce12009-08-04 21:02:39 +00008404 getLangOptions().getGCMode() != LangOptions::NonGC &&
John McCall31168b02011-06-15 23:02:42 +00008405 Record && !Record->hasObjectMember()) {
8406 if (FD->getType()->isObjCObjectPointerType() ||
8407 FD->getType().isObjCGCStrong())
8408 Record->setHasObjectMember(true);
8409 else if (Context.getAsArrayType(FD->getType())) {
8410 QualType BaseType = Context.getBaseElementType(FD->getType());
8411 if (BaseType->isRecordType() &&
8412 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
8413 Record->setHasObjectMember(true);
8414 else if (BaseType->isObjCObjectPointerType() ||
8415 BaseType.isObjCGCStrong())
8416 Record->setHasObjectMember(true);
8417 }
8418 }
Fariborz Jahanian021510e2010-06-15 22:44:06 +00008419 }
Chris Lattner82625602007-01-24 02:26:21 +00008420 // Keep track of the number of named members.
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008421 if (FD->getIdentifier())
Chris Lattner82625602007-01-24 02:26:21 +00008422 ++NumNamedMembers;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00008423 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00008424
Chris Lattner82625602007-01-24 02:26:21 +00008425 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +00008426 if (Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00008427 bool Completed = false;
8428 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
8429 if (!CXXRecord->isInvalidDecl()) {
8430 // Set access bits correctly on the directly-declared conversions.
8431 UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions();
8432 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end();
8433 I != E; ++I)
8434 Convs->setAccess(I, (*I)->getAccess());
8435
8436 if (!CXXRecord->isDependentType()) {
John McCall31168b02011-06-15 23:02:42 +00008437 // Objective-C Automatic Reference Counting:
8438 // If a class has a non-static data member of Objective-C pointer
8439 // type (or array thereof), it is a non-POD type and its
8440 // default constructor (if any), copy constructor, copy assignment
8441 // operator, and destructor are non-trivial.
8442 //
8443 // This rule is also handled by CXXRecordDecl::completeDefinition().
8444 // However, here we check whether this particular class is only
8445 // non-POD because of the presence of an Objective-C pointer member.
8446 // If so, objects of this type cannot be shared between code compiled
8447 // with instant objects and code compiled with manual retain/release.
8448 if (getLangOptions().ObjCAutoRefCount &&
8449 CXXRecord->hasObjectMember() &&
8450 CXXRecord->getLinkage() == ExternalLinkage) {
8451 if (CXXRecord->isPOD()) {
8452 Diag(CXXRecord->getLocation(),
8453 diag::warn_arc_non_pod_class_with_object_member)
8454 << CXXRecord;
8455 } else {
8456 // FIXME: Fix-Its would be nice here, but finding a good location
8457 // for them is going to be tricky.
8458 if (CXXRecord->hasTrivialCopyConstructor())
8459 Diag(CXXRecord->getLocation(),
8460 diag::warn_arc_trivial_member_function_with_object_member)
8461 << CXXRecord << 0;
8462 if (CXXRecord->hasTrivialCopyAssignment())
8463 Diag(CXXRecord->getLocation(),
8464 diag::warn_arc_trivial_member_function_with_object_member)
8465 << CXXRecord << 1;
8466 if (CXXRecord->hasTrivialDestructor())
8467 Diag(CXXRecord->getLocation(),
8468 diag::warn_arc_trivial_member_function_with_object_member)
8469 << CXXRecord << 2;
8470 }
8471 }
8472
Sebastian Redl623ea822011-05-19 05:13:44 +00008473 // Adjust user-defined destructor exception spec.
8474 if (getLangOptions().CPlusPlus0x &&
8475 CXXRecord->hasUserDeclaredDestructor())
8476 AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor());
8477
Douglas Gregor8fb95122010-09-29 00:15:42 +00008478 // Add any implicitly-declared members to this class.
8479 AddImplicitlyDeclaredMembersToClass(CXXRecord);
8480
8481 // If we have virtual base classes, we may end up finding multiple
8482 // final overriders for a given virtual function. Check for this
8483 // problem now.
8484 if (CXXRecord->getNumVBases()) {
8485 CXXFinalOverriderMap FinalOverriders;
8486 CXXRecord->getFinalOverriders(FinalOverriders);
8487
8488 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
8489 MEnd = FinalOverriders.end();
8490 M != MEnd; ++M) {
8491 for (OverridingMethods::iterator SO = M->second.begin(),
8492 SOEnd = M->second.end();
8493 SO != SOEnd; ++SO) {
8494 assert(SO->second.size() > 0 &&
8495 "Virtual function without overridding functions?");
8496 if (SO->second.size() == 1)
8497 continue;
8498
8499 // C++ [class.virtual]p2:
8500 // In a derived class, if a virtual member function of a base
8501 // class subobject has more than one final overrider the
8502 // program is ill-formed.
8503 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
8504 << (NamedDecl *)M->first << Record;
8505 Diag(M->first->getLocation(),
8506 diag::note_overridden_virtual_function);
8507 for (OverridingMethods::overriding_iterator
8508 OM = SO->second.begin(),
8509 OMEnd = SO->second.end();
8510 OM != OMEnd; ++OM)
8511 Diag(OM->Method->getLocation(), diag::note_final_overrider)
8512 << (NamedDecl *)M->first << OM->Method->getParent();
8513
8514 Record->setInvalidDecl();
8515 }
8516 }
8517 CXXRecord->completeDefinition(&FinalOverriders);
8518 Completed = true;
8519 }
8520 }
8521 }
8522 }
8523
8524 if (!Completed)
8525 Record->completeDefinition();
Sebastian Redl623ea822011-05-19 05:13:44 +00008526
8527 // Now that the record is complete, do any delayed exception spec checks
8528 // we were missing.
Richard Smith938f40b2011-06-11 17:19:42 +00008529 while (!DelayedDestructorExceptionSpecChecks.empty()) {
Sebastian Redl623ea822011-05-19 05:13:44 +00008530 const CXXDestructorDecl *Dtor =
8531 DelayedDestructorExceptionSpecChecks.back().first;
Richard Smith938f40b2011-06-11 17:19:42 +00008532 if (Dtor->getParent() != Record)
8533 break;
8534
8535 assert(!Dtor->getParent()->isDependentType() &&
8536 "Should not ever add destructors of templates into the list.");
8537 CheckOverridingFunctionExceptionSpec(Dtor,
8538 DelayedDestructorExceptionSpecChecks.back().second);
8539 DelayedDestructorExceptionSpecChecks.pop_back();
Sebastian Redl623ea822011-05-19 05:13:44 +00008540 }
8541
Chris Lattner622c1932008-02-06 00:51:33 +00008542 } else {
Jay Foad7d0479f2009-05-21 09:52:38 +00008543 ObjCIvarDecl **ClsFields =
8544 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian02225532008-12-13 20:28:25 +00008545 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattner22298722009-02-20 21:35:13 +00008546 ID->setLocEnd(RBrac);
Fariborz Jahanian68453832009-06-05 18:16:35 +00008547 // Add ivar's to class's DeclContext.
8548 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
8549 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008550 ID->addDecl(ClsFields[i]);
Fariborz Jahanian68453832009-06-05 18:16:35 +00008551 }
Fariborz Jahaniana599c132008-12-16 01:08:35 +00008552 // Must enforce the rule that ivars in the base classes may not be
8553 // duplicates.
Fariborz Jahanian545643c2010-02-23 23:41:11 +00008554 if (ID->getSuperClass())
8555 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump11289f42009-09-09 15:08:12 +00008556 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattnerd13b8b52009-02-23 22:00:08 +00008557 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00008558 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian68453832009-06-05 18:16:35 +00008559 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
8560 // Ivar declared in @implementation never belongs to the implementation.
8561 // Only it is in implementation's lexical context.
Douglas Gregor5f662052009-04-23 03:23:08 +00008562 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian95b60762007-10-31 18:48:14 +00008563 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +00008564 } else if (ObjCCategoryDecl *CDecl =
8565 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00008566 // case of ivars in class extension; all other cases have been
8567 // reported as errors elsewhere.
8568 // FIXME. Class extension does not have a LocEnd field.
8569 // CDecl->setLocEnd(RBrac);
8570 // Add ivar's to class extension's DeclContext.
8571 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
8572 ClsFields[i]->setLexicalDeclContext(CDecl);
8573 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +00008574 }
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +00008575 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +00008576 }
Daniel Dunbar325601a2008-10-03 17:33:35 +00008577
8578 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00008579 ProcessDeclAttributeList(S, Record, Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00008580
8581 // If there's a #pragma GCC visibility in scope, and this isn't a subclass,
8582 // set the visibility of this record.
8583 if (Record && !Record->getDeclContext()->isRecord())
8584 AddPushedVisibilityAttribute(Record);
Chris Lattner1300fb92007-01-23 23:42:53 +00008585}
8586
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008587/// \brief Determine whether the given integral value is representable within
8588/// the given type T.
8589static bool isRepresentableIntegerValue(ASTContext &Context,
8590 llvm::APSInt &Value,
8591 QualType T) {
Douglas Gregor6972a622010-06-16 00:35:25 +00008592 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregorc1cf8142010-04-15 15:53:31 +00008593 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008594
Douglas Gregor0bf31402010-10-08 23:50:27 +00008595 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00008596 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor0bf31402010-10-08 23:50:27 +00008597 --BitWidth;
8598 return Value.getActiveBits() <= BitWidth;
8599 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008600 return Value.getMinSignedBits() <= BitWidth;
8601}
8602
8603// \brief Given an integral type, return the next larger integral type
8604// (or a NULL type of no such type exists).
8605static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
8606 // FIXME: Int128/UInt128 support, which also needs to be introduced into
8607 // enum checking below.
Douglas Gregor6972a622010-06-16 00:35:25 +00008608 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008609 const unsigned NumTypes = 4;
8610 QualType SignedIntegralTypes[NumTypes] = {
8611 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
8612 };
8613 QualType UnsignedIntegralTypes[NumTypes] = {
8614 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
8615 Context.UnsignedLongLongTy
8616 };
8617
8618 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00008619 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
8620 : UnsignedIntegralTypes;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008621 for (unsigned I = 0; I != NumTypes; ++I)
8622 if (Context.getTypeSize(Types[I]) > BitWidth)
8623 return Types[I];
8624
8625 return QualType();
8626}
8627
Douglas Gregor954f6b272009-03-17 19:05:46 +00008628EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
8629 EnumConstantDecl *LastEnumConst,
8630 SourceLocation IdLoc,
8631 IdentifierInfo *Id,
John McCallb268a282010-08-23 23:25:46 +00008632 Expr *Val) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008633 unsigned IntWidth = Context.Target.getIntWidth();
8634 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor954f6b272009-03-17 19:05:46 +00008635 QualType EltTy;
Douglas Gregor2b988fd2010-12-16 00:24:44 +00008636
8637 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
8638 Val = 0;
8639
Douglas Gregorb2186fe2009-11-06 00:03:12 +00008640 if (Val) {
Douglas Gregordc70c3a2010-03-02 17:53:14 +00008641 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregorb2186fe2009-11-06 00:03:12 +00008642 EltTy = Context.DependentTy;
8643 else {
Douglas Gregorb2186fe2009-11-06 00:03:12 +00008644 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
8645 SourceLocation ExpLoc;
Douglas Gregordc70c3a2010-03-02 17:53:14 +00008646 if (!Val->isValueDependent() &&
8647 VerifyIntegerConstantExpression(Val, &EnumVal)) {
Douglas Gregorb2186fe2009-11-06 00:03:12 +00008648 Val = 0;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008649 } else {
8650 if (!getLangOptions().CPlusPlus) {
8651 // C99 6.7.2.2p2:
8652 // The expression that defines the value of an enumeration constant
8653 // shall be an integer constant expression that has a value
8654 // representable as an int.
8655
8656 // Complain if the value is not representable in an int.
8657 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
8658 Diag(IdLoc, diag::ext_enum_value_not_int)
8659 << EnumVal.toString(10) << Val->getSourceRange()
Douglas Gregorc0b8c812010-02-17 22:40:11 +00008660 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008661 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
8662 // Force the type of the expression to 'int'.
John Wiegley01296292011-04-08 18:41:53 +00008663 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008664 }
8665 }
8666
Douglas Gregor0bf31402010-10-08 23:50:27 +00008667 if (Enum->isFixed()) {
8668 EltTy = Enum->getIntegerType();
8669
8670 // C++0x [dcl.enum]p5:
8671 // ... if the initializing value of an enumerator cannot be
8672 // represented by the underlying type, the program is ill-formed.
Francois Picheta3108062010-10-18 15:01:13 +00008673 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
8674 if (getLangOptions().Microsoft) {
8675 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
John Wiegley01296292011-04-08 18:41:53 +00008676 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Francois Picheta3108062010-10-18 15:01:13 +00008677 } else
8678 Diag(IdLoc, diag::err_enumerator_too_large)
8679 << EltTy;
8680 } else
John Wiegley01296292011-04-08 18:41:53 +00008681 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008682 }
8683 else {
8684 // C++0x [dcl.enum]p5:
8685 // If the underlying type is not fixed, the type of each enumerator
8686 // is the type of its initializing value:
8687 // - If an initializer is specified for an enumerator, the
8688 // initializing value has the same type as the expression.
8689 EltTy = Val->getType();
8690 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +00008691 }
Douglas Gregor954f6b272009-03-17 19:05:46 +00008692 }
8693 }
Mike Stump11289f42009-09-09 15:08:12 +00008694
Douglas Gregor954f6b272009-03-17 19:05:46 +00008695 if (!Val) {
Eli Friedmand0e60972009-12-11 01:34:50 +00008696 if (Enum->isDependentType())
8697 EltTy = Context.DependentTy;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008698 else if (!LastEnumConst) {
8699 // C++0x [dcl.enum]p5:
8700 // If the underlying type is not fixed, the type of each enumerator
8701 // is the type of its initializing value:
8702 // - If no initializer is specified for the first enumerator, the
8703 // initializing value has an unspecified integral type.
8704 //
8705 // GCC uses 'int' for its unspecified integral type, as does
8706 // C99 6.7.2.2p3.
Douglas Gregor0bf31402010-10-08 23:50:27 +00008707 if (Enum->isFixed()) {
8708 EltTy = Enum->getIntegerType();
8709 }
8710 else {
8711 EltTy = Context.IntTy;
8712 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008713 } else {
Douglas Gregor954f6b272009-03-17 19:05:46 +00008714 // Assign the last value + 1.
8715 EnumVal = LastEnumConst->getInitVal();
8716 ++EnumVal;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008717 EltTy = LastEnumConst->getType();
Douglas Gregor954f6b272009-03-17 19:05:46 +00008718
8719 // Check for overflow on increment.
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008720 if (EnumVal < LastEnumConst->getInitVal()) {
8721 // C++0x [dcl.enum]p5:
8722 // If the underlying type is not fixed, the type of each enumerator
8723 // is the type of its initializing value:
8724 //
8725 // - Otherwise the type of the initializing value is the same as
8726 // the type of the initializing value of the preceding enumerator
8727 // unless the incremented value is not representable in that type,
8728 // in which case the type is an unspecified integral type
8729 // sufficient to contain the incremented value. If no such type
8730 // exists, the program is ill-formed.
8731 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor0bf31402010-10-08 23:50:27 +00008732 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008733 // There is no integral type larger enough to represent this
8734 // value. Complain, then allow the value to wrap around.
8735 EnumVal = LastEnumConst->getInitVal();
Jay Foad6d4db0c2010-12-07 08:25:34 +00008736 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor0bf31402010-10-08 23:50:27 +00008737 ++EnumVal;
8738 if (Enum->isFixed())
8739 // When the underlying type is fixed, this is ill-formed.
8740 Diag(IdLoc, diag::err_enumerator_wrapped)
8741 << EnumVal.toString(10)
8742 << EltTy;
8743 else
8744 Diag(IdLoc, diag::warn_enumerator_too_large)
8745 << EnumVal.toString(10);
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008746 } else {
8747 EltTy = T;
8748 }
8749
8750 // Retrieve the last enumerator's value, extent that type to the
8751 // type that is supposed to be large enough to represent the incremented
8752 // value, then increment.
8753 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00008754 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad6d4db0c2010-12-07 08:25:34 +00008755 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008756 ++EnumVal;
8757
8758 // If we're not in C++, diagnose the overflow of enumerator values,
8759 // which in C99 means that the enumerator value is not representable in
8760 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
8761 // permits enumerator values that are representable in some larger
8762 // integral type.
8763 if (!getLangOptions().CPlusPlus && !T.isNull())
8764 Diag(IdLoc, diag::warn_enum_value_overflow);
8765 } else if (!getLangOptions().CPlusPlus &&
8766 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
8767 // Enforce C99 6.7.2.2p2 even when we compute the next value.
8768 Diag(IdLoc, diag::ext_enum_value_not_int)
8769 << EnumVal.toString(10) << 1;
8770 }
Douglas Gregor954f6b272009-03-17 19:05:46 +00008771 }
8772 }
Mike Stump11289f42009-09-09 15:08:12 +00008773
Douglas Gregordc70c3a2010-03-02 17:53:14 +00008774 if (!EltTy->isDependentType()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008775 // Make the enumerator value match the signedness and size of the
8776 // enumerator's type.
Jay Foad6d4db0c2010-12-07 08:25:34 +00008777 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00008778 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008779 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +00008780
Douglas Gregor954f6b272009-03-17 19:05:46 +00008781 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump11289f42009-09-09 15:08:12 +00008782 Val, EnumVal);
Douglas Gregor954f6b272009-03-17 19:05:46 +00008783}
8784
8785
John McCall811a0f52010-10-22 23:36:17 +00008786Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
8787 SourceLocation IdLoc, IdentifierInfo *Id,
8788 AttributeList *Attr,
8789 SourceLocation EqualLoc, ExprTy *val) {
John McCall48871652010-08-21 09:40:31 +00008790 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Chris Lattner4ef40012007-06-11 01:28:17 +00008791 EnumConstantDecl *LastEnumConst =
John McCall48871652010-08-21 09:40:31 +00008792 cast_or_null<EnumConstantDecl>(lastEnumConst);
Chris Lattner4ef40012007-06-11 01:28:17 +00008793 Expr *Val = static_cast<Expr*>(val);
Chris Lattner8116d1b2007-01-25 22:38:29 +00008794
Chris Lattner1a76a3c2007-08-26 06:24:45 +00008795 // The scope passed in may not be a decl scope. Zip up the scope tree until
8796 // we find one that is.
Douglas Gregor45a33ec2009-01-12 18:45:55 +00008797 S = getNonFieldDeclScope(S);
Mike Stump11289f42009-09-09 15:08:12 +00008798
Chris Lattner8116d1b2007-01-25 22:38:29 +00008799 // Verify that there isn't already something declared with this name in this
8800 // scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00008801 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregor5204248f2010-01-19 06:06:57 +00008802 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +00008803 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00008804 // Maybe we will complain about the shadowed template parameter.
8805 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
8806 // Just pretend that we didn't see the previous declaration.
8807 PrevDecl = 0;
8808 }
8809
8810 if (PrevDecl) {
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +00008811 // When in C++, we may get a TagDecl with the same name; in this case the
8812 // enum constant will 'hide' the tag.
8813 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
8814 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis5b144d52008-09-09 21:18:04 +00008815 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +00008816 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner4bd8dd82008-11-19 08:23:25 +00008817 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner8116d1b2007-01-25 22:38:29 +00008818 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +00008819 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner0369c572008-11-23 23:12:31 +00008820 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00008821 return 0;
Chris Lattner8116d1b2007-01-25 22:38:29 +00008822 }
8823 }
Chris Lattner4ef40012007-06-11 01:28:17 +00008824
Douglas Gregor36c22a22010-10-15 13:21:21 +00008825 // C++ [class.mem]p13:
8826 // If T is the name of a class, then each of the following shall have a
8827 // name different from T:
8828 // - every enumerator of every member of class T that is an enumerated
8829 // type
8830 if (CXXRecordDecl *Record
8831 = dyn_cast<CXXRecordDecl>(
8832 TheEnumDecl->getDeclContext()->getRedeclContext()))
8833 if (Record->getIdentifier() && Record->getIdentifier() == Id)
8834 Diag(IdLoc, diag::err_member_name_of_class) << Id;
8835
John McCall811a0f52010-10-22 23:36:17 +00008836 EnumConstantDecl *New =
8837 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner0515e4b2007-08-27 21:16:18 +00008838
John McCall553c0792010-01-23 00:46:32 +00008839 if (New) {
John McCall811a0f52010-10-22 23:36:17 +00008840 // Process attributes.
8841 if (Attr) ProcessDeclAttributeList(S, New, Attr);
8842
8843 // Register this decl in the current scope stack.
John McCall553c0792010-01-23 00:46:32 +00008844 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor954f6b272009-03-17 19:05:46 +00008845 PushOnScopeChains(New, S);
John McCall553c0792010-01-23 00:46:32 +00008846 }
Douglas Gregor2f521192008-12-17 02:04:30 +00008847
John McCall48871652010-08-21 09:40:31 +00008848 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +00008849}
8850
Mike Stump6814d1c2009-05-16 07:06:02 +00008851void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCall48871652010-08-21 09:40:31 +00008852 SourceLocation RBraceLoc, Decl *EnumDeclX,
8853 Decl **Elements, unsigned NumElements,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008854 Scope *S, AttributeList *Attr) {
John McCall48871652010-08-21 09:40:31 +00008855 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor07665a62009-01-05 19:45:36 +00008856 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008857
8858 if (Attr)
8859 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump11289f42009-09-09 15:08:12 +00008860
Eli Friedmand0e60972009-12-11 01:34:50 +00008861 if (Enum->isDependentType()) {
8862 for (unsigned i = 0; i != NumElements; ++i) {
8863 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +00008864 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmand0e60972009-12-11 01:34:50 +00008865 if (!ECD) continue;
8866
8867 ECD->setType(EnumType);
8868 }
8869
John McCall9aa35be2010-05-06 08:49:23 +00008870 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmand0e60972009-12-11 01:34:50 +00008871 return;
8872 }
8873
Chris Lattner67933c02007-08-28 05:10:31 +00008874 // TODO: If the result value doesn't fit in an int, it must be a long or long
8875 // long value. ISO C does not support this, but GCC does as an extension,
8876 // emit a warning.
Chris Lattner37e05872008-03-05 18:54:05 +00008877 unsigned IntWidth = Context.Target.getIntWidth();
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008878 unsigned CharWidth = Context.Target.getCharWidth();
8879 unsigned ShortWidth = Context.Target.getShortWidth();
Mike Stump11289f42009-09-09 15:08:12 +00008880
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008881 // Verify that all the values are okay, compute the size of the values, and
8882 // reverse the list.
8883 unsigned NumNegativeBits = 0;
8884 unsigned NumPositiveBits = 0;
Mike Stump11289f42009-09-09 15:08:12 +00008885
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008886 // Keep track of whether all elements have type int.
8887 bool AllElementsInt = true;
Mike Stump11289f42009-09-09 15:08:12 +00008888
Chris Lattnerc1915e22007-01-25 07:29:02 +00008889 for (unsigned i = 0; i != NumElements; ++i) {
8890 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +00008891 cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerc1915e22007-01-25 07:29:02 +00008892 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump11289f42009-09-09 15:08:12 +00008893
Chris Lattnerbf478cb2007-08-28 05:27:00 +00008894 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump11289f42009-09-09 15:08:12 +00008895
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008896 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +00008897 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +00008898 NumPositiveBits = std::max(NumPositiveBits,
8899 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008900 else
Chris Lattner49f980c2008-01-14 21:47:29 +00008901 NumNegativeBits = std::max(NumNegativeBits,
8902 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +00008903
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008904 // Keep track of whether every enum element has type int (very commmon).
8905 if (AllElementsInt)
Mike Stump11289f42009-09-09 15:08:12 +00008906 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattnerc1915e22007-01-25 07:29:02 +00008907 }
Mike Stump11289f42009-09-09 15:08:12 +00008908
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008909 // Figure out the type that should be used for this enum.
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008910 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +00008911 unsigned BestWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008912
John McCall56774992009-12-09 09:09:27 +00008913 // C++0x N3000 [conv.prom]p3:
8914 // An rvalue of an unscoped enumeration type whose underlying
8915 // type is not fixed can be converted to an rvalue of the first
8916 // of the following types that can represent all the values of
8917 // the enumeration: int, unsigned int, long int, unsigned long
8918 // int, long long int, or unsigned long long int.
8919 // C99 6.4.4.3p2:
8920 // An identifier declared as an enumeration constant has type int.
8921 // The C99 rule is modified by a gcc extension
8922 QualType BestPromotionType;
8923
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008924 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
Argyrios Kyrtzidis74825bc2010-10-08 00:25:19 +00008925 // -fshort-enums is the equivalent to specifying the packed attribute on all
8926 // enum definitions.
8927 if (LangOpts.ShortEnums)
8928 Packed = true;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008929
Douglas Gregor0bf31402010-10-08 23:50:27 +00008930 if (Enum->isFixed()) {
8931 BestType = BestPromotionType = Enum->getIntegerType();
Duncan Sands38b918c2010-10-12 14:07:59 +00008932 // We don't need to set BestWidth, because BestType is going to be the type
8933 // of the enumerators, but we do anyway because otherwise some compilers
8934 // warn that it might be used uninitialized.
8935 BestWidth = CharWidth;
Douglas Gregor0bf31402010-10-08 23:50:27 +00008936 }
8937 else if (NumNegativeBits) {
Mike Stump11289f42009-09-09 15:08:12 +00008938 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008939 // int/long/longlong) that fits.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008940 // If it's packed, check also if it fits a char or a short.
8941 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall56774992009-12-09 09:09:27 +00008942 BestType = Context.SignedCharTy;
8943 BestWidth = CharWidth;
Mike Stump11289f42009-09-09 15:08:12 +00008944 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008945 NumPositiveBits < ShortWidth) {
John McCall56774992009-12-09 09:09:27 +00008946 BestType = Context.ShortTy;
8947 BestWidth = ShortWidth;
8948 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008949 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00008950 BestWidth = IntWidth;
8951 } else {
Chris Lattner37e05872008-03-05 18:54:05 +00008952 BestWidth = Context.Target.getLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +00008953
John McCall56774992009-12-09 09:09:27 +00008954 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008955 BestType = Context.LongTy;
John McCall56774992009-12-09 09:09:27 +00008956 } else {
Chris Lattner37e05872008-03-05 18:54:05 +00008957 BestWidth = Context.Target.getLongLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +00008958
Chris Lattner3a370bf2007-08-29 17:31:48 +00008959 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008960 Diag(Enum->getLocation(), diag::warn_enum_too_large);
8961 BestType = Context.LongLongTy;
8962 }
8963 }
John McCall56774992009-12-09 09:09:27 +00008964 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008965 } else {
Douglas Gregora71cc152010-02-02 20:10:50 +00008966 // If there is no negative value, figure out the smallest type that fits
8967 // all of the enumerator values.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008968 // If it's packed, check also if it fits a char or a short.
8969 if (Packed && NumPositiveBits <= CharWidth) {
John McCall56774992009-12-09 09:09:27 +00008970 BestType = Context.UnsignedCharTy;
8971 BestPromotionType = Context.IntTy;
8972 BestWidth = CharWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008973 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall56774992009-12-09 09:09:27 +00008974 BestType = Context.UnsignedShortTy;
8975 BestPromotionType = Context.IntTy;
8976 BestWidth = ShortWidth;
8977 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008978 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00008979 BestWidth = IntWidth;
Douglas Gregora71cc152010-02-02 20:10:50 +00008980 BestPromotionType
8981 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
8982 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00008983 } else if (NumPositiveBits <=
Chris Lattner37e05872008-03-05 18:54:05 +00008984 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008985 BestType = Context.UnsignedLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +00008986 BestPromotionType
8987 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
8988 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner37e05872008-03-05 18:54:05 +00008989 } else {
8990 BestWidth = Context.Target.getLongLongWidth();
Chris Lattner3a370bf2007-08-29 17:31:48 +00008991 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008992 "How could an initializer get larger than ULL?");
8993 BestType = Context.UnsignedLongLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +00008994 BestPromotionType
8995 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
8996 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008997 }
8998 }
Mike Stump11289f42009-09-09 15:08:12 +00008999
Chris Lattner3a370bf2007-08-29 17:31:48 +00009000 // Loop over all of the enumerator constants, changing their types to match
9001 // the type of the enum if needed.
9002 for (unsigned i = 0; i != NumElements; ++i) {
John McCall48871652010-08-21 09:40:31 +00009003 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattner3a370bf2007-08-29 17:31:48 +00009004 if (!ECD) continue; // Already issued a diagnostic.
9005
9006 // Standard C says the enumerators have int type, but we allow, as an
9007 // extension, the enumerators to be larger than int size. If each
9008 // enumerator value fits in an int, type it as an int, otherwise type it the
9009 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
9010 // that X has type 'int', not 'unsigned'.
Chris Lattner3a370bf2007-08-29 17:31:48 +00009011
9012 // Determine whether the value fits into an int.
9013 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattner3a370bf2007-08-29 17:31:48 +00009014
9015 // If it fits into an integer type, force it. Otherwise force it to match
9016 // the enum decl type.
9017 QualType NewTy;
9018 unsigned NewWidth;
9019 bool NewSign;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00009020 if (!getLangOptions().CPlusPlus &&
9021 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattner3a370bf2007-08-29 17:31:48 +00009022 NewTy = Context.IntTy;
9023 NewWidth = IntWidth;
9024 NewSign = true;
9025 } else if (ECD->getType() == BestType) {
9026 // Already the right type!
Douglas Gregor1d248c52008-12-12 02:00:36 +00009027 if (getLangOptions().CPlusPlus)
9028 // C++ [dcl.enum]p4: Following the closing brace of an
9029 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +00009030 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +00009031 ECD->setType(EnumType);
Chris Lattner3a370bf2007-08-29 17:31:48 +00009032 continue;
9033 } else {
9034 NewTy = BestType;
9035 NewWidth = BestWidth;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00009036 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattner3a370bf2007-08-29 17:31:48 +00009037 }
9038
9039 // Adjust the APSInt value.
Jay Foad6d4db0c2010-12-07 08:25:34 +00009040 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattner3a370bf2007-08-29 17:31:48 +00009041 InitVal.setIsSigned(NewSign);
9042 ECD->setInitVal(InitVal);
Mike Stump11289f42009-09-09 15:08:12 +00009043
Chris Lattner3a370bf2007-08-29 17:31:48 +00009044 // Adjust the Expr initializer and type.
Abramo Bagnara77815432010-12-17 15:49:53 +00009045 if (ECD->getInitExpr() &&
9046 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallcf142162010-08-07 06:22:56 +00009047 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCalle3027922010-08-25 11:45:40 +00009048 CK_IntegralCast,
John McCallcf142162010-08-07 06:22:56 +00009049 ECD->getInitExpr(),
9050 /*base paths*/ 0,
John McCall2536c6d2010-08-25 10:28:54 +00009051 VK_RValue));
Douglas Gregor1d248c52008-12-12 02:00:36 +00009052 if (getLangOptions().CPlusPlus)
9053 // C++ [dcl.enum]p4: Following the closing brace of an
9054 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +00009055 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +00009056 ECD->setType(EnumType);
9057 else
9058 ECD->setType(NewTy);
Chris Lattner3a370bf2007-08-29 17:31:48 +00009059 }
Mike Stump11289f42009-09-09 15:08:12 +00009060
John McCall9aa35be2010-05-06 08:49:23 +00009061 Enum->completeDefinition(BestType, BestPromotionType,
9062 NumPositiveBits, NumNegativeBits);
Chris Lattnerc1915e22007-01-25 07:29:02 +00009063}
Chris Lattner1300fb92007-01-23 23:42:53 +00009064
Abramo Bagnara348823a2011-03-03 14:20:18 +00009065Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
9066 SourceLocation StartLoc,
9067 SourceLocation EndLoc) {
John McCallb268a282010-08-23 23:25:46 +00009068 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redlc675bab2008-12-13 16:23:55 +00009069
Douglas Gregor278f52e2009-05-30 00:08:05 +00009070 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara348823a2011-03-03 14:20:18 +00009071 AsmString, StartLoc,
9072 EndLoc);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009073 CurContext->addDecl(New);
John McCall48871652010-08-21 09:40:31 +00009074 return New;
Anders Carlsson5c6c0592008-02-08 00:33:21 +00009075}
Eli Friedman5ed51982009-06-05 02:44:36 +00009076
9077void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
9078 SourceLocation PragmaLoc,
9079 SourceLocation NameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00009080 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedman5ed51982009-06-05 02:44:36 +00009081
Eli Friedman5ed51982009-06-05 02:44:36 +00009082 if (PrevDecl) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00009083 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
Ryan Flynn7d470f32009-07-30 03:15:39 +00009084 } else {
9085 (void)WeakUndeclaredIdentifiers.insert(
9086 std::pair<IdentifierInfo*,WeakInfo>
9087 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedman5ed51982009-06-05 02:44:36 +00009088 }
Eli Friedman5ed51982009-06-05 02:44:36 +00009089}
9090
9091void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
9092 IdentifierInfo* AliasName,
9093 SourceLocation PragmaLoc,
9094 SourceLocation NameLoc,
9095 SourceLocation AliasNameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00009096 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
9097 LookupOrdinaryName);
Ryan Flynn7d470f32009-07-30 03:15:39 +00009098 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedman5ed51982009-06-05 02:44:36 +00009099
Eli Friedman5ed51982009-06-05 02:44:36 +00009100 if (PrevDecl) {
Ryan Flynn7d470f32009-07-30 03:15:39 +00009101 if (!PrevDecl->hasAttr<AliasAttr>())
9102 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynnd963a492009-07-31 02:52:19 +00009103 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynn7d470f32009-07-30 03:15:39 +00009104 } else {
9105 (void)WeakUndeclaredIdentifiers.insert(
9106 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedman5ed51982009-06-05 02:44:36 +00009107 }
Eli Friedman5ed51982009-06-05 02:44:36 +00009108}