blob: 9d91a48bdcd76f613ed2ce9710c6ec2fd3d6ab2f [file] [log] [blame]
Chris Lattner697e5d62006-11-09 06:32:27 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner697e5d62006-11-09 06:32:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
John McCallcc14d1f2010-08-24 08:50:51 +000017#include "clang/Sema/CXXFieldCollector.h"
18#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
Douglas Gregor844cb502011-03-01 18:12:44 +000020#include "TypeLocBuilder.h"
Anders Carlsson7a241ba2008-07-03 04:20:39 +000021#include "clang/AST/APValue.h"
Chris Lattner622c1932008-02-06 00:51:33 +000022#include "clang/AST/ASTConsumer.h"
Chris Lattner5c5fbcc2006-12-03 08:41:30 +000023#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000024#include "clang/AST/CXXInheritance.h"
John McCall28a0cf72010-08-25 07:42:41 +000025#include "clang/AST/DeclCXX.h"
John McCallde6836a2010-08-24 07:21:54 +000026#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000027#include "clang/AST/DeclTemplate.h"
Chandler Carruth33bf3e72011-03-27 09:46:56 +000028#include "clang/AST/EvaluatedExprVisitor.h"
Chris Lattner2c6fcf52008-06-26 18:38:35 +000029#include "clang/AST/ExprCXX.h"
Sebastian Redla7b98a72009-04-26 20:35:05 +000030#include "clang/AST/StmtCXX.h"
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +000031#include "clang/AST/CharUnits.h"
John McCall8b0666c2010-08-20 18:27:03 +000032#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/ParsedTemplate.h"
Douglas Gregor15e56022009-10-13 23:27:22 +000034#include "clang/Parse/ParseDiagnostic.h"
Anders Carlssond624e162009-08-26 23:45:07 +000035#include "clang/Basic/PartialDiagnostic.h"
Steve Naroffe101f952008-01-30 23:46:05 +000036#include "clang/Basic/SourceManager.h"
Anders Carlssond624e162009-08-26 23:45:07 +000037#include "clang/Basic/TargetInfo.h"
Steve Naroffe101f952008-01-30 23:46:05 +000038// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattner622c1932008-02-06 00:51:33 +000039#include "clang/Lex/Preprocessor.h"
Mike Stump11289f42009-09-09 15:08:12 +000040#include "clang/Lex/HeaderSearch.h"
John McCall0e21fcc2009-12-24 09:58:38 +000041#include "llvm/ADT/Triple.h"
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000042#include <algorithm>
Douglas Gregor56fbc372009-09-28 21:14:19 +000043#include <cstring>
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000044#include <functional>
Chris Lattner697e5d62006-11-09 06:32:27 +000045using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000046using namespace sema;
Chris Lattner697e5d62006-11-09 06:32:27 +000047
Richard Smithcd1c0552011-07-01 19:46:12 +000048Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
49 if (OwnedType) {
50 Decl *Group[2] = { OwnedType, Ptr };
51 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
52 }
53
John McCall48871652010-08-21 09:40:31 +000054 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
Chris Lattner5bbb3c82009-03-29 16:50:03 +000055}
56
Douglas Gregorec6e1892009-02-04 19:16:12 +000057/// \brief If the identifier refers to a type name within this scope,
58/// return the declaration of that type.
59///
60/// This routine performs ordinary name lookup of the identifier II
61/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor9817f4a2009-02-09 15:09:02 +000062/// determine whether the name refers to a type. If so, returns an
63/// opaque pointer (actually a QualType) corresponding to that
64/// type. Otherwise, returns NULL.
Douglas Gregorec6e1892009-02-04 19:16:12 +000065///
66/// If name lookup results in an ambiguity, this routine will complain
67/// and then return NULL.
John McCallba7bf592010-08-24 05:47:05 +000068ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
69 Scope *S, CXXScopeSpec *SS,
Fariborz Jahanian87967422011-02-08 18:05:59 +000070 bool isClassName, bool HasTrailingDot,
Douglas Gregor844cb502011-03-01 18:12:44 +000071 ParsedType ObjectTypePtr,
72 bool WantNontrivialTypeSourceInfo) {
Douglas Gregora25d65d2009-11-20 22:03:38 +000073 // Determine where we will perform name lookup.
74 DeclContext *LookupCtx = 0;
75 if (ObjectTypePtr) {
John McCallba7bf592010-08-24 05:47:05 +000076 QualType ObjectType = ObjectTypePtr.get();
Douglas Gregora25d65d2009-11-20 22:03:38 +000077 if (ObjectType->isRecordType())
78 LookupCtx = computeDeclContext(ObjectType);
Jeffrey Yasskin4e150f82010-04-07 23:29:58 +000079 } else if (SS && SS->isNotEmpty()) {
Douglas Gregora25d65d2009-11-20 22:03:38 +000080 LookupCtx = computeDeclContext(*SS, false);
81
82 if (!LookupCtx) {
83 if (isDependentScopeSpecifier(*SS)) {
84 // C++ [temp.res]p3:
85 // A qualified-id that refers to a type and in which the
86 // nested-name-specifier depends on a template-parameter (14.6.2)
87 // shall be prefixed by the keyword typename to indicate that the
88 // qualified-id denotes a type, forming an
89 // elaborated-type-specifier (7.1.5.3).
90 //
91 // We therefore do not perform any name lookup if the result would
92 // refer to a member of an unknown specialization.
93 if (!isClassName)
John McCallba7bf592010-08-24 05:47:05 +000094 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +000095
John McCallc392f372010-06-11 00:33:02 +000096 // We know from the grammar that this name refers to a type,
97 // so build a dependent node to describe the type.
Douglas Gregor844cb502011-03-01 18:12:44 +000098 if (WantNontrivialTypeSourceInfo)
99 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
100
101 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
John McCallba7bf592010-08-24 05:47:05 +0000102 QualType T =
Douglas Gregor844cb502011-03-01 18:12:44 +0000103 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000104 II, NameLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +0000105
106 return ParsedType::make(T);
Douglas Gregora25d65d2009-11-20 22:03:38 +0000107 }
108
John McCallba7bf592010-08-24 05:47:05 +0000109 return ParsedType();
Douglas Gregora25d65d2009-11-20 22:03:38 +0000110 }
111
John McCall0b66eb32010-05-01 00:40:08 +0000112 if (!LookupCtx->isDependentContext() &&
113 RequireCompleteDeclContext(*SS, LookupCtx))
John McCallba7bf592010-08-24 05:47:05 +0000114 return ParsedType();
Douglas Gregor5e0962f2009-08-26 18:27:52 +0000115 }
Eli Friedman9025ec22009-12-21 01:42:38 +0000116
117 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
118 // lookup for class-names.
119 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
120 LookupOrdinaryName;
121 LookupResult Result(*this, &II, NameLoc, Kind);
Douglas Gregora25d65d2009-11-20 22:03:38 +0000122 if (LookupCtx) {
123 // Perform "qualified" name lookup into the declaration context we
124 // computed, which is either the type of the base of a member access
125 // expression or the declaration context associated with a prior
126 // nested-name-specifier.
127 LookupQualifiedName(Result, LookupCtx);
Douglas Gregorc9f9b862009-05-11 19:58:34 +0000128
Douglas Gregora25d65d2009-11-20 22:03:38 +0000129 if (ObjectTypePtr && Result.empty()) {
130 // C++ [basic.lookup.classref]p3:
131 // If the unqualified-id is ~type-name, the type-name is looked up
132 // in the context of the entire postfix-expression. If the type T of
133 // the object expression is of a class type C, the type-name is also
134 // looked up in the scope of class C. At least one of the lookups shall
135 // find a name that refers to (possibly cv-qualified) T.
136 LookupName(Result, S);
137 }
138 } else {
139 // Perform unqualified name lookup.
140 LookupName(Result, S);
141 }
142
Chris Lattnera3778332009-02-16 22:07:16 +0000143 NamedDecl *IIDecl = 0;
John McCall27b18f82009-11-17 02:14:36 +0000144 switch (Result.getResultKind()) {
Chris Lattnera3778332009-02-16 22:07:16 +0000145 case LookupResult::NotFound:
Douglas Gregord0d2ee02010-01-15 01:44:47 +0000146 case LookupResult::NotFoundInCurrentInstantiation:
Chris Lattnera3778332009-02-16 22:07:16 +0000147 case LookupResult::FoundOverloaded:
John McCalle61f2ba2009-11-18 02:36:19 +0000148 case LookupResult::FoundUnresolvedValue:
John McCall58cc69d2010-01-27 01:50:18 +0000149 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000150 return ParsedType();
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000151
Chris Lattnere40853a2009-10-25 22:09:09 +0000152 case LookupResult::Ambiguous:
John McCall6538c932009-10-10 05:48:19 +0000153 // Recover from type-hiding ambiguities by hiding the type. We'll
154 // do the lookup again when looking for an object, and we can
155 // diagnose the error then. If we don't do this, then the error
156 // about hiding the type will be immediately followed by an error
157 // that only makes sense if the identifier was treated like a type.
John McCall27b18f82009-11-17 02:14:36 +0000158 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
159 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000160 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000161 }
John McCall6538c932009-10-10 05:48:19 +0000162
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000163 // Look to see if we have a type anywhere in the list of results.
164 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
165 Res != ResEnd; ++Res) {
166 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
Mike Stump11289f42009-09-09 15:08:12 +0000167 if (!IIDecl ||
168 (*Res)->getLocation().getRawEncoding() <
Douglas Gregor712a3512009-04-13 15:14:38 +0000169 IIDecl->getLocation().getRawEncoding())
170 IIDecl = *Res;
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000171 }
172 }
173
174 if (!IIDecl) {
175 // None of the entities we found is a type, so there is no way
176 // to even assume that the result is a type. In this case, don't
177 // complain about the ambiguity. The parser will either try to
178 // perform this lookup again (e.g., as an object name), which
179 // will produce the ambiguity, or will complain that it expected
180 // a type name.
John McCall27b18f82009-11-17 02:14:36 +0000181 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000182 return ParsedType();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000183 }
184
185 // We found a type within the ambiguous lookup; diagnose the
186 // ambiguity and then return that type. This might be the right
187 // answer, or it might not be, but it suppresses any attempt to
188 // perform the name lookup again.
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000189 break;
Douglas Gregor8a6be5e2009-02-04 17:00:24 +0000190
Chris Lattnera3778332009-02-16 22:07:16 +0000191 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +0000192 IIDecl = Result.getFoundDecl();
Chris Lattnera3778332009-02-16 22:07:16 +0000193 break;
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000194 }
195
Chris Lattner17e15f12009-10-25 17:16:46 +0000196 assert(IIDecl && "Didn't find decl");
John McCall28a6aea2009-11-04 02:18:39 +0000197
Chris Lattner17e15f12009-10-25 17:16:46 +0000198 QualType T;
199 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
John McCall28a6aea2009-11-04 02:18:39 +0000200 DiagnoseUseOfDecl(IIDecl, NameLoc);
John McCall27b18f82009-11-17 02:14:36 +0000201
Chris Lattner17e15f12009-10-25 17:16:46 +0000202 if (T.isNull())
203 T = Context.getTypeDeclType(TD);
204
Douglas Gregor844cb502011-03-01 18:12:44 +0000205 if (SS && SS->isNotEmpty()) {
206 if (WantNontrivialTypeSourceInfo) {
207 // Construct a type with type-source information.
208 TypeLocBuilder Builder;
209 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
210
211 T = getElaboratedType(ETK_None, *SS, T);
212 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
213 ElabTL.setKeywordLoc(SourceLocation());
214 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
215 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
216 } else {
217 T = getElaboratedType(ETK_None, *SS, T);
218 }
219 }
Chris Lattner17e15f12009-10-25 17:16:46 +0000220 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
Fariborz Jahanian08891f52011-03-08 19:12:46 +0000221 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
Fariborz Jahanian87967422011-02-08 18:05:59 +0000222 if (!HasTrailingDot)
223 T = Context.getObjCInterfaceType(IDecl);
224 }
225
226 if (T.isNull()) {
John McCall27b18f82009-11-17 02:14:36 +0000227 // If it's not plausibly a type, suppress diagnostics.
228 Result.suppressDiagnostics();
John McCallba7bf592010-08-24 05:47:05 +0000229 return ParsedType();
John McCall27b18f82009-11-17 02:14:36 +0000230 }
John McCallba7bf592010-08-24 05:47:05 +0000231 return ParsedType::make(T);
Chris Lattnere168f762006-11-10 05:29:30 +0000232}
233
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000234/// isTagName() - This method is called *for error recovery purposes only*
235/// to determine if the specified name is a valid tag name ("struct foo"). If
236/// so, this returns the TST for the tag corresponding to it (TST_enum,
237/// TST_union, TST_struct, TST_class). This is used to diagnose cases in C
238/// where the user forgot to specify the tag.
239DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
240 // Do a tag name lookup in this scope.
John McCall27b18f82009-11-17 02:14:36 +0000241 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
242 LookupName(R, S, false);
243 R.suppressDiagnostics();
244 if (R.getResultKind() == LookupResult::Found)
John McCall67c00872009-12-02 08:25:40 +0000245 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000246 switch (TD->getTagKind()) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000247 default: return DeclSpec::TST_unspecified;
248 case TTK_Struct: return DeclSpec::TST_struct;
249 case TTK_Union: return DeclSpec::TST_union;
250 case TTK_Class: return DeclSpec::TST_class;
251 case TTK_Enum: return DeclSpec::TST_enum;
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000252 }
253 }
Mike Stump11289f42009-09-09 15:08:12 +0000254
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000255 return DeclSpec::TST_unspecified;
256}
257
Francois Pichet48c946e2011-04-13 02:38:49 +0000258/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
259/// if a CXXScopeSpec's type is equal to the type of one of the base classes
260/// then downgrade the missing typename error to a warning.
261/// This is needed for MSVC compatibility; Example:
262/// @code
263/// template<class T> class A {
264/// public:
265/// typedef int TYPE;
266/// };
267/// template<class T> class B : public A<T> {
268/// public:
269/// A<T>::TYPE a; // no typename required because A<T> is a base class.
270/// };
271/// @endcode
272bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS) {
273 if (CurContext->isRecord()) {
Francois Pichetefc283c2011-04-13 02:44:57 +0000274 const Type *Ty = SS->getScopeRep()->getAsType();
Francois Pichet48c946e2011-04-13 02:38:49 +0000275
276 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
277 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
278 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
279 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
280 return true;
281 }
282 return false;
283}
284
Douglas Gregor15e56022009-10-13 23:27:22 +0000285bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
286 SourceLocation IILoc,
287 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000288 CXXScopeSpec *SS,
John McCallba7bf592010-08-24 05:47:05 +0000289 ParsedType &SuggestedType) {
Douglas Gregor15e56022009-10-13 23:27:22 +0000290 // We don't have anything to suggest (yet).
John McCallba7bf592010-08-24 05:47:05 +0000291 SuggestedType = ParsedType();
Douglas Gregor15e56022009-10-13 23:27:22 +0000292
Douglas Gregor2d435302009-12-30 17:04:44 +0000293 // There may have been a typo in the name of the type. Look up typo
294 // results, in case we have something that we can suggest.
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000295 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(&II, IILoc),
296 LookupOrdinaryName, S, SS, NULL,
297 false, CTC_Type)) {
298 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
299 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
Douglas Gregor2d435302009-12-30 17:04:44 +0000300
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000301 if (Corrected.isKeyword()) {
302 // We corrected to a keyword.
303 // FIXME: Actually recover with the keyword we suggest, and emit a fix-it.
304 Diag(IILoc, diag::err_unknown_typename_suggest)
305 << &II << CorrectedQuotedStr;
306 return true;
307 } else {
308 NamedDecl *Result = Corrected.getCorrectionDecl();
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000309 if ((isa<TypeDecl>(Result) || isa<ObjCInterfaceDecl>(Result)) &&
310 !Result->isInvalidDecl()) {
311 // We found a similarly-named type or interface; suggest that.
312 if (!SS || !SS->isSet())
313 Diag(IILoc, diag::err_unknown_typename_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000314 << &II << CorrectedQuotedStr
315 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000316 else if (DeclContext *DC = computeDeclContext(*SS, false))
317 Diag(IILoc, diag::err_unknown_nested_typename_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000318 << &II << DC << CorrectedQuotedStr << SS->getRange()
319 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000320 else
321 llvm_unreachable("could not have corrected a typo here");
Douglas Gregor2d435302009-12-30 17:04:44 +0000322
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000323 Diag(Result->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000324 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000325
Douglas Gregor844cb502011-03-01 18:12:44 +0000326 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS,
327 false, false, ParsedType(),
328 /*NonTrivialTypeSourceInfo=*/true);
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000329 return true;
330 }
Douglas Gregor2d435302009-12-30 17:04:44 +0000331 }
332 }
333
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000334 if (getLangOptions().CPlusPlus) {
335 // See if II is a class template that the user forgot to pass arguments to.
336 UnqualifiedId Name;
337 Name.setIdentifier(&II, IILoc);
338 CXXScopeSpec EmptySS;
339 TemplateTy TemplateResult;
Douglas Gregor786123d2010-05-21 23:18:07 +0000340 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000341 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
John McCallba7bf592010-08-24 05:47:05 +0000342 Name, ParsedType(), true, TemplateResult,
Douglas Gregor786123d2010-05-21 23:18:07 +0000343 MemberOfUnknownSpecialization) == TNK_Type_template) {
Jeffrey Yasskin54eba422010-04-08 21:04:54 +0000344 TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
345 Diag(IILoc, diag::err_template_missing_args) << TplName;
346 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
347 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
348 << TplDecl->getTemplateParameters()->getSourceRange();
349 }
350 return true;
351 }
352 }
353
Douglas Gregor15e56022009-10-13 23:27:22 +0000354 // FIXME: Should we move the logic that tries to recover from a missing tag
355 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
356
Douglas Gregor2d435302009-12-30 17:04:44 +0000357 if (!SS || (!SS->isSet() && !SS->isInvalid()))
Douglas Gregor15e56022009-10-13 23:27:22 +0000358 Diag(IILoc, diag::err_unknown_typename) << &II;
359 else if (DeclContext *DC = computeDeclContext(*SS, false))
360 Diag(IILoc, diag::err_typename_nested_not_found)
361 << &II << DC << SS->getRange();
362 else if (isDependentScopeSpecifier(*SS)) {
Francois Pichet48c946e2011-04-13 02:38:49 +0000363 unsigned DiagID = diag::err_typename_missing;
364 if (getLangOptions().Microsoft && isMicrosoftMissingTypename(SS))
Francois Pichet93921652011-04-22 08:25:24 +0000365 DiagID = diag::warn_typename_missing;
Francois Pichet48c946e2011-04-13 02:38:49 +0000366
367 Diag(SS->getRange().getBegin(), DiagID)
Daniel Dunbar07d07852009-10-18 21:17:35 +0000368 << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
Douglas Gregor15e56022009-10-13 23:27:22 +0000369 << SourceRange(SS->getRange().getBegin(), IILoc)
Douglas Gregora771f462010-03-31 17:46:05 +0000370 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
Douglas Gregorf7d77712010-06-16 22:31:08 +0000371 SuggestedType = ActOnTypenameType(S, SourceLocation(), *SS, II, IILoc).get();
Douglas Gregor15e56022009-10-13 23:27:22 +0000372 } else {
373 assert(SS && SS->isInvalid() &&
374 "Invalid scope specifier has already been diagnosed");
375 }
376
377 return true;
378}
Chris Lattnerffaa0e62009-04-12 21:49:30 +0000379
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000380/// \brief Determine whether the given result set contains either a type name
381/// or
382static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
383 bool CheckTemplate = R.getSema().getLangOptions().CPlusPlus &&
384 NextToken.is(tok::less);
385
386 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
387 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
388 return true;
389
390 if (CheckTemplate && isa<TemplateDecl>(*I))
391 return true;
392 }
393
394 return false;
395}
396
397Sema::NameClassification Sema::ClassifyName(Scope *S,
398 CXXScopeSpec &SS,
399 IdentifierInfo *&Name,
400 SourceLocation NameLoc,
401 const Token &NextToken) {
402 DeclarationNameInfo NameInfo(Name, NameLoc);
403 ObjCMethodDecl *CurMethod = getCurMethodDecl();
404
405 if (NextToken.is(tok::coloncolon)) {
406 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
407 QualType(), false, SS, 0, false);
408
409 }
410
411 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
412 LookupParsedName(Result, S, &SS, !CurMethod);
413
414 // Perform lookup for Objective-C instance variables (including automatically
415 // synthesized instance variables), if we're in an Objective-C method.
416 // FIXME: This lookup really, really needs to be folded in to the normal
417 // unqualified lookup mechanism.
418 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
419 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
Douglas Gregorb90f5182011-04-25 15:05:41 +0000420 if (E.get() || E.isInvalid())
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000421 return E;
422
423 // Synthesize ivars lazily.
424 if (getLangOptions().ObjCDefaultSynthProperties &&
425 getLangOptions().ObjCNonFragileABI2) {
426 if (SynthesizeProvisionalIvar(Result, Name, NameLoc)) {
427 if (const ObjCPropertyDecl *Property =
428 canSynthesizeProvisionalIvar(Name)) {
429 Diag(NameLoc, diag::warn_synthesized_ivar_access) << Name;
430 Diag(Property->getLocation(), diag::note_property_declare);
431 }
432
433 // FIXME: This is strange. Shouldn't we just take the ivar returned
434 // from SynthesizeProvisionalIvar and continue with that?
Douglas Gregorb90f5182011-04-25 15:05:41 +0000435 E = LookupInObjCMethod(Result, S, Name, true);
436 if (E.get() || E.isInvalid())
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000437 return E;
438 }
439 }
440 }
441
442 bool SecondTry = false;
443 bool IsFilteredTemplateName = false;
444
445Corrected:
446 switch (Result.getResultKind()) {
447 case LookupResult::NotFound:
448 // If an unqualified-id is followed by a '(', then we have a function
449 // call.
450 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
451 // In C++, this is an ADL-only call.
452 // FIXME: Reference?
453 if (getLangOptions().CPlusPlus)
454 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
455
456 // C90 6.3.2.2:
457 // If the expression that precedes the parenthesized argument list in a
458 // function call consists solely of an identifier, and if no
459 // declaration is visible for this identifier, the identifier is
460 // implicitly declared exactly as if, in the innermost block containing
461 // the function call, the declaration
462 //
463 // extern int identifier ();
464 //
465 // appeared.
466 //
467 // We also allow this in C99 as an extension.
468 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
469 Result.addDecl(D);
470 Result.resolveKind();
471 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
472 }
473 }
474
475 // In C, we first see whether there is a tag type by the same name, in
476 // which case it's likely that the user just forget to write "enum",
477 // "struct", or "union".
478 if (!getLangOptions().CPlusPlus && !SecondTry) {
479 Result.clear(LookupTagName);
480 LookupParsedName(Result, S, &SS);
481 if (TagDecl *Tag = Result.getAsSingle<TagDecl>()) {
482 const char *TagName = 0;
483 const char *FixItTagName = 0;
484 switch (Tag->getTagKind()) {
485 case TTK_Class:
486 TagName = "class";
487 FixItTagName = "class ";
488 break;
489
490 case TTK_Enum:
491 TagName = "enum";
492 FixItTagName = "enum ";
493 break;
494
495 case TTK_Struct:
496 TagName = "struct";
497 FixItTagName = "struct ";
498 break;
499
500 case TTK_Union:
501 TagName = "union";
502 FixItTagName = "union ";
503 break;
504 }
505
506 Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
507 << Name << TagName << getLangOptions().CPlusPlus
508 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
509 break;
510 }
511
512 Result.clear(LookupOrdinaryName);
513 }
514
515 // Perform typo correction to determine if there is another name that is
516 // close to this name.
517 if (!SecondTry) {
Douglas Gregor5cf0e152011-07-14 04:54:23 +0000518 SecondTry = true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000519 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
520 Result.getLookupKind(), S, &SS)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000521 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
522 unsigned QualifiedDiag = diag::err_no_member_suggest;
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000523 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
524 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
Douglas Gregor5e16c162011-04-27 03:47:06 +0000525
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000526 NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000527 NamedDecl *UnderlyingFirstDecl
528 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
Douglas Gregor5e16c162011-04-27 03:47:06 +0000529 if (getLangOptions().CPlusPlus && NextToken.is(tok::less) &&
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000530 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000531 UnqualifiedDiag = diag::err_no_template_suggest;
532 QualifiedDiag = diag::err_no_member_template_suggest;
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000533 } else if (UnderlyingFirstDecl &&
534 (isa<TypeDecl>(UnderlyingFirstDecl) ||
535 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
536 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
Douglas Gregor5e16c162011-04-27 03:47:06 +0000537 UnqualifiedDiag = diag::err_unknown_typename_suggest;
538 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
539 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000540
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000541 if (SS.isEmpty())
Douglas Gregor5e16c162011-04-27 03:47:06 +0000542 Diag(NameLoc, UnqualifiedDiag)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000543 << Name << CorrectedQuotedStr
544 << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000545 else
Douglas Gregor5e16c162011-04-27 03:47:06 +0000546 Diag(NameLoc, QualifiedDiag)
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000547 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000548 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000549 << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000550
551 // Update the name, so that the caller has the new name.
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000552 Name = Corrected.getCorrectionAsIdentifierInfo();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000553
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000554 // Also update the LookupResult...
555 // FIXME: This should probably go away at some point
556 Result.clear();
557 Result.setLookupName(Corrected.getCorrection());
558 if (FirstDecl) Result.addDecl(FirstDecl);
559
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000560 // Typo correction corrected to a keyword.
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000561 if (Corrected.isKeyword())
562 return Corrected.getCorrectionAsIdentifierInfo();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000563
Douglas Gregor5cf0e152011-07-14 04:54:23 +0000564 if (FirstDecl)
565 Diag(FirstDecl->getLocation(), diag::note_previous_decl)
566 << CorrectedQuotedStr;
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000567
568 // If we found an Objective-C instance variable, let
569 // LookupInObjCMethod build the appropriate expression to
570 // reference the ivar.
571 // FIXME: This is a gross hack.
572 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
573 Result.clear();
574 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
575 return move(E);
576 }
577
578 goto Corrected;
579 }
580 }
581
582 // We failed to correct; just fall through and let the parser deal with it.
583 Result.suppressDiagnostics();
584 return NameClassification::Unknown();
585
586 case LookupResult::NotFoundInCurrentInstantiation:
587 // We performed name lookup into the current instantiation, and there were
588 // dependent bases, so we treat this result the same way as any other
589 // dependent nested-name-specifier.
590
591 // C++ [temp.res]p2:
592 // A name used in a template declaration or definition and that is
593 // dependent on a template-parameter is assumed not to name a type
594 // unless the applicable name lookup finds a type name or the name is
595 // qualified by the keyword typename.
596 //
597 // FIXME: If the next token is '<', we might want to ask the parser to
598 // perform some heroics to see if we actually have a
599 // template-argument-list, which would indicate a missing 'template'
600 // keyword here.
601 return BuildDependentDeclRefExpr(SS, NameInfo, /*TemplateArgs=*/0);
602
603 case LookupResult::Found:
604 case LookupResult::FoundOverloaded:
605 case LookupResult::FoundUnresolvedValue:
606 break;
607
608 case LookupResult::Ambiguous:
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000609 if (getLangOptions().CPlusPlus && NextToken.is(tok::less) &&
610 hasAnyAcceptableTemplateNames(Result)) {
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000611 // C++ [temp.local]p3:
612 // A lookup that finds an injected-class-name (10.2) can result in an
613 // ambiguity in certain cases (for example, if it is found in more than
614 // one base class). If all of the injected-class-names that are found
615 // refer to specializations of the same class template, and if the name
616 // is followed by a template-argument-list, the reference refers to the
617 // class template itself and not a specialization thereof, and is not
618 // ambiguous.
619 //
620 // This filtering can make an ambiguous result into an unambiguous one,
621 // so try again after filtering out template names.
622 FilterAcceptableTemplateNames(Result);
623 if (!Result.isAmbiguous()) {
624 IsFilteredTemplateName = true;
625 break;
626 }
627 }
628
629 // Diagnose the ambiguity and return an error.
630 return NameClassification::Error();
631 }
632
633 if (getLangOptions().CPlusPlus && NextToken.is(tok::less) &&
634 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
635 // C++ [temp.names]p3:
636 // After name lookup (3.4) finds that a name is a template-name or that
637 // an operator-function-id or a literal- operator-id refers to a set of
638 // overloaded functions any member of which is a function template if
639 // this is followed by a <, the < is always taken as the delimiter of a
640 // template-argument-list and never as the less-than operator.
641 if (!IsFilteredTemplateName)
642 FilterAcceptableTemplateNames(Result);
643
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000644 if (!Result.empty()) {
645 bool IsFunctionTemplate;
646 TemplateName Template;
647 if (Result.end() - Result.begin() > 1) {
648 IsFunctionTemplate = true;
649 Template = Context.getOverloadedTemplateName(Result.begin(),
650 Result.end());
651 } else {
652 TemplateDecl *TD
653 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
654 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
655
656 if (SS.isSet() && !SS.isInvalid())
657 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000658 /*TemplateKeyword=*/false,
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000659 TD);
660 else
661 Template = TemplateName(TD);
662 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000663
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000664 if (IsFunctionTemplate) {
665 // Function templates always go through overload resolution, at which
666 // point we'll perform the various checks (e.g., accessibility) we need
667 // to based on which function we selected.
668 Result.suppressDiagnostics();
669
670 return NameClassification::FunctionTemplate(Template);
671 }
672
673 return NameClassification::TypeTemplate(Template);
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000674 }
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000675 }
676
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000677 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000678 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
679 DiagnoseUseOfDecl(Type, NameLoc);
680 QualType T = Context.getTypeDeclType(Type);
681 return ParsedType::make(T);
682 }
683
684 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
685 if (!Class) {
686 // FIXME: It's unfortunate that we don't have a Type node for handling this.
687 if (ObjCCompatibleAliasDecl *Alias
688 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
689 Class = Alias->getClassInterface();
690 }
691
692 if (Class) {
693 DiagnoseUseOfDecl(Class, NameLoc);
694
695 if (NextToken.is(tok::period)) {
696 // Interface. <something> is parsed as a property reference expression.
697 // Just return "unknown" as a fall-through for now.
698 Result.suppressDiagnostics();
699 return NameClassification::Unknown();
700 }
701
702 QualType T = Context.getObjCInterfaceType(Class);
703 return ParsedType::make(T);
704 }
705
Douglas Gregor8b02cd02011-04-27 04:48:22 +0000706 if (!Result.empty() && (*Result.begin())->isCXXClassMember())
707 return BuildPossibleImplicitMemberExpr(SS, Result, 0);
708
Douglas Gregor0e7dde52011-04-24 05:37:28 +0000709 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
710 return BuildDeclarationNameExpr(SS, Result, ADL);
711}
712
John McCall5ed6e8f2009-08-18 00:00:49 +0000713// Determines the context to return to after temporarily entering a
714// context. This depends in an unnecessarily complicated way on the
715// exact ordering of callbacks from the parser.
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000716DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000717
John McCall5ed6e8f2009-08-18 00:00:49 +0000718 // Functions defined inline within classes aren't parsed until we've
719 // finished parsing the top-level class, so the top-level class is
720 // the context we'll need to return to.
721 if (isa<FunctionDecl>(DC)) {
722 DC = DC->getLexicalParent();
723
724 // A function not defined within a class will always return to its
725 // lexical context.
726 if (!isa<CXXRecordDecl>(DC))
727 return DC;
728
729 // A C++ inline method/friend is parsed *after* the topmost class
730 // it was declared in is fully parsed ("complete"); the topmost
731 // class is the context we need to return to.
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000732 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000733 DC = RD;
734
735 // Return the declaration context of the topmost class the inline method is
736 // declared in.
737 return DC;
738 }
739
John McCalldc9796e2010-08-06 00:46:05 +0000740 // ObjCMethodDecls are parsed (for some reason) outside the context
741 // of the class.
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +0000742 if (isa<ObjCMethodDecl>(DC))
John McCalldc9796e2010-08-06 00:46:05 +0000743 return DC->getLexicalParent()->getLexicalParent();
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +0000744
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000745 return DC->getLexicalParent();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000746}
747
Douglas Gregor91f84212008-12-11 16:49:14 +0000748void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000749 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu17a37eb2008-12-08 07:14:51 +0000750 "The next DeclContext should be lexically contained in the current one.");
Chris Lattnerbec41342008-04-22 18:39:57 +0000751 CurContext = DC;
Douglas Gregor91f84212008-12-11 16:49:14 +0000752 S->setEntity(DC);
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000753}
754
Chris Lattner0a5ff0d2008-04-06 04:47:34 +0000755void Sema::PopDeclContext() {
756 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor91f84212008-12-11 16:49:14 +0000757
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000758 CurContext = getContainingDC(CurContext);
John McCalldd762d12010-07-23 22:45:07 +0000759 assert(CurContext && "Popped translation unit!");
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000760}
761
Argyrios Kyrtzidis9941a4d2009-06-17 23:19:02 +0000762/// EnterDeclaratorContext - Used when we must lookup names in the context
763/// of a declarator's nested name specifier.
John McCall6df5fef2009-12-19 10:49:29 +0000764///
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000765void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
John McCall6df5fef2009-12-19 10:49:29 +0000766 // C++0x [basic.lookup.unqual]p13:
767 // A name used in the definition of a static data member of class
768 // X (after the qualified-id of the static member) is looked up as
769 // if the name was used in a member function of X.
770 // C++0x [basic.lookup.unqual]p14:
771 // If a variable member of a namespace is defined outside of the
772 // scope of its namespace then any name used in the definition of
773 // the variable member (after the declarator-id) is looked up as
774 // if the definition of the variable member occurred in its
775 // namespace.
776 // Both of these imply that we should push a scope whose context
777 // is the semantic context of the declaration. We can't use
778 // PushDeclContext here because that context is not necessarily
779 // lexically contained in the current context. Fortunately,
780 // the containing scope should have the appropriate information.
781
782 assert(!S->getEntity() && "scope already has entity");
783
784#ifndef NDEBUG
785 Scope *Ancestor = S->getParent();
786 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
787 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
788#endif
789
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000790 CurContext = DC;
John McCall6df5fef2009-12-19 10:49:29 +0000791 S->setEntity(DC);
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000792}
793
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000794void Sema::ExitDeclaratorContext(Scope *S) {
John McCall6df5fef2009-12-19 10:49:29 +0000795 assert(S->getEntity() == CurContext && "Context imbalance!");
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000796
John McCall6df5fef2009-12-19 10:49:29 +0000797 // Switch back to the lexical context. The safety of this is
798 // enforced by an assert in EnterDeclaratorContext.
799 Scope *Ancestor = S->getParent();
800 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
801 CurContext = (DeclContext*) Ancestor->getEntity();
802
803 // We don't need to do anything with the scope, which is going to
804 // disappear.
Argyrios Kyrtzidis7bcce492009-06-17 23:15:40 +0000805}
806
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000807/// \brief Determine whether we allow overloading of the function
808/// PrevDecl with another declaration.
809///
810/// This routine determines whether overloading is possible, not
811/// whether some new function is actually an overload. It will return
812/// true in C++ (where we can always provide overloads) or, as an
813/// extension, in C when the previous function is already an
814/// overloaded function declaration or has the "overloadable"
815/// attribute.
John McCall1f82f242009-11-18 22:49:29 +0000816static bool AllowOverloadingOfFunction(LookupResult &Previous,
817 ASTContext &Context) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000818 if (Context.getLangOptions().CPlusPlus)
819 return true;
820
John McCall1f82f242009-11-18 22:49:29 +0000821 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000822 return true;
823
John McCall1f82f242009-11-18 22:49:29 +0000824 return (Previous.getResultKind() == LookupResult::Found
825 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000826}
827
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +0000828/// Add this decl to the scope shadowed decl chains.
John McCall759e32b2009-08-31 22:39:49 +0000829void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
Douglas Gregor07665a62009-01-05 19:45:36 +0000830 // Move up the scope chain until we find the nearest enclosing
831 // non-transparent context. The declaration will be introduced into this
832 // scope.
Mike Stump11289f42009-09-09 15:08:12 +0000833 while (S->getEntity() &&
Douglas Gregor07665a62009-01-05 19:45:36 +0000834 ((DeclContext *)S->getEntity())->isTransparentContext())
835 S = S->getParent();
836
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000837 // Add scoped declarations into their context, so that they can be
838 // found later. Declarations without a context won't be inserted
839 // into any context.
John McCall759e32b2009-08-31 22:39:49 +0000840 if (AddToContext)
841 CurContext->addDecl(D);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000842
Chandler Carruthf50ef6e2010-02-21 07:08:09 +0000843 // Out-of-line definitions shouldn't be pushed into scope in C++.
844 // Out-of-line variable and function definitions shouldn't even in C.
845 if ((getLangOptions().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
846 D->isOutOfLine())
847 return;
848
849 // Template instantiations should also not be pushed into scope.
850 if (isa<FunctionDecl>(D) &&
851 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
Douglas Gregor5ad7c542009-09-28 18:41:37 +0000852 return;
853
John McCall9f3059a2009-10-09 21:13:30 +0000854 // If this replaces anything in the current scope,
855 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
856 IEnd = IdResolver.end();
857 for (; I != IEnd; ++I) {
John McCall48871652010-08-21 09:40:31 +0000858 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
859 S->RemoveDecl(*I);
John McCall9f3059a2009-10-09 21:13:30 +0000860 IdResolver.RemoveDecl(*I);
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000861
John McCall9f3059a2009-10-09 21:13:30 +0000862 // Should only need to replace one decl.
863 break;
Douglas Gregor38feed82009-04-24 02:57:34 +0000864 }
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000865 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000866
John McCall48871652010-08-21 09:40:31 +0000867 S->AddDecl(D);
Douglas Gregor88764cf2011-03-14 21:19:51 +0000868
869 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
870 // Implicitly-generated labels may end up getting generated in an order that
871 // isn't strictly lexical, which breaks name lookup. Be careful to insert
872 // the label at the appropriate place in the identifier chain.
873 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
Douglas Gregord7d7e0d2011-03-24 14:35:16 +0000874 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
Douglas Gregor46c04e72011-03-16 16:39:03 +0000875 if (IDC == CurContext) {
876 if (!S->isDeclScope(*I))
877 continue;
878 } else if (IDC->Encloses(CurContext))
Douglas Gregor88764cf2011-03-14 21:19:51 +0000879 break;
880 }
881
Douglas Gregor46c04e72011-03-16 16:39:03 +0000882 IdResolver.InsertDeclAfter(I, D);
Douglas Gregor88764cf2011-03-14 21:19:51 +0000883 } else {
884 IdResolver.AddDecl(D);
885 }
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +0000886}
887
Douglas Gregordb446112011-03-07 16:54:27 +0000888bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S,
889 bool ExplicitInstantiationOrSpecialization) {
890 return IdResolver.isDeclInScope(D, Ctx, Context, S,
891 ExplicitInstantiationOrSpecialization);
Douglas Gregor505ad492009-09-28 00:47:05 +0000892}
893
John McCallcc14d1f2010-08-24 08:50:51 +0000894Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
895 DeclContext *TargetDC = DC->getPrimaryContext();
896 do {
897 if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
898 if (ScopeDC->getPrimaryContext() == TargetDC)
899 return S;
900 } while ((S = S->getParent()));
901
902 return 0;
903}
904
John McCall1f82f242009-11-18 22:49:29 +0000905static bool isOutOfScopePreviousDeclaration(NamedDecl *,
906 DeclContext*,
907 ASTContext&);
908
909/// Filters out lookup results that don't fall within the given scope
910/// as determined by isDeclInScope.
Richard Smith3f1b5d02011-05-05 21:57:07 +0000911void Sema::FilterLookupForScope(LookupResult &R,
912 DeclContext *Ctx, Scope *S,
913 bool ConsiderLinkage,
914 bool ExplicitInstantiationOrSpecialization) {
John McCall1f82f242009-11-18 22:49:29 +0000915 LookupResult::Filter F = R.makeFilter();
916 while (F.hasNext()) {
917 NamedDecl *D = F.next();
918
Richard Smith3f1b5d02011-05-05 21:57:07 +0000919 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
John McCall1f82f242009-11-18 22:49:29 +0000920 continue;
921
922 if (ConsiderLinkage &&
Richard Smith3f1b5d02011-05-05 21:57:07 +0000923 isOutOfScopePreviousDeclaration(D, Ctx, Context))
John McCall1f82f242009-11-18 22:49:29 +0000924 continue;
925
926 F.erase();
927 }
928
929 F.done();
930}
931
932static bool isUsingDecl(NamedDecl *D) {
933 return isa<UsingShadowDecl>(D) ||
934 isa<UnresolvedUsingTypenameDecl>(D) ||
935 isa<UnresolvedUsingValueDecl>(D);
936}
937
938/// Removes using shadow declarations from the lookup results.
939static void RemoveUsingDecls(LookupResult &R) {
940 LookupResult::Filter F = R.makeFilter();
941 while (F.hasNext())
942 if (isUsingDecl(F.next()))
943 F.erase();
944
945 F.done();
946}
947
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000948/// \brief Check for this common pattern:
949/// @code
950/// class S {
951/// S(const S&); // DO NOT IMPLEMENT
952/// void operator=(const S&); // DO NOT IMPLEMENT
953/// };
954/// @endcode
955static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
956 // FIXME: Should check for private access too but access is set after we get
957 // the decl here.
Alexis Hunt4a8ea102011-05-06 20:44:56 +0000958 if (D->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000959 return false;
960
961 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
962 return CD->isCopyConstructor();
Douglas Gregora1ce1f82010-09-27 22:06:20 +0000963 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
964 return Method->isCopyAssignmentOperator();
965 return false;
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000966}
967
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000968bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
969 assert(D);
Argyrios Kyrtzidis540bc012010-08-13 18:42:29 +0000970
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000971 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
972 return false;
973
974 // Ignore class templates.
Chandler Carruth8e666512011-01-03 19:27:19 +0000975 if (D->getDeclContext()->isDependentContext() ||
976 D->getLexicalDeclContext()->isDependentContext())
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000977 return false;
978
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000979 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000980 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
981 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000982
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000983 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
984 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
985 return false;
986 } else {
987 // 'static inline' functions are used in headers; don't warn.
John McCall8e7d6562010-08-26 03:08:43 +0000988 if (FD->getStorageClass() == SC_Static &&
Argyrios Kyrtzidis04c7fa02010-08-15 10:17:33 +0000989 FD->isInlineSpecified())
990 return false;
991 }
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000992
Alexis Hunt4a8ea102011-05-06 20:44:56 +0000993 if (FD->doesThisDeclarationHaveABody() &&
John McCalld37d35b2010-10-27 01:41:35 +0000994 Context.DeclMustBeEmitted(FD))
995 return false;
John McCalld37d35b2010-10-27 01:41:35 +0000996 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
997 if (!VD->isFileVarDecl() ||
998 VD->getType().isConstant(Context) ||
999 Context.DeclMustBeEmitted(VD))
1000 return false;
1001
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001002 if (VD->isStaticDataMember() &&
1003 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1004 return false;
1005
John McCalld37d35b2010-10-27 01:41:35 +00001006 } else {
1007 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001008 }
1009
John McCalld37d35b2010-10-27 01:41:35 +00001010 // Only warn for unused decls internal to the translation unit.
1011 if (D->getLinkage() == ExternalLinkage)
1012 return false;
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001013
John McCalld37d35b2010-10-27 01:41:35 +00001014 return true;
1015}
1016
1017void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00001018 if (!D)
1019 return;
1020
1021 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1022 const FunctionDecl *First = FD->getFirstDeclaration();
1023 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1024 return; // First should already be in the vector.
1025 }
1026
1027 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1028 const VarDecl *First = VD->getFirstDeclaration();
1029 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1030 return; // First should already be in the vector.
1031 }
1032
1033 if (ShouldWarnIfUnusedFileScopedDecl(D))
1034 UnusedFileScopedDecls.push_back(D);
1035 }
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00001036
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001037static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
John McCall67da35c2010-02-04 22:26:26 +00001038 if (D->isInvalidDecl())
1039 return false;
1040
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001041 if (D->isUsed() || D->hasAttr<UnusedAttr>())
1042 return false;
John McCall67da35c2010-02-04 22:26:26 +00001043
Chris Lattnercab02a62011-02-17 20:34:02 +00001044 if (isa<LabelDecl>(D))
1045 return true;
1046
John McCall67da35c2010-02-04 22:26:26 +00001047 // White-list anything that isn't a local variable.
1048 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1049 !D->getDeclContext()->isFunctionOrMethod())
1050 return false;
1051
1052 // Types of valid local variables should be complete, so this should succeed.
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001053 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
John McCallcef15822010-03-31 02:47:45 +00001054
1055 // White-list anything with an __attribute__((unused)) type.
1056 QualType Ty = VD->getType();
1057
1058 // Only look at the outermost level of typedef.
1059 if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) {
1060 if (TT->getDecl()->hasAttr<UnusedAttr>())
1061 return false;
1062 }
1063
Douglas Gregor14f232e2010-05-08 23:05:03 +00001064 // If we failed to complete the type for some reason, or if the type is
1065 // dependent, don't diagnose the variable.
1066 if (Ty->isIncompleteType() || Ty->isDependentType())
Douglas Gregor19defcd2010-04-27 16:20:13 +00001067 return false;
1068
John McCallcef15822010-03-31 02:47:45 +00001069 if (const TagType *TT = Ty->getAs<TagType>()) {
1070 const TagDecl *Tag = TT->getDecl();
1071 if (Tag->hasAttr<UnusedAttr>())
1072 return false;
1073
1074 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
Douglas Gregor14f232e2010-05-08 23:05:03 +00001075 // FIXME: Checking for the presence of a user-declared constructor
1076 // isn't completely accurate; we'd prefer to check that the initializer
1077 // has no side effects.
1078 if (RD->hasUserDeclaredConstructor() || !RD->hasTrivialDestructor())
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001079 return false;
1080 }
1081 }
John McCallcef15822010-03-31 02:47:45 +00001082
1083 // TODO: __attribute__((unused)) templates?
Anders Carlssonf5dc6fa2009-11-07 07:26:56 +00001084 }
1085
John McCall67da35c2010-02-04 22:26:26 +00001086 return true;
Anders Carlsson2889e0e2009-11-07 07:18:14 +00001087}
1088
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001089/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1090/// unless they are marked attr(unused).
Douglas Gregor14f232e2010-05-08 23:05:03 +00001091void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1092 if (!ShouldDiagnoseUnusedDecl(D))
1093 return;
1094
Chris Lattnercab02a62011-02-17 20:34:02 +00001095 unsigned DiagID;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001096 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
Chris Lattnercab02a62011-02-17 20:34:02 +00001097 DiagID = diag::warn_unused_exception_param;
1098 else if (isa<LabelDecl>(D))
1099 DiagID = diag::warn_unused_label;
Douglas Gregor14f232e2010-05-08 23:05:03 +00001100 else
Chris Lattnercab02a62011-02-17 20:34:02 +00001101 DiagID = diag::warn_unused_variable;
1102
1103 Diag(D->getLocation(), DiagID) << D->getDeclName();
Douglas Gregor14f232e2010-05-08 23:05:03 +00001104}
1105
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001106static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1107 // Verify that we have no forward references left. If so, there was a goto
1108 // or address of a label taken, but no definition of it. Label fwd
1109 // definitions are indicated with a null substmt.
1110 if (L->getStmt() == 0)
1111 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1112}
1113
Steve Naroffc62adb62007-10-09 22:01:59 +00001114void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001115 if (S->decl_empty()) return;
Douglas Gregor5101c242008-12-05 18:15:24 +00001116 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
Mike Stump11289f42009-09-09 15:08:12 +00001117 "Scope shouldn't contain decls!");
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001118
Chris Lattner302b4be2006-11-19 02:31:38 +00001119 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1120 I != E; ++I) {
John McCall48871652010-08-21 09:40:31 +00001121 Decl *TmpD = (*I);
Steve Naroff9324db12007-09-13 18:10:37 +00001122 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001123
Douglas Gregor91f84212008-12-11 16:49:14 +00001124 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1125 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +00001126
Douglas Gregor91f84212008-12-11 16:49:14 +00001127 if (!D->getDeclName()) continue;
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001128
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00001129 // Diagnose unused variables in this scope.
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00001130 if (!S->hasErrorOccurred())
Douglas Gregor14f232e2010-05-08 23:05:03 +00001131 DiagnoseUnusedDecl(D);
1132
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001133 // If this was a forward reference to a label, verify it was defined.
1134 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1135 CheckPoppedLabel(LD, *this);
1136
Douglas Gregor91f84212008-12-11 16:49:14 +00001137 // Remove this name from our lexical scope.
1138 IdResolver.RemoveDecl(D);
Chris Lattner302b4be2006-11-19 02:31:38 +00001139 }
1140}
1141
Douglas Gregor1c283312010-08-11 12:19:30 +00001142/// \brief Look for an Objective-C class in the translation unit.
1143///
1144/// \param Id The name of the Objective-C class we're looking for. If
1145/// typo-correction fixes this name, the Id will be updated
1146/// to the fixed name.
1147///
1148/// \param IdLoc The location of the name in the translation unit.
1149///
1150/// \param TypoCorrection If true, this routine will attempt typo correction
1151/// if there is no class with the given name.
1152///
1153/// \returns The declaration of the named Objective-C class, or NULL if the
1154/// class could not be found.
1155ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1156 SourceLocation IdLoc,
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001157 bool DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001158 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1159 // creation from this context.
1160 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1161
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001162 if (!IDecl && DoTypoCorrection) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001163 // Perform typo correction at the given location, but only if we
1164 // find an Objective-C class name.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001165 TypoCorrection C;
1166 if ((C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1167 TUScope, NULL, NULL, false, CTC_NoKeywords)) &&
1168 (IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>())) {
Douglas Gregor1c283312010-08-11 12:19:30 +00001169 Diag(IdLoc, diag::err_undef_interface_suggest)
1170 << Id << IDecl->getDeclName()
1171 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
1172 Diag(IDecl->getLocation(), diag::note_previous_decl)
1173 << IDecl->getDeclName();
1174
1175 Id = IDecl->getIdentifier();
1176 }
1177 }
1178
1179 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1180}
1181
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001182/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1183/// from S, where a non-field would be declared. This routine copes
1184/// with the difference between C and C++ scoping rules in structs and
1185/// unions. For example, the following code is well-formed in C but
1186/// ill-formed in C++:
1187/// @code
1188/// struct S6 {
1189/// enum { BAR } e;
1190/// };
Mike Stump11289f42009-09-09 15:08:12 +00001191///
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001192/// void test_S6() {
1193/// struct S6 a;
1194/// a.e = BAR;
1195/// }
1196/// @endcode
1197/// For the declaration of BAR, this routine will return a different
1198/// scope. The scope S will be the scope of the unnamed enumeration
1199/// within S6. In C++, this routine will return the scope associated
1200/// with S6, because the enumeration's scope is a transparent
1201/// context but structures can contain non-field names. In C, this
1202/// routine will return the translation unit scope, since the
1203/// enumeration's scope is a transparent context and structures cannot
1204/// contain non-field names.
1205Scope *Sema::getNonFieldDeclScope(Scope *S) {
1206 while (((S->getFlags() & Scope::DeclScope) == 0) ||
Mike Stump11289f42009-09-09 15:08:12 +00001207 (S->getEntity() &&
Douglas Gregor45a33ec2009-01-12 18:45:55 +00001208 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
1209 (S->isClassScope() && !getLangOptions().CPlusPlus))
1210 S = S->getParent();
1211 return S;
1212}
1213
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001214/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1215/// file scope. lazily create a decl for it. ForRedeclaration is true
1216/// if we're creating this built-in in anticipation of redeclaring the
1217/// built-in.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001218NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001219 Scope *S, bool ForRedeclaration,
1220 SourceLocation Loc) {
Chris Lattner9561a0b2007-01-28 08:20:04 +00001221 Builtin::ID BID = (Builtin::ID)bid;
1222
Chris Lattnerecd79c62009-06-14 00:45:47 +00001223 ASTContext::GetBuiltinTypeError Error;
Mike Stump11289f42009-09-09 15:08:12 +00001224 QualType R = Context.GetBuiltinType(BID, Error);
Douglas Gregor538c3d82009-02-14 01:52:53 +00001225 switch (Error) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00001226 case ASTContext::GE_None:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001227 // Okay
1228 break;
1229
Mike Stump93246cc2009-07-28 23:57:15 +00001230 case ASTContext::GE_Missing_stdio:
Douglas Gregor538c3d82009-02-14 01:52:53 +00001231 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001232 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
Douglas Gregor538c3d82009-02-14 01:52:53 +00001233 << Context.BuiltinInfo.GetName(BID);
1234 return 0;
Mike Stumpa4de80b2009-07-28 02:25:19 +00001235
Mike Stump93246cc2009-07-28 23:57:15 +00001236 case ASTContext::GE_Missing_setjmp:
Mike Stumpa4de80b2009-07-28 02:25:19 +00001237 if (ForRedeclaration)
Douglas Gregorbfe022c2011-01-03 09:37:44 +00001238 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
Mike Stumpa4de80b2009-07-28 02:25:19 +00001239 << Context.BuiltinInfo.GetName(BID);
1240 return 0;
Douglas Gregor538c3d82009-02-14 01:52:53 +00001241 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001242
1243 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1244 Diag(Loc, diag::ext_implicit_lib_function_decl)
1245 << Context.BuiltinInfo.GetName(BID)
1246 << R;
Douglas Gregor9eebd972009-02-16 21:58:21 +00001247 if (Context.BuiltinInfo.getHeaderName(BID) &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001248 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
Chris Lattneraf73cf62009-04-16 03:59:32 +00001249 != Diagnostic::Ignored)
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001250 Diag(Loc, diag::note_please_include_header)
1251 << Context.BuiltinInfo.getHeaderName(BID)
1252 << Context.BuiltinInfo.GetName(BID);
1253 }
1254
Argyrios Kyrtzidis6d053032008-04-17 14:47:13 +00001255 FunctionDecl *New = FunctionDecl::Create(Context,
1256 Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001257 Loc, Loc, II, R, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00001258 SC_Extern,
1259 SC_None, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00001260 /*hasPrototype=*/true);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001261 New->setImplicit();
1262
Chris Lattner4dd27102008-05-05 22:18:14 +00001263 // Create Decl objects for each parameter, adding them to the
1264 // FunctionDecl.
John McCall424cec92011-01-19 06:33:43 +00001265 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner4dd27102008-05-05 22:18:14 +00001266 llvm::SmallVector<ParmVarDecl*, 16> Params;
John McCall8fb0d9d2011-05-01 22:35:37 +00001267 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1268 ParmVarDecl *parm =
1269 ParmVarDecl::Create(Context, New, SourceLocation(),
1270 SourceLocation(), 0,
1271 FT->getArgType(i), /*TInfo=*/0,
1272 SC_None, SC_None, 0);
1273 parm->setScopeInfo(0, i);
1274 Params.push_back(parm);
1275 }
Douglas Gregord5058122010-02-11 01:19:42 +00001276 New->setParams(Params.data(), Params.size());
Chris Lattner4dd27102008-05-05 22:18:14 +00001277 }
Mike Stump11289f42009-09-09 15:08:12 +00001278
1279 AddKnownFunctionAttributes(New);
1280
Chris Lattnerc5c95b52008-04-11 07:00:53 +00001281 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregorc72e6452009-01-09 18:51:29 +00001282 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1283 // relate Scopes to DeclContexts, and probably eliminate CurContext
1284 // entirely, but we're not there yet.
1285 DeclContext *SavedContext = CurContext;
1286 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +00001287 PushOnScopeChains(New, TUScope);
Douglas Gregorc72e6452009-01-09 18:51:29 +00001288 CurContext = SavedContext;
Chris Lattner9561a0b2007-01-28 08:20:04 +00001289 return New;
1290}
1291
Richard Smithdda56e42011-04-15 14:24:37 +00001292/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001293/// same name and scope as a previous declaration 'Old'. Figure out
1294/// how to resolve this situation, merging decls or emitting
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001295/// diagnostics as appropriate. If there was an error, set New to be invalid.
Chris Lattner01564d92007-01-27 19:27:06 +00001296///
Richard Smithdda56e42011-04-15 14:24:37 +00001297void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
John McCall1f82f242009-11-18 22:49:29 +00001298 // If the new decl is known invalid already, don't bother doing any
1299 // merging checks.
1300 if (New->isInvalidDecl()) return;
Mike Stump11289f42009-09-09 15:08:12 +00001301
Steve Naroff44cfcb62008-09-09 14:32:20 +00001302 // Allow multiple definitions for ObjC built-in typedefs.
1303 // FIXME: Verify the underlying types are equivalent!
1304 if (getLangOptions().ObjC1) {
Chris Lattner66e32812008-11-20 05:41:43 +00001305 const IdentifierInfo *TypeID = New->getIdentifier();
1306 switch (TypeID->getLength()) {
1307 default: break;
Mike Stump11289f42009-09-09 15:08:12 +00001308 case 2:
Chris Lattner66e32812008-11-20 05:41:43 +00001309 if (!TypeID->isStr("id"))
1310 break;
David Chisnall9f57c292009-08-17 16:35:33 +00001311 Context.ObjCIdRedefinitionType = New->getUnderlyingType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001312 // Install the built-in type for 'id', ignoring the current definition.
1313 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1314 return;
Chris Lattner66e32812008-11-20 05:41:43 +00001315 case 5:
1316 if (!TypeID->isStr("Class"))
1317 break;
David Chisnall9f57c292009-08-17 16:35:33 +00001318 Context.ObjCClassRedefinitionType = New->getUnderlyingType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001319 // Install the built-in type for 'Class', ignoring the current definition.
1320 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001321 return;
Chris Lattner66e32812008-11-20 05:41:43 +00001322 case 3:
1323 if (!TypeID->isStr("SEL"))
1324 break;
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00001325 Context.ObjCSelRedefinitionType = New->getUnderlyingType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001326 // Install the built-in type for 'SEL', ignoring the current definition.
1327 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001328 return;
Chris Lattner66e32812008-11-20 05:41:43 +00001329 case 8:
1330 if (!TypeID->isStr("Protocol"))
1331 break;
Steve Naroff44cfcb62008-09-09 14:32:20 +00001332 Context.setObjCProtoType(New->getUnderlyingType());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001333 return;
Steve Naroff44cfcb62008-09-09 14:32:20 +00001334 }
1335 // Fall through - the typedef name was not a builtin type.
1336 }
John McCall1f82f242009-11-18 22:49:29 +00001337
Douglas Gregorfb034662009-01-28 17:15:10 +00001338 // Verify the old decl was also a type.
John McCall91f1a022009-12-30 00:31:22 +00001339 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1340 if (!Old) {
Mike Stump11289f42009-09-09 15:08:12 +00001341 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001342 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00001343
1344 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001345 if (OldD->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +00001346 Diag(OldD->getLocation(), diag::note_previous_definition);
John McCall1f82f242009-11-18 22:49:29 +00001347
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001348 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00001349 }
Douglas Gregorfb034662009-01-28 17:15:10 +00001350
John McCall1f82f242009-11-18 22:49:29 +00001351 // If the old declaration is invalid, just give up here.
1352 if (Old->isInvalidDecl())
1353 return New->setInvalidDecl();
1354
Mike Stump11289f42009-09-09 15:08:12 +00001355 // Determine the "old" type we'll use for checking and diagnostics.
Douglas Gregorfb034662009-01-28 17:15:10 +00001356 QualType OldType;
Richard Smithdda56e42011-04-15 14:24:37 +00001357 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
Douglas Gregorfb034662009-01-28 17:15:10 +00001358 OldType = OldTypedef->getUnderlyingType();
1359 else
1360 OldType = Context.getTypeDeclType(Old);
1361
Chris Lattnerf9c49e52008-07-25 18:44:27 +00001362 // If the typedef types are not identical, reject them in all languages and
1363 // with any extensions enabled.
Douglas Gregorfb034662009-01-28 17:15:10 +00001364
Mike Stump11289f42009-09-09 15:08:12 +00001365 if (OldType != New->getUnderlyingType() &&
1366 Context.getCanonicalType(OldType) !=
Chris Lattnerf9c49e52008-07-25 18:44:27 +00001367 Context.getCanonicalType(New->getUnderlyingType())) {
Richard Smithdda56e42011-04-15 14:24:37 +00001368 int Kind = 0;
1369 if (isa<TypeAliasDecl>(Old))
1370 Kind = 1;
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00001371 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Richard Smithdda56e42011-04-15 14:24:37 +00001372 << Kind << New->getUnderlyingType() << OldType;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001373 if (Old->getLocation().isValid())
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +00001374 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001375 return New->setInvalidDecl();
Chris Lattnerf9c49e52008-07-25 18:44:27 +00001376 }
Mike Stump11289f42009-09-09 15:08:12 +00001377
John McCall91f1a022009-12-30 00:31:22 +00001378 // The types match. Link up the redeclaration chain if the old
1379 // declaration was a typedef.
Nick Lewycky0bdf13e2011-07-02 02:05:12 +00001380 // FIXME: this is a potential source of weirdness if the type
John McCall91f1a022009-12-30 00:31:22 +00001381 // spellings don't match exactly.
Richard Smithdda56e42011-04-15 14:24:37 +00001382 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old))
1383 New->setPreviousDeclaration(Typedef);
John McCall91f1a022009-12-30 00:31:22 +00001384
Steve Naroff7cae42b2009-07-10 23:34:53 +00001385 if (getLangOptions().Microsoft)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001386 return;
Eli Friedman61b529f2008-06-11 06:20:39 +00001387
Chris Lattner2581fc32009-04-17 22:04:20 +00001388 if (getLangOptions().CPlusPlus) {
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001389 // C++ [dcl.typedef]p2:
1390 // In a given non-class scope, a typedef specifier can be used to
1391 // redefine the name of any type declared in that scope to refer
1392 // to the type to which it already refers.
Chris Lattner2581fc32009-04-17 22:04:20 +00001393 if (!isa<CXXRecordDecl>(CurContext))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001394 return;
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001395
1396 // C++0x [dcl.typedef]p4:
1397 // In a given class scope, a typedef specifier can be used to redefine
1398 // any class-name declared in that scope that is not also a typedef-name
1399 // to refer to the type to which it already refers.
1400 //
1401 // This wording came in via DR424, which was a correction to the
1402 // wording in DR56, which accidentally banned code like:
1403 //
1404 // struct S {
1405 // typedef struct A { } A;
1406 // };
1407 //
1408 // in the C++03 standard. We implement the C++0x semantics, which
1409 // allow the above but disallow
1410 //
1411 // struct S {
1412 // typedef int I;
1413 // typedef int I;
1414 // };
1415 //
1416 // since that was the intent of DR56.
Richard Smithdda56e42011-04-15 14:24:37 +00001417 if (!isa<TypedefNameDecl>(Old))
Douglas Gregor9dd13ab2010-01-11 21:54:40 +00001418 return;
1419
Chris Lattner2581fc32009-04-17 22:04:20 +00001420 Diag(New->getLocation(), diag::err_redefinition)
1421 << New->getDeclName();
1422 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001423 return New->setInvalidDecl();
Daniel Dunbar84b70f72008-09-12 18:10:20 +00001424 }
Eli Friedman61b529f2008-06-11 06:20:39 +00001425
Chris Lattner2581fc32009-04-17 22:04:20 +00001426 // If we have a redefinition of a typedef in C, emit a warning. This warning
1427 // is normally mapped to an error, but can be controlled with
Eli Friedman319ce952009-06-04 23:03:07 +00001428 // -Wtypedef-redefinition. If either the original or the redefinition is
1429 // in a system header, don't emit this for compatibility with GCC.
Chris Lattner30d0cfd2010-03-01 20:59:53 +00001430 if (getDiagnostics().getSuppressSystemWarnings() &&
Eli Friedman319ce952009-06-04 23:03:07 +00001431 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1432 Context.getSourceManager().isInSystemHeader(New->getLocation())))
Chris Lattner9a845892009-04-27 01:46:12 +00001433 return;
Mike Stump11289f42009-09-09 15:08:12 +00001434
Chris Lattner2581fc32009-04-17 22:04:20 +00001435 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1436 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001437 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001438 return;
Chris Lattner01564d92007-01-27 19:27:06 +00001439}
1440
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001441/// DeclhasAttr - returns true if decl Declaration already has the target
1442/// attribute.
Mike Stump11289f42009-09-09 15:08:12 +00001443static bool
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001444DeclHasAttr(const Decl *D, const Attr *A) {
1445 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1446 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1447 if ((*i)->getKind() == A->getKind()) {
1448 // FIXME: Don't hardcode this check
1449 if (OA && isa<OwnershipAttr>(*i))
1450 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
Chris Lattner84966392008-03-03 03:28:21 +00001451 return true;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001452 }
Chris Lattner84966392008-03-03 03:28:21 +00001453
1454 return false;
1455}
1456
John McCallf79e87d2011-03-02 04:00:57 +00001457/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
1458static void mergeDeclAttributes(Decl *newDecl, const Decl *oldDecl,
1459 ASTContext &C) {
1460 if (!oldDecl->hasAttrs())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001461 return;
John McCallf79e87d2011-03-02 04:00:57 +00001462
1463 bool foundAny = newDecl->hasAttrs();
1464
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001465 // Ensure that any moving of objects within the allocated map is done before
1466 // we process them.
John McCallf79e87d2011-03-02 04:00:57 +00001467 if (!foundAny) newDecl->setAttrs(AttrVec());
1468
Peter Collingbourneab8bc062011-01-21 02:08:36 +00001469 for (specific_attr_iterator<InheritableAttr>
John McCallf79e87d2011-03-02 04:00:57 +00001470 i = oldDecl->specific_attr_begin<InheritableAttr>(),
1471 e = oldDecl->specific_attr_end<InheritableAttr>(); i != e; ++i) {
1472 if (!DeclHasAttr(newDecl, *i)) {
1473 InheritableAttr *newAttr = cast<InheritableAttr>((*i)->clone(C));
1474 newAttr->setInherited(true);
1475 newDecl->addAttr(newAttr);
1476 foundAny = true;
Chris Lattner84966392008-03-03 03:28:21 +00001477 }
1478 }
John McCallf79e87d2011-03-02 04:00:57 +00001479
1480 if (!foundAny) newDecl->dropAttrs();
1481}
1482
1483/// mergeParamDeclAttributes - Copy attributes from the old parameter
1484/// to the new one.
1485static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
1486 const ParmVarDecl *oldDecl,
1487 ASTContext &C) {
1488 if (!oldDecl->hasAttrs())
1489 return;
1490
1491 bool foundAny = newDecl->hasAttrs();
1492
1493 // Ensure that any moving of objects within the allocated map is
1494 // done before we process them.
1495 if (!foundAny) newDecl->setAttrs(AttrVec());
1496
1497 for (specific_attr_iterator<InheritableParamAttr>
1498 i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
1499 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
1500 if (!DeclHasAttr(newDecl, *i)) {
1501 InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C));
1502 newAttr->setInherited(true);
1503 newDecl->addAttr(newAttr);
1504 foundAny = true;
1505 }
1506 }
1507
1508 if (!foundAny) newDecl->dropAttrs();
Chris Lattner84966392008-03-03 03:28:21 +00001509}
1510
Dan Gohman28ade552010-07-26 21:25:24 +00001511namespace {
1512
Douglas Gregora74a2972009-03-06 22:43:54 +00001513/// Used in MergeFunctionDecl to keep track of function parameters in
1514/// C.
1515struct GNUCompatibleParamWarning {
1516 ParmVarDecl *OldParm;
1517 ParmVarDecl *NewParm;
1518 QualType PromotedType;
1519};
1520
Dan Gohman28ade552010-07-26 21:25:24 +00001521}
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001522
1523/// getSpecialMember - get the special member enum for a method.
Anders Carlsson05bf0092010-04-22 05:40:53 +00001524Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001525 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001526 if (Ctor->isDefaultConstructor())
1527 return Sema::CXXDefaultConstructor;
Alexis Huntd051b872011-05-26 01:26:05 +00001528
1529 if (Ctor->isCopyConstructor())
1530 return Sema::CXXCopyConstructor;
1531
1532 if (Ctor->isMoveConstructor())
1533 return Sema::CXXMoveConstructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00001534 } else if (isa<CXXDestructorDecl>(MD)) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001535 return Sema::CXXDestructor;
Alexis Hunt119c10e2011-05-25 23:16:36 +00001536 } else if (MD->isCopyAssignmentOperator()) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001537 return Sema::CXXCopyAssignment;
Alexis Hunt119c10e2011-05-25 23:16:36 +00001538 }
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001539
Alexis Hunt80f00ff2011-05-10 19:08:14 +00001540 return Sema::CXXInvalid;
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001541}
1542
Sebastian Redl243d9052010-06-09 21:17:41 +00001543/// canRedefineFunction - checks if a function can be redefined. Currently,
Charles Davisfea48452010-02-18 02:00:42 +00001544/// only extern inline functions can be redefined, and even then only in
1545/// GNU89 mode.
1546static bool canRedefineFunction(const FunctionDecl *FD,
1547 const LangOptions& LangOpts) {
Eli Friedman51dd0182011-06-13 23:56:42 +00001548 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
1549 !LangOpts.CPlusPlus &&
Charles Davisfea48452010-02-18 02:00:42 +00001550 FD->isInlineSpecified() &&
John McCall8e7d6562010-08-26 03:08:43 +00001551 FD->getStorageClass() == SC_Extern);
Charles Davisfea48452010-02-18 02:00:42 +00001552}
1553
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001554/// MergeFunctionDecl - We just parsed a function 'New' from
1555/// declarator D which has the same name and scope as a previous
1556/// declaration 'Old'. Figure out how to resolve this situation,
1557/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001558///
1559/// In C++, New and Old must be declarations that are not
1560/// overloaded. Use IsOverload to determine whether New and Old are
1561/// overloaded, and to select the Old declaration that New should be
1562/// merged with.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001563///
1564/// Returns true if there was an error, false otherwise.
1565bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +00001566 // Verify the old decl was also a function.
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001567 FunctionDecl *Old = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001568 if (FunctionTemplateDecl *OldFunctionTemplate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001569 = dyn_cast<FunctionTemplateDecl>(OldD))
1570 Old = OldFunctionTemplate->getTemplatedDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001571 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001572 Old = dyn_cast<FunctionDecl>(OldD);
Chris Lattnerc511efb2007-01-27 19:32:14 +00001573 if (!Old) {
John McCalle29c5cd2009-12-10 19:51:03 +00001574 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
1575 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
1576 Diag(Shadow->getTargetDecl()->getLocation(),
1577 diag::note_using_decl_target);
1578 Diag(Shadow->getUsingDecl()->getLocation(),
1579 diag::note_using_decl) << 0;
1580 return true;
1581 }
1582
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00001583 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001584 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001585 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001586 return true;
Chris Lattnerc511efb2007-01-27 19:32:14 +00001587 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001588
1589 // Determine whether the previous declaration was a definition,
1590 // implicit declaration, or a declaration.
1591 diag::kind PrevDiag;
1592 if (Old->isThisDeclarationADefinition())
Chris Lattner0369c572008-11-23 23:12:31 +00001593 PrevDiag = diag::note_previous_definition;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001594 else if (Old->isImplicit())
1595 PrevDiag = diag::note_previous_implicit_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00001596 else
Chris Lattner0369c572008-11-23 23:12:31 +00001597 PrevDiag = diag::note_previous_declaration;
Mike Stump11289f42009-09-09 15:08:12 +00001598
Chris Lattnerfc4379f2008-04-06 23:10:54 +00001599 QualType OldQType = Context.getCanonicalType(Old->getType());
1600 QualType NewQType = Context.getCanonicalType(New->getType());
Mike Stump11289f42009-09-09 15:08:12 +00001601
Charles Davisfea48452010-02-18 02:00:42 +00001602 // Don't complain about this if we're in GNU89 mode and the old function
1603 // is an extern inline function.
Douglas Gregore62c0a42009-02-24 01:23:02 +00001604 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
John McCall8e7d6562010-08-26 03:08:43 +00001605 New->getStorageClass() == SC_Static &&
1606 Old->getStorageClass() != SC_Static &&
Charles Davisfea48452010-02-18 02:00:42 +00001607 !canRedefineFunction(Old, getLangOptions())) {
Francois Pichet6841a122011-04-22 19:50:06 +00001608 if (getLangOptions().Microsoft) {
1609 Diag(New->getLocation(), diag::warn_static_non_static) << New;
1610 Diag(Old->getLocation(), PrevDiag);
1611 } else {
1612 Diag(New->getLocation(), diag::err_static_non_static) << New;
1613 Diag(Old->getLocation(), PrevDiag);
1614 return true;
1615 }
Douglas Gregore62c0a42009-02-24 01:23:02 +00001616 }
1617
John McCallcddbad02010-02-04 05:44:44 +00001618 // If a function is first declared with a calling convention, but is
1619 // later declared or defined without one, the second decl assumes the
1620 // calling convention of the first.
1621 //
1622 // For the new decl, we have to look at the NON-canonical type to tell the
1623 // difference between a function that really doesn't have a calling
1624 // convention and one that is declared cdecl. That's because in
1625 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
1626 // because it is the default calling convention.
1627 //
1628 // Note also that we DO NOT return at this point, because we still have
1629 // other tests to run.
John McCall4f5019e2010-12-19 02:44:49 +00001630 const FunctionType *OldType = cast<FunctionType>(OldQType);
John McCallcddbad02010-02-04 05:44:44 +00001631 const FunctionType *NewType = New->getType()->getAs<FunctionType>();
John McCall4f5019e2010-12-19 02:44:49 +00001632 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
1633 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
1634 bool RequiresAdjustment = false;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001635 if (OldTypeInfo.getCC() != CC_Default &&
1636 NewTypeInfo.getCC() == CC_Default) {
John McCall4f5019e2010-12-19 02:44:49 +00001637 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
1638 RequiresAdjustment = true;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001639 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
1640 NewTypeInfo.getCC())) {
John McCallcddbad02010-02-04 05:44:44 +00001641 // Calling conventions really aren't compatible, so complain.
John McCallab26cfa2010-02-05 21:31:56 +00001642 Diag(New->getLocation(), diag::err_cconv_change)
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001643 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
1644 << (OldTypeInfo.getCC() == CC_Default)
1645 << (OldTypeInfo.getCC() == CC_Default ? "" :
1646 FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
John McCallab26cfa2010-02-05 21:31:56 +00001647 Diag(Old->getLocation(), diag::note_previous_declaration);
John McCallcddbad02010-02-04 05:44:44 +00001648 return true;
1649 }
1650
John McCallab26cfa2010-02-05 21:31:56 +00001651 // FIXME: diagnose the other way around?
John McCall4f5019e2010-12-19 02:44:49 +00001652 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
1653 NewTypeInfo = NewTypeInfo.withNoReturn(true);
1654 RequiresAdjustment = true;
John McCallab26cfa2010-02-05 21:31:56 +00001655 }
1656
Douglas Gregor77e274f2010-06-18 21:30:25 +00001657 // Merge regparm attribute.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00001658 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
1659 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
1660 if (NewTypeInfo.getHasRegParm()) {
Douglas Gregor77e274f2010-06-18 21:30:25 +00001661 Diag(New->getLocation(), diag::err_regparm_mismatch)
1662 << NewType->getRegParmType()
1663 << OldType->getRegParmType();
1664 Diag(Old->getLocation(), diag::note_previous_declaration);
1665 return true;
1666 }
John McCall4f5019e2010-12-19 02:44:49 +00001667
1668 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
1669 RequiresAdjustment = true;
1670 }
1671
1672 if (RequiresAdjustment) {
1673 NewType = Context.adjustFunctionType(NewType, NewTypeInfo);
1674 New->setType(QualType(NewType, 0));
1675 NewQType = Context.getCanonicalType(New->getType());
Douglas Gregor77e274f2010-06-18 21:30:25 +00001676 }
1677
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001678 if (getLangOptions().CPlusPlus) {
1679 // (C++98 13.1p2):
1680 // Certain function declarations cannot be overloaded:
Mike Stump11289f42009-09-09 15:08:12 +00001681 // -- Function declarations that differ only in the return type
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001682 // cannot be overloaded.
John McCall4f5019e2010-12-19 02:44:49 +00001683 QualType OldReturnType = OldType->getResultType();
1684 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00001685 QualType ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001686 if (OldReturnType != NewReturnType) {
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00001687 if (NewReturnType->isObjCObjectPointerType()
1688 && OldReturnType->isObjCObjectPointerType())
1689 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
1690 if (ResQT.isNull()) {
Argyrios Kyrtzidis3d320862011-02-05 05:54:49 +00001691 if (New->isCXXClassMember() && New->isOutOfLine())
1692 Diag(New->getLocation(),
1693 diag::err_member_def_does_not_match_ret_type) << New;
1694 else
1695 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00001696 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1697 return true;
1698 }
1699 else
1700 NewQType = ResQT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001701 }
1702
1703 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
John McCall43314ab2010-04-13 07:45:41 +00001704 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001705 if (OldMethod && NewMethod) {
John McCall43314ab2010-04-13 07:45:41 +00001706 // Preserve triviality.
1707 NewMethod->setTrivial(OldMethod->isTrivial());
Francois Pichetc2fac712011-05-14 19:17:07 +00001708
John McCall43314ab2010-04-13 07:45:41 +00001709 bool isFriend = NewMethod->getFriendObjectKind();
1710
Francois Pichetc2fac712011-05-14 19:17:07 +00001711 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord()) {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001712 // -- Member function declarations with the same name and the
1713 // same parameter types cannot be overloaded if any of them
1714 // is a static member function declaration.
1715 if (OldMethod->isStatic() || NewMethod->isStatic()) {
1716 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
1717 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1718 return true;
1719 }
1720
1721 // C++ [class.mem]p1:
1722 // [...] A member shall not be declared twice in the
1723 // member-specification, except that a nested class or member
1724 // class template can be declared and then later defined.
1725 unsigned NewDiag;
1726 if (isa<CXXConstructorDecl>(OldMethod))
1727 NewDiag = diag::err_constructor_redeclared;
1728 else if (isa<CXXDestructorDecl>(NewMethod))
1729 NewDiag = diag::err_destructor_redeclared;
1730 else if (isa<CXXConversionDecl>(NewMethod))
1731 NewDiag = diag::err_conv_function_redeclared;
1732 else
1733 NewDiag = diag::err_member_redeclared;
1734
1735 Diag(New->getLocation(), NewDiag);
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001736 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
John McCall43314ab2010-04-13 07:45:41 +00001737
1738 // Complain if this is an explicit declaration of a special
1739 // member that was initially declared implicitly.
1740 //
1741 // As an exception, it's okay to befriend such methods in order
1742 // to permit the implicit constructor/destructor/operator calls.
1743 } else if (OldMethod->isImplicit()) {
1744 if (isFriend) {
1745 NewMethod->setImplicit();
1746 } else {
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001747 Diag(NewMethod->getLocation(),
1748 diag::err_definition_of_implicitly_declared_member)
Anders Carlsson05bf0092010-04-22 05:40:53 +00001749 << New << getSpecialMember(OldMethod);
Anders Carlsson1f78b2b2009-12-04 22:33:25 +00001750 return true;
1751 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00001752 } else if (OldMethod->isExplicitlyDefaulted()) {
1753 Diag(NewMethod->getLocation(),
1754 diag::err_definition_of_explicitly_defaulted_member)
1755 << getSpecialMember(OldMethod);
1756 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001757 }
1758 }
1759
1760 // (C++98 8.3.5p3):
1761 // All declarations for a function shall agree exactly in both the
1762 // return type and the parameter-type-list.
John McCall4f5019e2010-12-19 02:44:49 +00001763 // We also want to respect all the extended bits except noreturn.
1764
1765 // noreturn should now match unless the old type info didn't have it.
1766 QualType OldQTypeForComparison = OldQType;
1767 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
1768 assert(OldQType == QualType(OldType, 0));
1769 const FunctionType *OldTypeForComparison
1770 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
1771 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
1772 assert(OldQTypeForComparison.isCanonical());
1773 }
1774
1775 if (OldQTypeForComparison == NewQType)
Douglas Gregore62c0a42009-02-24 01:23:02 +00001776 return MergeCompatibleFunctionDecls(New, Old);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001777
1778 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor89f238c2008-04-21 02:02:58 +00001779 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001780
1781 // C: Function types need to be compatible, not identical. This handles
Steve Naroff012484d2008-01-14 20:51:29 +00001782 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001783 if (!getLangOptions().CPlusPlus &&
Eli Friedman47f77112008-08-22 00:56:42 +00001784 Context.typesAreCompatible(OldQType, NewQType)) {
John McCall9dd450b2009-09-21 23:43:11 +00001785 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
1786 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001787 const FunctionProtoType *OldProto = 0;
1788 if (isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregora74a2972009-03-06 22:43:54 +00001789 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregorbcbf8632009-02-16 18:20:44 +00001790 // The old declaration provided a function prototype, but the
1791 // new declaration does not. Merge in the prototype.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001792 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
Douglas Gregorbcbf8632009-02-16 18:20:44 +00001793 llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
1794 OldProto->arg_type_end());
1795 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
Jay Foad7d0479f2009-05-21 09:52:38 +00001796 ParamTypes.data(), ParamTypes.size(),
John McCalldb40c7f2010-12-14 08:05:40 +00001797 OldProto->getExtProtoInfo());
Douglas Gregorbcbf8632009-02-16 18:20:44 +00001798 New->setType(NewQType);
Anders Carlssone0dd1d52009-05-14 21:46:00 +00001799 New->setHasInheritedPrototype();
Douglas Gregorbfdd6072009-02-16 20:58:07 +00001800
1801 // Synthesize a parameter for each argument type.
1802 llvm::SmallVector<ParmVarDecl*, 16> Params;
Mike Stump11289f42009-09-09 15:08:12 +00001803 for (FunctionProtoType::arg_type_iterator
1804 ParamType = OldProto->arg_type_begin(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00001805 ParamEnd = OldProto->arg_type_end();
1806 ParamType != ParamEnd; ++ParamType) {
1807 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001808 SourceLocation(),
Douglas Gregorbfdd6072009-02-16 20:58:07 +00001809 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00001810 *ParamType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00001811 SC_None, SC_None,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001812 0);
John McCall8fb0d9d2011-05-01 22:35:37 +00001813 Param->setScopeInfo(0, Params.size());
Douglas Gregorbfdd6072009-02-16 20:58:07 +00001814 Param->setImplicit();
1815 Params.push_back(Param);
1816 }
1817
Douglas Gregord5058122010-02-11 01:19:42 +00001818 New->setParams(Params.data(), Params.size());
Mike Stump11289f42009-09-09 15:08:12 +00001819 }
Douglas Gregorbcbf8632009-02-16 18:20:44 +00001820
Douglas Gregore62c0a42009-02-24 01:23:02 +00001821 return MergeCompatibleFunctionDecls(New, Old);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00001822 }
Chris Lattner45d561a2007-11-06 06:07:26 +00001823
Douglas Gregora74a2972009-03-06 22:43:54 +00001824 // GNU C permits a K&R definition to follow a prototype declaration
1825 // if the declared types of the parameters in the K&R definition
1826 // match the types in the prototype declaration, even when the
1827 // promoted types of the parameters from the K&R definition differ
1828 // from the types in the prototype. GCC then keeps the types from
1829 // the prototype.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001830 //
1831 // If a variadic prototype is followed by a non-variadic K&R definition,
1832 // the K&R definition becomes variadic. This is sort of an edge case, but
1833 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
1834 // C99 6.9.1p8.
Douglas Gregora74a2972009-03-06 22:43:54 +00001835 if (!getLangOptions().CPlusPlus &&
Douglas Gregora74a2972009-03-06 22:43:54 +00001836 Old->hasPrototype() && !New->hasPrototype() &&
John McCall9dd450b2009-09-21 23:43:11 +00001837 New->getType()->getAs<FunctionProtoType>() &&
Douglas Gregora74a2972009-03-06 22:43:54 +00001838 Old->getNumParams() == New->getNumParams()) {
1839 llvm::SmallVector<QualType, 16> ArgTypes;
1840 llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
Mike Stump11289f42009-09-09 15:08:12 +00001841 const FunctionProtoType *OldProto
John McCall9dd450b2009-09-21 23:43:11 +00001842 = Old->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00001843 const FunctionProtoType *NewProto
John McCall9dd450b2009-09-21 23:43:11 +00001844 = New->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00001845
Douglas Gregora74a2972009-03-06 22:43:54 +00001846 // Determine whether this is the GNU C extension.
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001847 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
1848 NewProto->getResultType());
1849 bool LooseCompatible = !MergedReturn.isNull();
Mike Stump11289f42009-09-09 15:08:12 +00001850 for (unsigned Idx = 0, End = Old->getNumParams();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001851 LooseCompatible && Idx != End; ++Idx) {
Douglas Gregora74a2972009-03-06 22:43:54 +00001852 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
1853 ParmVarDecl *NewParm = New->getParamDecl(Idx);
Mike Stump11289f42009-09-09 15:08:12 +00001854 if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregora74a2972009-03-06 22:43:54 +00001855 NewProto->getArgType(Idx))) {
1856 ArgTypes.push_back(NewParm->getType());
1857 } else if (Context.typesAreCompatible(OldParm->getType(),
Douglas Gregor17ea3f52010-07-29 15:18:02 +00001858 NewParm->getType(),
1859 /*CompareUnqualified=*/true)) {
Mike Stump11289f42009-09-09 15:08:12 +00001860 GNUCompatibleParamWarning Warn
Douglas Gregora74a2972009-03-06 22:43:54 +00001861 = { OldParm, NewParm, NewProto->getArgType(Idx) };
1862 Warnings.push_back(Warn);
1863 ArgTypes.push_back(NewParm->getType());
1864 } else
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001865 LooseCompatible = false;
Douglas Gregora74a2972009-03-06 22:43:54 +00001866 }
1867
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001868 if (LooseCompatible) {
Douglas Gregora74a2972009-03-06 22:43:54 +00001869 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
1870 Diag(Warnings[Warn].NewParm->getLocation(),
1871 diag::ext_param_promoted_not_compatible_with_prototype)
1872 << Warnings[Warn].PromotedType
1873 << Warnings[Warn].OldParm->getType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00001874 if (Warnings[Warn].OldParm->getLocation().isValid())
1875 Diag(Warnings[Warn].OldParm->getLocation(),
1876 diag::note_previous_declaration);
Douglas Gregora74a2972009-03-06 22:43:54 +00001877 }
1878
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00001879 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
1880 ArgTypes.size(),
John McCalldb40c7f2010-12-14 08:05:40 +00001881 OldProto->getExtProtoInfo()));
Douglas Gregora74a2972009-03-06 22:43:54 +00001882 return MergeCompatibleFunctionDecls(New, Old);
1883 }
1884
1885 // Fall through to diagnose conflicting types.
1886 }
1887
Steve Naroff17832a42008-01-16 15:01:34 +00001888 // A function that has already been declared has been redeclared or defined
1889 // with a different type- show appropriate diagnostic
Douglas Gregor15fc9562009-09-12 00:22:50 +00001890 if (unsigned BuiltinID = Old->getBuiltinID()) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001891 // The user has declared a builtin function with an incompatible
1892 // signature.
1893 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
1894 // The function the user is redeclaring is a library-defined
1895 // function like 'malloc' or 'printf'. Warn about the
Douglas Gregor893c2c92009-03-23 17:47:24 +00001896 // redeclaration, then pretend that we don't know about this
1897 // library built-in.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001898 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
1899 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
1900 << Old << Old->getType();
Douglas Gregor893c2c92009-03-23 17:47:24 +00001901 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
1902 Old->setInvalidDecl();
1903 return false;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001904 }
Steve Naroff17832a42008-01-16 15:01:34 +00001905
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001906 PrevDiag = diag::note_previous_builtin_declaration;
1907 }
1908
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001909 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001910 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001911 return true;
Chris Lattner01564d92007-01-27 19:27:06 +00001912}
1913
Douglas Gregore62c0a42009-02-24 01:23:02 +00001914/// \brief Completes the merge of two function declarations that are
Mike Stump11289f42009-09-09 15:08:12 +00001915/// known to be compatible.
Douglas Gregore62c0a42009-02-24 01:23:02 +00001916///
1917/// This routine handles the merging of attributes and other
1918/// properties of function declarations form the old declaration to
1919/// the new declaration, once we know that New is in fact a
1920/// redeclaration of Old.
1921///
1922/// \returns false
1923bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
1924 // Merge the attributes
John McCallf79e87d2011-03-02 04:00:57 +00001925 mergeDeclAttributes(New, Old, Context);
Douglas Gregore62c0a42009-02-24 01:23:02 +00001926
1927 // Merge the storage class.
John McCall8e7d6562010-08-26 03:08:43 +00001928 if (Old->getStorageClass() != SC_Extern &&
1929 Old->getStorageClass() != SC_None)
Douglas Gregor76fe50c2009-04-28 06:37:30 +00001930 New->setStorageClass(Old->getStorageClass());
Douglas Gregore62c0a42009-02-24 01:23:02 +00001931
Douglas Gregore62c0a42009-02-24 01:23:02 +00001932 // Merge "pure" flag.
1933 if (Old->isPure())
1934 New->setPure();
1935
John McCallf79e87d2011-03-02 04:00:57 +00001936 // Merge attributes from the parameters. These can mismatch with K&R
1937 // declarations.
1938 if (New->getNumParams() == Old->getNumParams())
1939 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
1940 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
1941 Context);
1942
Douglas Gregore62c0a42009-02-24 01:23:02 +00001943 if (getLangOptions().CPlusPlus)
1944 return MergeCXXFunctionDecl(New, Old);
1945
1946 return false;
1947}
1948
John McCall31168b02011-06-15 23:02:42 +00001949
John McCallf79e87d2011-03-02 04:00:57 +00001950void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
1951 const ObjCMethodDecl *oldMethod) {
1952 // Merge the attributes.
1953 mergeDeclAttributes(newMethod, oldMethod, Context);
1954
1955 // Merge attributes from the parameters.
1956 for (ObjCMethodDecl::param_iterator oi = oldMethod->param_begin(),
1957 ni = newMethod->param_begin(), ne = newMethod->param_end();
1958 ni != ne; ++ni, ++oi)
Douglas Gregor33823722011-06-11 01:09:30 +00001959 mergeParamDeclAttributes(*ni, *oi, Context);
1960
1961 CheckObjCMethodOverride(newMethod, oldMethod, true);
John McCallf79e87d2011-03-02 04:00:57 +00001962}
1963
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001964/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
1965/// scope as a previous declaration 'Old'. Figure out how to merge their types,
Richard Smith30482bc2011-02-20 03:19:35 +00001966/// emitting diagnostics as appropriate.
1967///
1968/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
1969/// to here in AddInitializerToDecl and AddCXXDirectInitializerToDecl. We can't
1970/// check them before the initializer is attached.
1971///
1972void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) {
1973 if (New->isInvalidDecl() || Old->isInvalidDecl())
1974 return;
1975
1976 QualType MergedT;
1977 if (getLangOptions().CPlusPlus) {
1978 AutoType *AT = New->getType()->getContainedAutoType();
1979 if (AT && !AT->isDeduced()) {
1980 // We don't know what the new type is until the initializer is attached.
1981 return;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001982 } else if (Context.hasSameType(New->getType(), Old->getType())) {
1983 // These could still be something that needs exception specs checked.
1984 return MergeVarDeclExceptionSpecs(New, Old);
1985 }
Richard Smith30482bc2011-02-20 03:19:35 +00001986 // C++ [basic.link]p10:
1987 // [...] the types specified by all declarations referring to a given
1988 // object or function shall be identical, except that declarations for an
1989 // array object can specify array types that differ by the presence or
1990 // absence of a major array bound (8.3.4).
1991 else if (Old->getType()->isIncompleteArrayType() &&
1992 New->getType()->isArrayType()) {
1993 CanQual<ArrayType> OldArray
1994 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1995 CanQual<ArrayType> NewArray
1996 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1997 if (OldArray->getElementType() == NewArray->getElementType())
1998 MergedT = New->getType();
1999 } else if (Old->getType()->isArrayType() &&
2000 New->getType()->isIncompleteArrayType()) {
2001 CanQual<ArrayType> OldArray
2002 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2003 CanQual<ArrayType> NewArray
2004 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2005 if (OldArray->getElementType() == NewArray->getElementType())
2006 MergedT = Old->getType();
2007 } else if (New->getType()->isObjCObjectPointerType()
2008 && Old->getType()->isObjCObjectPointerType()) {
2009 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2010 Old->getType());
2011 }
2012 } else {
2013 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2014 }
2015 if (MergedT.isNull()) {
2016 Diag(New->getLocation(), diag::err_redefinition_different_type)
2017 << New->getDeclName();
2018 Diag(Old->getLocation(), diag::note_previous_definition);
2019 return New->setInvalidDecl();
2020 }
2021 New->setType(MergedT);
2022}
2023
Chris Lattner01564d92007-01-27 19:27:06 +00002024/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2025/// and scope as a previous declaration 'Old'. Figure out how to resolve this
2026/// situation, merging decls or emitting diagnostics as appropriate.
2027///
Mike Stump11289f42009-09-09 15:08:12 +00002028/// Tentative definition rules (C99 6.9.2p2) are checked by
2029/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
Steve Naroff5bb8f222008-08-08 17:50:35 +00002030/// definitions here, since the initializer hasn't been attached.
Mike Stump11289f42009-09-09 15:08:12 +00002031///
John McCall1f82f242009-11-18 22:49:29 +00002032void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
2033 // If the new decl is already invalid, don't do any other checking.
2034 if (New->isInvalidDecl())
2035 return;
Mike Stump11289f42009-09-09 15:08:12 +00002036
Chris Lattnerc511efb2007-01-27 19:32:14 +00002037 // Verify the old decl was also a variable.
John McCall1f82f242009-11-18 22:49:29 +00002038 VarDecl *Old = 0;
2039 if (!Previous.isSingleResult() ||
2040 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
Chris Lattner651d42d2008-11-20 06:38:18 +00002041 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002042 << New->getDeclName();
John McCall1f82f242009-11-18 22:49:29 +00002043 Diag(Previous.getRepresentativeDecl()->getLocation(),
2044 diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002045 return New->setInvalidDecl();
Chris Lattnerc511efb2007-01-27 19:32:14 +00002046 }
Chris Lattner84966392008-03-03 03:28:21 +00002047
Douglas Gregor2c7d9292010-08-30 14:32:14 +00002048 // C++ [class.mem]p1:
2049 // A member shall not be declared twice in the member-specification [...]
2050 //
2051 // Here, we need only consider static data members.
2052 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
2053 Diag(New->getLocation(), diag::err_duplicate_member)
2054 << New->getIdentifier();
2055 Diag(Old->getLocation(), diag::note_previous_declaration);
2056 New->setInvalidDecl();
2057 }
2058
John McCallf79e87d2011-03-02 04:00:57 +00002059 mergeDeclAttributes(New, Old, Context);
Fariborz Jahanian33e02262011-06-22 22:08:50 +00002060 // Warn if an already-declared variable is made a weak_import in a subsequent declaration
Fariborz Jahanianab578bf2011-06-20 17:50:03 +00002061 if (New->getAttr<WeakImportAttr>() &&
2062 Old->getStorageClass() == SC_None &&
Fariborz Jahanian33e02262011-06-22 22:08:50 +00002063 !Old->getAttr<WeakImportAttr>()) {
2064 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
2065 Diag(Old->getLocation(), diag::note_previous_definition);
2066 // Remove weak_import attribute on new declaration.
Fariborz Jahanian0dfc9502011-06-23 17:50:10 +00002067 New->dropAttr<WeakImportAttr>();
Fariborz Jahanian33e02262011-06-22 22:08:50 +00002068 }
Chris Lattner84966392008-03-03 03:28:21 +00002069
Richard Smith30482bc2011-02-20 03:19:35 +00002070 // Merge the types.
2071 MergeVarDeclTypes(New, Old);
2072 if (New->isInvalidDecl())
2073 return;
Douglas Gregor04e9a032009-03-11 23:52:16 +00002074
Steve Naroff1e787362008-01-30 00:44:01 +00002075 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
John McCall8e7d6562010-08-26 03:08:43 +00002076 if (New->getStorageClass() == SC_Static &&
2077 (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002078 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002079 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002080 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00002081 }
Mike Stump11289f42009-09-09 15:08:12 +00002082 // C99 6.2.2p4:
Douglas Gregor37311622009-03-19 22:01:50 +00002083 // For an identifier declared with the storage-class specifier
2084 // extern in a scope in which a prior declaration of that
2085 // identifier is visible,23) if the prior declaration specifies
2086 // internal or external linkage, the linkage of the identifier at
2087 // the later declaration is the same as the linkage specified at
2088 // the prior declaration. If no prior declaration is visible, or
2089 // if the prior declaration specifies no linkage, then the
2090 // identifier has external linkage.
Douglas Gregord4eca012009-03-23 16:17:01 +00002091 if (New->hasExternalStorage() && Old->hasLinkage())
Douglas Gregor37311622009-03-19 22:01:50 +00002092 /* Okay */;
John McCall8e7d6562010-08-26 03:08:43 +00002093 else if (New->getStorageClass() != SC_Static &&
2094 Old->getStorageClass() == SC_Static) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002095 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002096 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002097 return New->setInvalidDecl();
Steve Naroff1e787362008-01-30 00:44:01 +00002098 }
Daniel Dunbar0ca16602009-04-14 02:25:56 +00002099
Argyrios Kyrtzidis819f6102011-01-31 07:04:46 +00002100 // Check if extern is followed by non-extern and vice-versa.
2101 if (New->hasExternalStorage() &&
2102 !Old->hasLinkage() && Old->isLocalVarDecl()) {
2103 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
2104 Diag(Old->getLocation(), diag::note_previous_definition);
2105 return New->setInvalidDecl();
2106 }
2107 if (Old->hasExternalStorage() &&
2108 !New->hasLinkage() && New->isLocalVarDecl()) {
2109 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
2110 Diag(Old->getLocation(), diag::note_previous_definition);
2111 return New->setInvalidDecl();
2112 }
2113
Steve Naroffa5629372008-09-17 14:05:40 +00002114 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Mike Stump11289f42009-09-09 15:08:12 +00002115
Daniel Dunbar0ca16602009-04-14 02:25:56 +00002116 // FIXME: The test for external storage here seems wrong? We still
2117 // need to check for mismatches.
2118 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
Douglas Gregor04e9a032009-03-11 23:52:16 +00002119 // Don't complain about out-of-line definitions of static members.
2120 !(Old->getLexicalDeclContext()->isRecord() &&
2121 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattnere3d20d92008-11-23 21:45:46 +00002122 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002123 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002124 return New->setInvalidDecl();
Steve Naroff6fbf0dc2007-03-16 00:33:25 +00002125 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00002126
Eli Friedmand5c0eed2009-04-19 20:27:55 +00002127 if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
2128 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
2129 Diag(Old->getLocation(), diag::note_previous_definition);
2130 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
2131 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
2132 Diag(Old->getLocation(), diag::note_previous_definition);
2133 }
2134
Sebastian Redlf1842912010-02-02 18:35:11 +00002135 // C++ doesn't have tentative definitions, so go right ahead and check here.
2136 const VarDecl *Def;
Sebastian Redld85be0c2010-02-03 02:08:48 +00002137 if (getLangOptions().CPlusPlus &&
2138 New->isThisDeclarationADefinition() == VarDecl::Definition &&
Sebastian Redlf1842912010-02-02 18:35:11 +00002139 (Def = Old->getDefinition())) {
2140 Diag(New->getLocation(), diag::err_redefinition)
2141 << New->getDeclName();
2142 Diag(Def->getLocation(), diag::note_previous_definition);
2143 New->setInvalidDecl();
2144 return;
2145 }
Fariborz Jahanianad356a12010-06-25 00:05:45 +00002146 // c99 6.2.2 P4.
2147 // For an identifier declared with the storage-class specifier extern in a
2148 // scope in which a prior declaration of that identifier is visible, if
2149 // the prior declaration specifies internal or external linkage, the linkage
2150 // of the identifier at the later declaration is the same as the linkage
2151 // specified at the prior declaration.
2152 // FIXME. revisit this code.
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00002153 if (New->hasExternalStorage() &&
Fariborz Jahanian4f9c9d62010-06-24 18:50:41 +00002154 Old->getLinkage() == InternalLinkage &&
2155 New->getDeclContext() == Old->getDeclContext())
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00002156 New->setStorageClass(Old->getStorageClass());
2157
Douglas Gregor0760fa12009-03-10 23:43:53 +00002158 // Keep a chain of previous declarations.
2159 New->setPreviousDeclaration(Old);
John McCall401982f2010-01-20 21:53:11 +00002160
2161 // Inherit access appropriately.
2162 New->setAccess(Old->getAccess());
Chris Lattner01564d92007-01-27 19:27:06 +00002163}
2164
Chris Lattnerb6738ec2007-01-28 00:38:24 +00002165/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2166/// no declarator (e.g. "struct foo;") is parsed.
John McCall48871652010-08-21 09:40:31 +00002167Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
John McCallaa017372011-03-22 23:00:04 +00002168 DeclSpec &DS) {
Chandler Carruth7c9856d2011-05-03 18:35:10 +00002169 return ParsedFreeStandingDeclSpec(S, AS, DS,
2170 MultiTemplateParamsArg(*this, 0, 0));
2171}
2172
2173/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2174/// no declarator (e.g. "struct foo;") is parsed. It also accopts template
2175/// parameters to cope with template friend declarations.
2176Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2177 DeclSpec &DS,
2178 MultiTemplateParamsArg TemplateParams) {
John McCallc3987482009-10-07 23:34:25 +00002179 Decl *TagD = 0;
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002180 TagDecl *Tag = 0;
2181 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
2182 DS.getTypeSpecType() == DeclSpec::TST_struct ||
2183 DS.getTypeSpecType() == DeclSpec::TST_union ||
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002184 DS.getTypeSpecType() == DeclSpec::TST_enum) {
John McCallba7bf592010-08-24 05:47:05 +00002185 TagD = DS.getRepAsDecl();
John McCallc3987482009-10-07 23:34:25 +00002186
2187 if (!TagD) // We probably had an error
John McCall48871652010-08-21 09:40:31 +00002188 return 0;
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002189
John McCall07e91c02009-08-06 02:15:43 +00002190 // Note that the above type specs guarantee that the
2191 // type rep is a Decl, whereas in many of the others
2192 // it's a Type.
John McCallc3987482009-10-07 23:34:25 +00002193 Tag = dyn_cast<TagDecl>(TagD);
Douglas Gregor1b57ff32009-05-12 23:25:50 +00002194 }
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002195
Nuno Lopese9823fa2009-12-17 11:35:26 +00002196 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
2197 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
2198 // or incomplete types shall not be restrict-qualified."
2199 if (TypeQuals & DeclSpec::TQ_restrict)
2200 Diag(DS.getRestrictSpecLoc(),
2201 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
2202 << DS.getSourceRange();
2203 }
2204
Douglas Gregor3dad8422009-09-26 06:47:28 +00002205 if (DS.isFriendSpecified()) {
John McCallace48cd2010-10-19 01:40:49 +00002206 // If we're dealing with a decl but not a TagDecl, assume that
2207 // whatever routines created it handled the friendship aspect.
2208 if (TagD && !Tag)
John McCall48871652010-08-21 09:40:31 +00002209 return 0;
Chandler Carruth7c9856d2011-05-03 18:35:10 +00002210 return ActOnFriendTypeDecl(S, DS, TemplateParams);
Douglas Gregor3dad8422009-09-26 06:47:28 +00002211 }
John McCallaa017372011-03-22 23:00:04 +00002212
2213 // Track whether we warned about the fact that there aren't any
2214 // declarators.
2215 bool emittedWarning = false;
Douglas Gregor3dad8422009-09-26 06:47:28 +00002216
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002217 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
John McCall53fa7142010-12-24 02:08:15 +00002218 ProcessDeclAttributeList(S, Record, DS.getAttributes().getList());
Chris Lattnerecf328e2009-10-25 22:21:57 +00002219
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002220 if (!Record->getDeclName() && Record->isDefinition() &&
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002221 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
2222 if (getLangOptions().CPlusPlus ||
2223 Record->getDeclContext()->isRecord())
John McCallb54367d2010-05-21 20:45:30 +00002224 return BuildAnonymousStructOrUnion(S, DS, AS, Record);
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002225
Douglas Gregorf19ac0e2010-04-08 21:33:23 +00002226 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002227 << DS.getSourceRange();
John McCallaa017372011-03-22 23:00:04 +00002228 emittedWarning = true;
Douglas Gregor2e7cba62009-03-06 23:06:59 +00002229 }
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002230 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002231
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002232 // Check for Microsoft C extension: anonymous struct.
2233 if (getLangOptions().Microsoft && !getLangOptions().CPlusPlus &&
2234 CurContext->isRecord() &&
2235 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
2236 // Handle 2 kinds of anonymous struct:
2237 // struct STRUCT;
2238 // and
2239 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
2240 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
2241 if ((Record && Record->getDeclName() && !Record->isDefinition()) ||
2242 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
2243 DS.getRepAsType().get()->isStructureType())) {
2244 Diag(DS.getSourceRange().getBegin(), diag::ext_ms_anonymous_struct)
2245 << DS.getSourceRange();
2246 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
2247 }
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002248 }
Douglas Gregor3dad8422009-09-26 06:47:28 +00002249
Douglas Gregoraa8c9722010-07-13 06:24:26 +00002250 if (getLangOptions().CPlusPlus &&
2251 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
2252 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
2253 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
John McCallaa017372011-03-22 23:00:04 +00002254 !Enum->getIdentifier() && !Enum->isInvalidDecl()) {
Douglas Gregoraa8c9722010-07-13 06:24:26 +00002255 Diag(Enum->getLocation(), diag::ext_no_declarators)
2256 << DS.getSourceRange();
John McCallaa017372011-03-22 23:00:04 +00002257 emittedWarning = true;
2258 }
2259
2260 // Skip all the checks below if we have a type error.
2261 if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD;
Douglas Gregoraa8c9722010-07-13 06:24:26 +00002262
John McCallaa017372011-03-22 23:00:04 +00002263 if (!DS.isMissingDeclaratorOk()) {
Douglas Gregor2d9dde0e2009-01-22 16:23:54 +00002264 // Warn about typedefs of enums without names, since this is an
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00002265 // extension in both Microsoft and GNU.
Douglas Gregor051d8fd2009-01-17 02:55:50 +00002266 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
2267 Tag && isa<EnumDecl>(Tag)) {
Douglas Gregor3a8e0d72010-07-16 15:40:40 +00002268 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
2269 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00002270 return Tag;
Douglas Gregor2b136fe2009-01-13 23:10:51 +00002271 }
2272
Douglas Gregorf19ac0e2010-04-08 21:33:23 +00002273 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
Sebastian Redla2b5e312008-12-28 15:28:59 +00002274 << DS.getSourceRange();
John McCallaa017372011-03-22 23:00:04 +00002275 emittedWarning = true;
Sebastian Redla2b5e312008-12-28 15:28:59 +00002276 }
Mike Stump11289f42009-09-09 15:08:12 +00002277
John McCallaa017372011-03-22 23:00:04 +00002278 // We're going to complain about a bunch of spurious specifiers;
2279 // only do this if we're declaring a tag, because otherwise we
2280 // should be getting diag::ext_no_declarators.
2281 if (emittedWarning || (TagD && TagD->isInvalidDecl()))
2282 return TagD;
2283
John McCall4d55f5a2011-03-26 02:09:52 +00002284 // Note that a linkage-specification sets a storage class, but
2285 // 'extern "C" struct foo;' is actually valid and not theoretically
2286 // useless.
John McCallaa017372011-03-22 23:00:04 +00002287 if (DeclSpec::SCS scs = DS.getStorageClassSpec())
John McCall4d55f5a2011-03-26 02:09:52 +00002288 if (!DS.isExternInLinkageSpec())
2289 Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier)
2290 << DeclSpec::getSpecifierName(scs);
2291
John McCallaa017372011-03-22 23:00:04 +00002292 if (DS.isThreadSpecified())
2293 Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread";
2294 if (DS.getTypeQualifiers()) {
2295 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2296 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const";
2297 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2298 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile";
2299 // Restrict is covered above.
2300 }
2301 if (DS.isInlineSpecified())
2302 Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline";
2303 if (DS.isVirtualSpecified())
2304 Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual";
2305 if (DS.isExplicitSpecified())
2306 Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit";
2307
2308 // FIXME: Warn on useless attributes
2309
John McCall48871652010-08-21 09:40:31 +00002310 return TagD;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002311}
2312
Fariborz Jahanian1db5c942010-09-28 20:42:35 +00002313/// ActOnVlaStmt - This rouine if finds a vla expression in a decl spec.
2314/// builds a statement for it and returns it so it is evaluated.
2315StmtResult Sema::ActOnVlaStmt(const DeclSpec &DS) {
2316 StmtResult R;
2317 if (DS.getTypeSpecType() == DeclSpec::TST_typeofExpr) {
2318 Expr *Exp = DS.getRepAsExpr();
2319 QualType Ty = Exp->getType();
2320 if (Ty->isPointerType()) {
2321 do
2322 Ty = Ty->getAs<PointerType>()->getPointeeType();
2323 while (Ty->isPointerType());
2324 }
2325 if (Ty->isVariableArrayType()) {
2326 R = ActOnExprStmt(MakeFullExpr(Exp));
2327 }
2328 }
2329 return R;
2330}
2331
John McCallea305ed2009-12-18 10:40:03 +00002332/// We are trying to inject an anonymous member into the given scope;
John McCall1f82f242009-11-18 22:49:29 +00002333/// check if there's an existing declaration that can't be overloaded.
2334///
2335/// \return true if this is a forbidden redeclaration
John McCallea305ed2009-12-18 10:40:03 +00002336static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
2337 Scope *S,
Fariborz Jahanian53967e22010-01-22 18:30:17 +00002338 DeclContext *Owner,
John McCallea305ed2009-12-18 10:40:03 +00002339 DeclarationName Name,
2340 SourceLocation NameLoc,
2341 unsigned diagnostic) {
2342 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
2343 Sema::ForRedeclaration);
2344 if (!SemaRef.LookupName(R, S)) return false;
John McCall1f82f242009-11-18 22:49:29 +00002345
John McCallea305ed2009-12-18 10:40:03 +00002346 if (R.getAsSingle<TagDecl>())
John McCall1f82f242009-11-18 22:49:29 +00002347 return false;
2348
2349 // Pick a representative declaration.
John McCallea305ed2009-12-18 10:40:03 +00002350 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
Argyrios Kyrtzidise619e992010-09-23 14:26:01 +00002351 assert(PrevDecl && "Expected a non-null Decl");
2352
2353 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
2354 return false;
John McCall1f82f242009-11-18 22:49:29 +00002355
John McCallea305ed2009-12-18 10:40:03 +00002356 SemaRef.Diag(NameLoc, diagnostic) << Name;
2357 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
John McCall1f82f242009-11-18 22:49:29 +00002358
2359 return true;
2360}
2361
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002362/// InjectAnonymousStructOrUnionMembers - Inject the members of the
2363/// anonymous struct or union AnonRecord into the owning context Owner
2364/// and scope S. This routine will be invoked just after we realize
2365/// that an unnamed union or struct is actually an anonymous union or
2366/// struct, e.g.,
2367///
2368/// @code
2369/// union {
2370/// int i;
2371/// float f;
2372/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
2373/// // f into the surrounding scope.x
2374/// @endcode
2375///
2376/// This routine is recursive, injecting the names of nested anonymous
2377/// structs/unions into the owning context and scope as well.
John McCallb54367d2010-05-21 20:45:30 +00002378static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
2379 DeclContext *Owner,
2380 RecordDecl *AnonRecord,
Francois Pichet783dd6e2010-11-21 06:08:52 +00002381 AccessSpecifier AS,
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002382 llvm::SmallVector<NamedDecl*, 2> &Chaining,
2383 bool MSAnonStruct) {
John McCall1f82f242009-11-18 22:49:29 +00002384 unsigned diagKind
2385 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
2386 : diag::err_anonymous_struct_member_redecl;
2387
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002388 bool Invalid = false;
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002389
2390 // Look every FieldDecl and IndirectFieldDecl with a name.
2391 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
2392 DEnd = AnonRecord->decls_end();
2393 D != DEnd; ++D) {
2394 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
2395 cast<NamedDecl>(*D)->getDeclName()) {
2396 ValueDecl *VD = cast<ValueDecl>(*D);
2397 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
2398 VD->getLocation(), diagKind)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002399 // C++ [class.union]p2:
2400 // The names of the members of an anonymous union shall be
2401 // distinct from the names of any other entity in the
2402 // scope in which the anonymous union is declared.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002403 Invalid = true;
2404 } else {
2405 // C++ [class.union]p2:
2406 // For the purpose of name lookup, after the anonymous union
2407 // definition, the members of the anonymous union are
2408 // considered to have been defined in the scope in which the
2409 // anonymous union is declared.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002410 unsigned OldChainingSize = Chaining.size();
2411 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
2412 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
2413 PE = IF->chain_end(); PI != PE; ++PI)
2414 Chaining.push_back(*PI);
2415 else
2416 Chaining.push_back(VD);
2417
Francois Pichet783dd6e2010-11-21 06:08:52 +00002418 assert(Chaining.size() >= 2);
2419 NamedDecl **NamedChain =
2420 new (SemaRef.Context)NamedDecl*[Chaining.size()];
2421 for (unsigned i = 0; i < Chaining.size(); i++)
2422 NamedChain[i] = Chaining[i];
2423
2424 IndirectFieldDecl* IndirectField =
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002425 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
2426 VD->getIdentifier(), VD->getType(),
Francois Pichet783dd6e2010-11-21 06:08:52 +00002427 NamedChain, Chaining.size());
2428
2429 IndirectField->setAccess(AS);
2430 IndirectField->setImplicit();
2431 SemaRef.PushOnScopeChains(IndirectField, S);
John McCallb54367d2010-05-21 20:45:30 +00002432
2433 // That includes picking up the appropriate access specifier.
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002434 if (AS != AS_none) IndirectField->setAccess(AS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002435
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002436 Chaining.resize(OldChainingSize);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002437 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002438 }
2439 }
2440
2441 return Invalid;
2442}
2443
Douglas Gregorc4df4072010-04-19 22:54:31 +00002444/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
2445/// a VarDecl::StorageClass. Any error reporting is up to the caller:
John McCall8e7d6562010-08-26 03:08:43 +00002446/// illegal input values are mapped to SC_None.
2447static StorageClass
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00002448StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
Douglas Gregorc4df4072010-04-19 22:54:31 +00002449 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00002450 case DeclSpec::SCS_unspecified: return SC_None;
2451 case DeclSpec::SCS_extern: return SC_Extern;
2452 case DeclSpec::SCS_static: return SC_Static;
2453 case DeclSpec::SCS_auto: return SC_Auto;
2454 case DeclSpec::SCS_register: return SC_Register;
2455 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002456 // Illegal SCSs map to None: error reporting is up to the caller.
2457 case DeclSpec::SCS_mutable: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00002458 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002459 }
2460 llvm_unreachable("unknown storage class specifier");
2461}
2462
2463/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
John McCall8e7d6562010-08-26 03:08:43 +00002464/// a StorageClass. Any error reporting is up to the caller:
2465/// illegal input values are mapped to SC_None.
2466static StorageClass
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00002467StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
Douglas Gregorc4df4072010-04-19 22:54:31 +00002468 switch (StorageClassSpec) {
John McCall8e7d6562010-08-26 03:08:43 +00002469 case DeclSpec::SCS_unspecified: return SC_None;
2470 case DeclSpec::SCS_extern: return SC_Extern;
2471 case DeclSpec::SCS_static: return SC_Static;
2472 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002473 // Illegal SCSs map to None: error reporting is up to the caller.
2474 case DeclSpec::SCS_auto: // Fall through.
2475 case DeclSpec::SCS_mutable: // Fall through.
2476 case DeclSpec::SCS_register: // Fall through.
John McCall8e7d6562010-08-26 03:08:43 +00002477 case DeclSpec::SCS_typedef: return SC_None;
Douglas Gregorc4df4072010-04-19 22:54:31 +00002478 }
2479 llvm_unreachable("unknown storage class specifier");
2480}
2481
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002482/// BuildAnonymousStructOrUnion - Handle the declaration of an
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002483/// anonymous structure or union. Anonymous unions are a C++ feature
2484/// (C++ [class.union]) and a GNU C extension; anonymous structures
Mike Stump11289f42009-09-09 15:08:12 +00002485/// are a GNU C and GNU C++ extension.
John McCall48871652010-08-21 09:40:31 +00002486Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2487 AccessSpecifier AS,
2488 RecordDecl *Record) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002489 DeclContext *Owner = Record->getDeclContext();
2490
2491 // Diagnose whether this anonymous struct/union is an extension.
2492 if (Record->isUnion() && !getLangOptions().CPlusPlus)
2493 Diag(Record->getLocation(), diag::ext_anonymous_union);
2494 else if (!Record->isUnion())
2495 Diag(Record->getLocation(), diag::ext_anonymous_struct);
Mike Stump11289f42009-09-09 15:08:12 +00002496
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002497 // C and C++ require different kinds of checks for anonymous
2498 // structs/unions.
2499 bool Invalid = false;
2500 if (getLangOptions().CPlusPlus) {
2501 const char* PrevSpec = 0;
John McCall49bfce42009-08-03 20:12:06 +00002502 unsigned DiagID;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002503 // C++ [class.union]p3:
2504 // Anonymous unions declared in a named namespace or in the
2505 // global namespace shall be declared static.
2506 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
2507 (isa<TranslationUnitDecl>(Owner) ||
Mike Stump11289f42009-09-09 15:08:12 +00002508 (isa<NamespaceDecl>(Owner) &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002509 cast<NamespaceDecl>(Owner)->getDeclName()))) {
2510 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
2511 Invalid = true;
2512
2513 // Recover by adding 'static'.
John McCall49bfce42009-08-03 20:12:06 +00002514 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(),
Peter Collingbournede32b202011-02-11 19:59:54 +00002515 PrevSpec, DiagID, getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +00002516 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002517 // C++ [class.union]p3:
2518 // A storage class is not allowed in a declaration of an
2519 // anonymous union in a class scope.
2520 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
2521 isa<RecordDecl>(Owner)) {
Mike Stump11289f42009-09-09 15:08:12 +00002522 Diag(DS.getStorageClassSpecLoc(),
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002523 diag::err_anonymous_union_with_storage_spec);
2524 Invalid = true;
2525
2526 // Recover by removing the storage specifier.
2527 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
Peter Collingbournede32b202011-02-11 19:59:54 +00002528 PrevSpec, DiagID, getLangOptions());
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002529 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00002530
Douglas Gregor0f8bc972011-05-09 23:05:33 +00002531 // Ignore const/volatile/restrict qualifiers.
2532 if (DS.getTypeQualifiers()) {
2533 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2534 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
2535 << Record->isUnion() << 0
2536 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
2537 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2538 Diag(DS.getVolatileSpecLoc(), diag::ext_anonymous_struct_union_qualified)
2539 << Record->isUnion() << 1
2540 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
2541 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
2542 Diag(DS.getRestrictSpecLoc(), diag::ext_anonymous_struct_union_qualified)
2543 << Record->isUnion() << 2
2544 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
2545
2546 DS.ClearTypeQualifiers();
2547 }
2548
Mike Stump11289f42009-09-09 15:08:12 +00002549 // C++ [class.union]p2:
Douglas Gregorf4d33272009-01-07 19:46:03 +00002550 // The member-specification of an anonymous union shall only
2551 // define non-static data members. [Note: nested types and
2552 // functions cannot be declared within an anonymous union. ]
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002553 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
2554 MemEnd = Record->decls_end();
Douglas Gregorf4d33272009-01-07 19:46:03 +00002555 Mem != MemEnd; ++Mem) {
2556 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
2557 // C++ [class.union]p3:
2558 // An anonymous union shall not have private or protected
2559 // members (clause 11).
John McCallb54367d2010-05-21 20:45:30 +00002560 assert(FD->getAccess() != AS_none);
2561 if (FD->getAccess() != AS_public) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00002562 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
2563 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
2564 Invalid = true;
2565 }
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00002566
Alexis Hunt97ab5542011-05-16 22:41:40 +00002567 // C++ [class.union]p1
2568 // An object of a class with a non-trivial constructor, a non-trivial
2569 // copy constructor, a non-trivial destructor, or a non-trivial copy
2570 // assignment operator cannot be a member of a union, nor can an
2571 // array of such objects.
2572 if (!getLangOptions().CPlusPlus0x && CheckNontrivialField(FD))
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00002573 Invalid = true;
Douglas Gregorf4d33272009-01-07 19:46:03 +00002574 } else if ((*Mem)->isImplicit()) {
2575 // Any implicit members are fine.
Douglas Gregor8761da52009-02-03 00:34:39 +00002576 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
2577 // This is a type that showed up in an
2578 // elaborated-type-specifier inside the anonymous struct or
2579 // union, but which actually declares a type outside of the
2580 // anonymous struct or union. It's okay.
Douglas Gregorf4d33272009-01-07 19:46:03 +00002581 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
2582 if (!MemRecord->isAnonymousStructOrUnion() &&
2583 MemRecord->getDeclName()) {
Francois Pichet4ad4b582010-09-08 11:32:25 +00002584 // Visual C++ allows type definition in anonymous struct or union.
2585 if (getLangOptions().Microsoft)
2586 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
2587 << (int)Record->isUnion();
2588 else {
2589 // This is a nested type declaration.
2590 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
2591 << (int)Record->isUnion();
2592 Invalid = true;
2593 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00002594 }
Abramo Bagnarad7340582010-06-05 05:09:32 +00002595 } else if (isa<AccessSpecDecl>(*Mem)) {
2596 // Any access specifier is fine.
Douglas Gregorf4d33272009-01-07 19:46:03 +00002597 } else {
2598 // We have something that isn't a non-static data
2599 // member. Complain about it.
2600 unsigned DK = diag::err_anonymous_record_bad_member;
2601 if (isa<TypeDecl>(*Mem))
2602 DK = diag::err_anonymous_record_with_type;
2603 else if (isa<FunctionDecl>(*Mem))
2604 DK = diag::err_anonymous_record_with_function;
2605 else if (isa<VarDecl>(*Mem))
2606 DK = diag::err_anonymous_record_with_static;
Francois Pichet4ad4b582010-09-08 11:32:25 +00002607
2608 // Visual C++ allows type definition in anonymous struct or union.
2609 if (getLangOptions().Microsoft &&
2610 DK == diag::err_anonymous_record_with_type)
2611 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
Douglas Gregorf4d33272009-01-07 19:46:03 +00002612 << (int)Record->isUnion();
Francois Pichet4ad4b582010-09-08 11:32:25 +00002613 else {
2614 Diag((*Mem)->getLocation(), DK)
2615 << (int)Record->isUnion();
Douglas Gregorf4d33272009-01-07 19:46:03 +00002616 Invalid = true;
Francois Pichet4ad4b582010-09-08 11:32:25 +00002617 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00002618 }
2619 }
Mike Stump11289f42009-09-09 15:08:12 +00002620 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002621
2622 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002623 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
2624 << (int)getLangOptions().CPlusPlus;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002625 Invalid = true;
2626 }
2627
John McCallfa2d6922009-10-22 23:31:08 +00002628 // Mock up a declarator.
Argyrios Kyrtzidis7baa0af2011-06-28 03:01:18 +00002629 Declarator Dc(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00002630 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
John McCallbcd03502009-12-07 02:54:59 +00002631 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
John McCallfa2d6922009-10-22 23:31:08 +00002632
Mike Stump11289f42009-09-09 15:08:12 +00002633 // Create a declaration for this anonymous struct/union.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002634 NamedDecl *Anon = 0;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002635 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00002636 Anon = FieldDecl::Create(Context, OwningClass,
2637 DS.getSourceRange().getBegin(),
2638 Record->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002639 /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00002640 Context.getTypeDeclType(Record),
John McCallbcd03502009-12-07 02:54:59 +00002641 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00002642 /*BitWidth=*/0, /*Mutable=*/false,
2643 /*HasInit=*/false);
John McCallb54367d2010-05-21 20:45:30 +00002644 Anon->setAccess(AS);
Douglas Gregor9d5938a2010-09-28 20:38:10 +00002645 if (getLangOptions().CPlusPlus)
Douglas Gregorf4d33272009-01-07 19:46:03 +00002646 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002647 } else {
Douglas Gregorc4df4072010-04-19 22:54:31 +00002648 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
2649 assert(SCSpec != DeclSpec::SCS_typedef &&
2650 "Parser allowed 'typedef' as storage class VarDecl.");
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00002651 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregorc4df4072010-04-19 22:54:31 +00002652 if (SCSpec == DeclSpec::SCS_mutable) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002653 // mutable can only appear on non-static class members, so it's always
2654 // an error here
2655 Diag(Record->getLocation(), diag::err_mutable_nonmember);
2656 Invalid = true;
John McCall8e7d6562010-08-26 03:08:43 +00002657 SC = SC_None;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002658 }
Douglas Gregorc4df4072010-04-19 22:54:31 +00002659 SCSpec = DS.getStorageClassSpecAsWritten();
2660 VarDecl::StorageClass SCAsWritten
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00002661 = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002662
Abramo Bagnaradff19302011-03-08 08:55:46 +00002663 Anon = VarDecl::Create(Context, Owner,
2664 DS.getSourceRange().getBegin(),
2665 Record->getLocation(), /*IdentifierInfo=*/0,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00002666 Context.getTypeDeclType(Record),
Douglas Gregorc4df4072010-04-19 22:54:31 +00002667 TInfo, SC, SCAsWritten);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002668 }
Douglas Gregorf4d33272009-01-07 19:46:03 +00002669 Anon->setImplicit();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002670
2671 // Add the anonymous struct/union object to the current
2672 // context. We'll be referencing this object when we refer to one of
2673 // its members.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002674 Owner->addDecl(Anon);
Douglas Gregor456ad1a2010-05-03 15:18:25 +00002675
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002676 // Inject the members of the anonymous struct/union into the owning
2677 // context and into the identifier resolver chain for name lookup
2678 // purposes.
Francois Pichet783dd6e2010-11-21 06:08:52 +00002679 llvm::SmallVector<NamedDecl*, 2> Chain;
2680 Chain.push_back(Anon);
2681
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002682 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
2683 Chain, false))
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002684 Invalid = true;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002685
2686 // Mark this as an anonymous struct/union type. Note that we do not
2687 // do this until after we have already checked and injected the
2688 // members of this anonymous struct/union type, because otherwise
2689 // the members could be injected twice: once by DeclContext when it
2690 // builds its lookup table, and once by
Mike Stump11289f42009-09-09 15:08:12 +00002691 // InjectAnonymousStructOrUnionMembers.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002692 Record->setAnonymousStructOrUnion(true);
2693
2694 if (Invalid)
2695 Anon->setInvalidDecl();
2696
John McCall48871652010-08-21 09:40:31 +00002697 return Anon;
Chris Lattnerb6738ec2007-01-28 00:38:24 +00002698}
2699
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002700/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
2701/// Microsoft C anonymous structure.
2702/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
2703/// Example:
2704///
2705/// struct A { int a; };
2706/// struct B { struct A; int b; };
2707///
2708/// void foo() {
2709/// B var;
2710/// var.a = 3;
2711/// }
2712///
2713Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2714 RecordDecl *Record) {
2715
2716 // If there is no Record, get the record via the typedef.
2717 if (!Record)
2718 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
2719
2720 // Mock up a declarator.
2721 Declarator Dc(DS, Declarator::TypeNameContext);
2722 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
2723 assert(TInfo && "couldn't build declarator info for anonymous struct");
2724
2725 // Create a declaration for this anonymous struct.
2726 NamedDecl* Anon = FieldDecl::Create(Context,
2727 cast<RecordDecl>(CurContext),
2728 DS.getSourceRange().getBegin(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002729 DS.getSourceRange().getBegin(),
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002730 /*IdentifierInfo=*/0,
2731 Context.getTypeDeclType(Record),
2732 TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00002733 /*BitWidth=*/0, /*Mutable=*/false,
2734 /*HasInit=*/false);
Francois Pichet0c71f6c2010-11-23 06:07:27 +00002735 Anon->setImplicit();
2736
2737 // Add the anonymous struct object to the current context.
2738 CurContext->addDecl(Anon);
2739
2740 // Inject the members of the anonymous struct into the current
2741 // context and into the identifier resolver chain for name lookup
2742 // purposes.
2743 llvm::SmallVector<NamedDecl*, 2> Chain;
2744 Chain.push_back(Anon);
2745
2746 if (InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
2747 Record->getDefinition(),
2748 AS_none, Chain, true))
2749 Anon->setInvalidDecl();
2750
2751 return Anon;
2752}
Steve Naroff2fea1392007-09-02 02:04:30 +00002753
Douglas Gregor92751d42008-11-17 22:58:34 +00002754/// GetNameForDeclarator - Determine the full declaration name for the
2755/// given Declarator.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002756DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
Douglas Gregora121b752009-11-03 16:56:39 +00002757 return GetNameFromUnqualifiedId(D.getName());
2758}
2759
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002760/// \brief Retrieves the declaration name from a parsed unqualified-id.
2761DeclarationNameInfo
2762Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
2763 DeclarationNameInfo NameInfo;
2764 NameInfo.setLoc(Name.StartLocation);
2765
Douglas Gregor7861a802009-11-03 01:35:08 +00002766 switch (Name.getKind()) {
Alexis Hunt34458502009-11-28 04:44:28 +00002767
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00002768 case UnqualifiedId::IK_ImplicitSelfParam:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002769 case UnqualifiedId::IK_Identifier:
2770 NameInfo.setName(Name.Identifier);
2771 NameInfo.setLoc(Name.StartLocation);
2772 return NameInfo;
Alexis Hunt34458502009-11-28 04:44:28 +00002773
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002774 case UnqualifiedId::IK_OperatorFunctionId:
2775 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
2776 Name.OperatorFunctionId.Operator));
2777 NameInfo.setLoc(Name.StartLocation);
2778 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
2779 = Name.OperatorFunctionId.SymbolLocations[0];
2780 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
2781 = Name.EndLocation.getRawEncoding();
2782 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002783
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002784 case UnqualifiedId::IK_LiteralOperatorId:
2785 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
2786 Name.Identifier));
2787 NameInfo.setLoc(Name.StartLocation);
2788 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
2789 return NameInfo;
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002790
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002791 case UnqualifiedId::IK_ConversionFunctionId: {
2792 TypeSourceInfo *TInfo;
2793 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
2794 if (Ty.isNull())
2795 return DeclarationNameInfo();
2796 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
2797 Context.getCanonicalType(Ty)));
2798 NameInfo.setLoc(Name.StartLocation);
2799 NameInfo.setNamedTypeInfo(TInfo);
2800 return NameInfo;
Douglas Gregord90fd522009-09-25 21:45:23 +00002801 }
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002802
2803 case UnqualifiedId::IK_ConstructorName: {
2804 TypeSourceInfo *TInfo;
2805 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
2806 if (Ty.isNull())
2807 return DeclarationNameInfo();
2808 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
2809 Context.getCanonicalType(Ty)));
2810 NameInfo.setLoc(Name.StartLocation);
2811 NameInfo.setNamedTypeInfo(TInfo);
2812 return NameInfo;
2813 }
2814
2815 case UnqualifiedId::IK_ConstructorTemplateId: {
2816 // In well-formed code, we can only have a constructor
2817 // template-id that refers to the current context, so go there
2818 // to find the actual type being constructed.
2819 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
2820 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
2821 return DeclarationNameInfo();
2822
2823 // Determine the type of the class being constructed.
2824 QualType CurClassType = Context.getTypeDeclType(CurClass);
2825
2826 // FIXME: Check two things: that the template-id names the same type as
2827 // CurClassType, and that the template-id does not occur when the name
2828 // was qualified.
2829
2830 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
2831 Context.getCanonicalType(CurClassType)));
2832 NameInfo.setLoc(Name.StartLocation);
2833 // FIXME: should we retrieve TypeSourceInfo?
2834 NameInfo.setNamedTypeInfo(0);
2835 return NameInfo;
2836 }
2837
2838 case UnqualifiedId::IK_DestructorName: {
2839 TypeSourceInfo *TInfo;
2840 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
2841 if (Ty.isNull())
2842 return DeclarationNameInfo();
2843 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
2844 Context.getCanonicalType(Ty)));
2845 NameInfo.setLoc(Name.StartLocation);
2846 NameInfo.setNamedTypeInfo(TInfo);
2847 return NameInfo;
2848 }
2849
2850 case UnqualifiedId::IK_TemplateId: {
John McCall3e56fd42010-08-23 07:28:44 +00002851 TemplateName TName = Name.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002852 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
2853 return Context.getNameForTemplate(TName, TNameLoc);
2854 }
2855
2856 } // switch (Name.getKind())
2857
Douglas Gregor92751d42008-11-17 22:58:34 +00002858 assert(false && "Unknown name kind");
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002859 return DeclarationNameInfo();
Douglas Gregor92751d42008-11-17 22:58:34 +00002860}
2861
Douglas Gregor8af63e42009-02-06 17:46:57 +00002862/// isNearlyMatchingFunction - Determine whether the C++ functions
2863/// Declaration and Definition are "nearly" matching. This heuristic
2864/// is used to improve diagnostics in the case where an out-of-line
2865/// function definition doesn't match any declaration within
2866/// the class or namespace.
2867static bool isNearlyMatchingFunction(ASTContext &Context,
2868 FunctionDecl *Declaration,
2869 FunctionDecl *Definition) {
Douglas Gregorad590502008-12-15 23:53:10 +00002870 if (Declaration->param_size() != Definition->param_size())
2871 return false;
2872 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
2873 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
2874 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
2875
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002876 if (!Context.hasSameUnqualifiedType(DeclParamTy.getNonReferenceType(),
2877 DefParamTy.getNonReferenceType()))
Douglas Gregorad590502008-12-15 23:53:10 +00002878 return false;
2879 }
2880
2881 return true;
2882}
2883
John McCall99b2fe52010-04-29 23:50:39 +00002884/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
2885/// declarator needs to be rebuilt in the current instantiation.
2886/// Any bits of declarator which appear before the name are valid for
2887/// consideration here. That's specifically the type in the decl spec
2888/// and the base type in any member-pointer chunks.
2889static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
2890 DeclarationName Name) {
2891 // The types we specifically need to rebuild are:
2892 // - typenames, typeofs, and decltypes
2893 // - types which will become injected class names
2894 // Of course, we also need to rebuild any type referencing such a
2895 // type. It's safest to just say "dependent", but we call out a
2896 // few cases here.
2897
2898 DeclSpec &DS = D.getMutableDeclSpec();
2899 switch (DS.getTypeSpecType()) {
2900 case DeclSpec::TST_typename:
2901 case DeclSpec::TST_typeofType:
Alexis Hunt4a257072011-05-19 05:37:45 +00002902 case DeclSpec::TST_decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002903 case DeclSpec::TST_underlyingType: {
John McCall99b2fe52010-04-29 23:50:39 +00002904 // Grab the type from the parser.
2905 TypeSourceInfo *TSI = 0;
John McCallba7bf592010-08-24 05:47:05 +00002906 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
John McCall99b2fe52010-04-29 23:50:39 +00002907 if (T.isNull() || !T->isDependentType()) break;
2908
2909 // Make sure there's a type source info. This isn't really much
2910 // of a waste; most dependent types should have type source info
2911 // attached already.
2912 if (!TSI)
2913 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
2914
2915 // Rebuild the type in the current instantiation.
2916 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
2917 if (!TSI) return true;
2918
2919 // Store the new type back in the decl spec.
John McCallba7bf592010-08-24 05:47:05 +00002920 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
2921 DS.UpdateTypeRep(LocType);
2922 break;
2923 }
2924
2925 case DeclSpec::TST_typeofExpr: {
2926 Expr *E = DS.getRepAsExpr();
John McCalldadc5752010-08-24 06:29:42 +00002927 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
John McCallba7bf592010-08-24 05:47:05 +00002928 if (Result.isInvalid()) return true;
2929 DS.UpdateExprRep(Result.get());
John McCall99b2fe52010-04-29 23:50:39 +00002930 break;
2931 }
2932
2933 default:
2934 // Nothing to do for these decl specs.
2935 break;
2936 }
2937
2938 // It doesn't matter what order we do this in.
2939 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
2940 DeclaratorChunk &Chunk = D.getTypeObject(I);
2941
2942 // The only type information in the declarator which can come
2943 // before the declaration name is the base type of a member
2944 // pointer.
2945 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
2946 continue;
2947
2948 // Rebuild the scope specifier in-place.
2949 CXXScopeSpec &SS = Chunk.Mem.Scope();
2950 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
2951 return true;
2952 }
2953
2954 return false;
2955}
2956
Anders Carlsson1052fd72011-07-04 16:28:17 +00002957Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002958 return HandleDeclarator(S, D, MultiTemplateParamsArg(*this),
Anders Carlsson1052fd72011-07-04 16:28:17 +00002959 /*IsFunctionDefinition=*/false);
John McCallde6836a2010-08-24 07:21:54 +00002960}
2961
Richard Smithdda56e42011-04-15 14:24:37 +00002962/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
2963/// If T is the name of a class, then each of the following shall have a
2964/// name different from T:
2965/// - every static data member of class T;
2966/// - every member function of class T
2967/// - every member of class T that is itself a type;
2968/// \returns true if the declaration name violates these rules.
2969bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
2970 DeclarationNameInfo NameInfo) {
2971 DeclarationName Name = NameInfo.getName();
2972
2973 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
2974 if (Record->getIdentifier() && Record->getDeclName() == Name) {
2975 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
2976 return true;
2977 }
2978
2979 return false;
2980}
2981
John McCall48871652010-08-21 09:40:31 +00002982Decl *Sema::HandleDeclarator(Scope *S, Declarator &D,
2983 MultiTemplateParamsArg TemplateParamLists,
Alexis Hunt5a7fa252011-05-12 06:15:49 +00002984 bool IsFunctionDefinition) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002985 // TODO: consider using NameInfo for diagnostic.
2986 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2987 DeclarationName Name = NameInfo.getName();
Douglas Gregor92751d42008-11-17 22:58:34 +00002988
Chris Lattner02c04392007-07-25 00:24:17 +00002989 // All of these full declarators require an identifier. If it doesn't have
2990 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor92751d42008-11-17 22:58:34 +00002991 if (!Name) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002992 if (!D.isInvalidType()) // Reject this if we think it is valid.
Chris Lattner8c5dd732008-11-11 06:13:16 +00002993 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002994 diag::err_declarator_need_ident)
2995 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00002996 return 0;
Douglas Gregorc4356532010-12-16 00:46:58 +00002997 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
2998 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002999
Chris Lattner1a76a3c2007-08-26 06:24:45 +00003000 // The scope passed in may not be a decl scope. Zip up the scope tree until
3001 // we find one that is.
Douglas Gregor91f84212008-12-11 16:49:14 +00003002 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregorded2d7b2009-02-04 19:02:06 +00003003 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner1a76a3c2007-08-26 06:24:45 +00003004 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003005
John McCall99b2fe52010-04-29 23:50:39 +00003006 DeclContext *DC = CurContext;
3007 if (D.getCXXScopeSpec().isInvalid())
3008 D.setInvalidType();
3009 else if (D.getCXXScopeSpec().isSet()) {
Douglas Gregor6c110f32010-12-16 01:14:37 +00003010 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
3011 UPPC_DeclarationQualifier))
3012 return 0;
3013
John McCall99b2fe52010-04-29 23:50:39 +00003014 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
3015 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
3016 if (!DC) {
3017 // If we could not compute the declaration context, it's because the
3018 // declaration context is dependent but does not refer to a class,
3019 // class template, or class template partial specialization. Complain
3020 // and return early, to avoid the coming semantic disaster.
3021 Diag(D.getIdentifierLoc(),
3022 diag::err_template_qualified_declarator_no_match)
3023 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
3024 << D.getCXXScopeSpec().getRange();
John McCall48871652010-08-21 09:40:31 +00003025 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00003026 }
John McCall99b2fe52010-04-29 23:50:39 +00003027 bool IsDependentContext = DC->isDependentContext();
John McCall4d6d6132009-12-19 09:35:56 +00003028
John McCall99b2fe52010-04-29 23:50:39 +00003029 if (!IsDependentContext &&
John McCall0b66eb32010-05-01 00:40:08 +00003030 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
John McCall48871652010-08-21 09:40:31 +00003031 return 0;
John McCall99b2fe52010-04-29 23:50:39 +00003032
Douglas Gregora007d362010-10-13 22:19:53 +00003033 if (isa<CXXRecordDecl>(DC)) {
3034 if (!cast<CXXRecordDecl>(DC)->hasDefinition()) {
3035 Diag(D.getIdentifierLoc(),
3036 diag::err_member_def_undefined_record)
3037 << Name << DC << D.getCXXScopeSpec().getRange();
3038 D.setInvalidType();
3039 } else if (isa<CXXRecordDecl>(CurContext) &&
3040 !D.getDeclSpec().isFriendSpecified()) {
3041 // The user provided a superfluous scope specifier inside a class
3042 // definition:
3043 //
3044 // class X {
3045 // void X::f();
3046 // };
3047 if (CurContext->Equals(DC))
3048 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
3049 << Name << FixItHint::CreateRemoval(D.getCXXScopeSpec().getRange());
3050 else
3051 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3052 << Name << D.getCXXScopeSpec().getRange();
3053
3054 // Pretend that this qualifier was not here.
3055 D.getCXXScopeSpec().clear();
3056 }
John McCall99b2fe52010-04-29 23:50:39 +00003057 }
3058
3059 // Check whether we need to rebuild the type of the given
3060 // declaration in the current instantiation.
3061 if (EnteringContext && IsDependentContext &&
3062 TemplateParamLists.size() != 0) {
3063 ContextRAII SavedContext(*this, DC);
3064 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
3065 D.setInvalidType();
Douglas Gregor15acfb92009-08-06 16:20:37 +00003066 }
3067 }
Richard Smithdda56e42011-04-15 14:24:37 +00003068
3069 if (DiagnoseClassNameShadow(DC, NameInfo))
3070 // If this is a typedef, we'll end up spewing multiple diagnostics.
3071 // Just return early; it's safer.
3072 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3073 return 0;
Douglas Gregor36c22a22010-10-15 13:21:21 +00003074
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003075 NamedDecl *New;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00003076
John McCall8cb7bdf2010-06-04 23:28:52 +00003077 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3078 QualType R = TInfo->getType();
Douglas Gregoreddf4332009-02-24 20:03:32 +00003079
Douglas Gregor506bd562010-12-13 22:49:22 +00003080 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
3081 UPPC_DeclarationType))
3082 D.setInvalidType();
3083
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003084 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00003085 ForRedeclaration);
3086
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003087 // See if this is a redefinition of a variable in the same scope.
John McCall99b2fe52010-04-29 23:50:39 +00003088 if (!D.getCXXScopeSpec().isSet()) {
John McCall1f82f242009-11-18 22:49:29 +00003089 bool IsLinkageLookup = false;
Douglas Gregoreddf4332009-02-24 20:03:32 +00003090
3091 // If the declaration we're planning to build will be a function
3092 // or object with linkage, then look for another declaration with
3093 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
3094 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3095 /* Do nothing*/;
3096 else if (R->isFunctionType()) {
Douglas Gregor20749772009-07-07 17:00:05 +00003097 if (CurContext->isFunctionOrMethod() ||
3098 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall1f82f242009-11-18 22:49:29 +00003099 IsLinkageLookup = true;
Douglas Gregoreddf4332009-02-24 20:03:32 +00003100 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
John McCall1f82f242009-11-18 22:49:29 +00003101 IsLinkageLookup = true;
Sebastian Redl50c68252010-08-31 00:36:30 +00003102 else if (CurContext->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor20749772009-07-07 17:00:05 +00003103 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
John McCall1f82f242009-11-18 22:49:29 +00003104 IsLinkageLookup = true;
3105
3106 if (IsLinkageLookup)
3107 Previous.clear(LookupRedeclarationWithLinkage);
Douglas Gregoreddf4332009-02-24 20:03:32 +00003108
John McCall1f82f242009-11-18 22:49:29 +00003109 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003110 } else { // Something like "int foo::x;"
John McCall1f82f242009-11-18 22:49:29 +00003111 LookupQualifiedName(Previous, DC);
3112
3113 // Don't consider using declarations as previous declarations for
3114 // out-of-line members.
3115 RemoveUsingDecls(Previous);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003116
3117 // C++ 7.3.1.2p2:
3118 // Members (including explicit specializations of templates) of a named
3119 // namespace can also be defined outside that namespace by explicit
3120 // qualification of the name being defined, provided that the entity being
3121 // defined was already declared in the namespace and the definition appears
3122 // after the point of declaration in a namespace that encloses the
3123 // declarations namespace.
3124 //
Douglas Gregorad590502008-12-15 23:53:10 +00003125 // Note that we only check the context at this point. We don't yet
3126 // have enough information to make sure that PrevDecl is actually
3127 // the declaration we want to match. For example, given:
3128 //
Douglas Gregor4287b372008-12-12 08:25:50 +00003129 // class X {
3130 // void f();
Douglas Gregorad590502008-12-15 23:53:10 +00003131 // void f(float);
Douglas Gregor4287b372008-12-12 08:25:50 +00003132 // };
3133 //
Douglas Gregorad590502008-12-15 23:53:10 +00003134 // void X::f(int) { } // ill-formed
3135 //
3136 // In this case, PrevDecl will point to the overload set
3137 // containing the two f's declared in X, but neither of them
Mike Stump11289f42009-09-09 15:08:12 +00003138 // matches.
Douglas Gregor8af63e42009-02-06 17:46:57 +00003139
3140 // First check whether we named the global scope.
3141 if (isa<TranslationUnitDecl>(DC)) {
Mike Stump11289f42009-09-09 15:08:12 +00003142 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
Douglas Gregor8af63e42009-02-06 17:46:57 +00003143 << Name << D.getCXXScopeSpec().getRange();
Sebastian Redlafb8be72009-11-08 11:36:54 +00003144 } else {
3145 DeclContext *Cur = CurContext;
3146 while (isa<LinkageSpecDecl>(Cur))
3147 Cur = Cur->getParent();
3148 if (!Cur->Encloses(DC)) {
3149 // The qualifying scope doesn't enclose the original declaration.
3150 // Emit diagnostic based on current scope.
3151 SourceLocation L = D.getIdentifierLoc();
3152 SourceRange R = D.getCXXScopeSpec().getRange();
3153 if (isa<FunctionDecl>(Cur))
3154 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
3155 else
3156 Diag(L, diag::err_invalid_declarator_scope)
3157 << Name << cast<NamedDecl>(DC) << R;
3158 D.setInvalidType();
3159 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003160 }
3161 }
3162
John McCall1f82f242009-11-18 22:49:29 +00003163 if (Previous.isSingleResult() &&
3164 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00003165 // Maybe we will complain about the shadowed template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003166 if (!D.isInvalidType())
John McCall1f82f242009-11-18 22:49:29 +00003167 if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
3168 Previous.getFoundDecl()))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003169 D.setInvalidType();
Mike Stump11289f42009-09-09 15:08:12 +00003170
Douglas Gregor5101c242008-12-05 18:15:24 +00003171 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00003172 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00003173 }
3174
Douglas Gregor83a586e2008-04-13 21:07:44 +00003175 // In C++, the previous declaration we find might be a tag type
3176 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorfb034662009-01-28 17:15:10 +00003177 // tag type. Note that this does does not apply if we're declaring a
3178 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00003179 if (Previous.isSingleTagDecl() &&
Douglas Gregorfb034662009-01-28 17:15:10 +00003180 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
John McCall1f82f242009-11-18 22:49:29 +00003181 Previous.clear();
Douglas Gregor83a586e2008-04-13 21:07:44 +00003182
Douglas Gregor75a45ba2009-02-16 17:45:42 +00003183 bool Redeclaration = false;
Chris Lattner01a7c532007-01-25 23:09:03 +00003184 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003185 if (TemplateParamLists.size()) {
3186 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
John McCall48871652010-08-21 09:40:31 +00003187 return 0;
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003188 }
Mike Stump11289f42009-09-09 15:08:12 +00003189
John McCallbcd03502009-12-07 02:54:59 +00003190 New = ActOnTypedefDeclarator(S, D, DC, R, TInfo, Previous, Redeclaration);
Douglas Gregoreddf4332009-02-24 20:03:32 +00003191 } else if (R->isFunctionType()) {
John McCallbcd03502009-12-07 02:54:59 +00003192 New = ActOnFunctionDeclarator(S, D, DC, R, TInfo, Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00003193 move(TemplateParamLists),
Alexis Hunt5a7fa252011-05-12 06:15:49 +00003194 IsFunctionDefinition, Redeclaration);
Chris Lattner01a7c532007-01-25 23:09:03 +00003195 } else {
John McCallbcd03502009-12-07 02:54:59 +00003196 New = ActOnVariableDeclarator(S, D, DC, R, TInfo, Previous,
Douglas Gregorb09f3d82009-07-22 17:18:37 +00003197 move(TemplateParamLists),
3198 Redeclaration);
Chris Lattner01a7c532007-01-25 23:09:03 +00003199 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00003200
3201 if (New == 0)
John McCall48871652010-08-21 09:40:31 +00003202 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003203
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003204 // If this has an identifier and is not an invalid redeclaration or
3205 // function template specialization, add it to the scope stack.
Douglas Gregor536f0912010-07-24 00:10:38 +00003206 if (New->getDeclName() && !(Redeclaration && New->isInvalidDecl()))
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00003207 PushOnScopeChains(New, S);
Mike Stump11289f42009-09-09 15:08:12 +00003208
John McCall48871652010-08-21 09:40:31 +00003209 return New;
Chris Lattnere168f762006-11-10 05:29:30 +00003210}
3211
Eli Friedmana3b1d032009-02-21 00:44:51 +00003212/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3213/// types into constant array types in certain situations which would otherwise
3214/// be errors (for GCC compatibility).
3215static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3216 ASTContext &Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003217 bool &SizeIsNegative,
3218 llvm::APSInt &Oversized) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00003219 // This method tries to turn a variable array into a constant
3220 // array even when the size isn't an ICE. This is necessary
3221 // for compatibility with code that depends on gcc's buggy
3222 // constant expression folding, like struct {char x[(int)(char*)2];}
3223 SizeIsNegative = false;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003224 Oversized = 0;
3225
3226 if (T->isDependentType())
3227 return QualType();
3228
John McCall8ccfcb52009-09-24 19:53:00 +00003229 QualifierCollector Qs;
3230 const Type *Ty = Qs.strip(T);
3231
3232 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00003233 QualType Pointee = PTy->getPointeeType();
3234 QualType FixedType =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003235 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
3236 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003237 if (FixedType.isNull()) return FixedType;
Eli Friedman44c0f2a2009-02-21 00:58:02 +00003238 FixedType = Context.getPointerType(FixedType);
John McCall717d9b02010-12-10 11:01:00 +00003239 return Qs.apply(Context, FixedType);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003240 }
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003241 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
3242 QualType Inner = PTy->getInnerType();
3243 QualType FixedType =
3244 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
3245 Oversized);
3246 if (FixedType.isNull()) return FixedType;
3247 FixedType = Context.getParenType(FixedType);
3248 return Qs.apply(Context, FixedType);
3249 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00003250
3251 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanadf40d42009-02-26 03:58:54 +00003252 if (!VLATy)
3253 return QualType();
3254 // FIXME: We should probably handle this case
3255 if (VLATy->getElementType()->isVariablyModifiedType())
3256 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00003257
Eli Friedmana3b1d032009-02-21 00:44:51 +00003258 Expr::EvalResult EvalResult;
3259 if (!VLATy->getSizeExpr() ||
Eli Friedmanadf40d42009-02-26 03:58:54 +00003260 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
3261 !EvalResult.Val.isInt())
Eli Friedmana3b1d032009-02-21 00:44:51 +00003262 return QualType();
Eli Friedmanadf40d42009-02-26 03:58:54 +00003263
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003264 // Check whether the array size is negative.
Eli Friedmana3b1d032009-02-21 00:44:51 +00003265 llvm::APSInt &Res = EvalResult.Val.getInt();
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003266 if (Res.isSigned() && Res.isNegative()) {
3267 SizeIsNegative = true;
3268 return QualType();
Douglas Gregor04318252009-07-06 15:59:29 +00003269 }
Eli Friedmana3b1d032009-02-21 00:44:51 +00003270
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003271 // Check whether the array is too large to be addressed.
3272 unsigned ActiveSizeBits
3273 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
3274 Res);
3275 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
3276 Oversized = Res;
3277 return QualType();
3278 }
3279
3280 return Context.getConstantArrayType(VLATy->getElementType(),
3281 Res, ArrayType::Normal, 0);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003282}
3283
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003284/// \brief Register the given locally-scoped external C declaration so
3285/// that it can be found later for redeclarations
Mike Stump11289f42009-09-09 15:08:12 +00003286void
John McCall1f82f242009-11-18 22:49:29 +00003287Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
3288 const LookupResult &Previous,
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003289 Scope *S) {
3290 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
3291 "Decl is not a locally-scoped decl!");
3292 // Note that we have a locally-scoped external with this name.
3293 LocallyScopedExternalDecls[ND->getDeclName()] = ND;
3294
John McCall1f82f242009-11-18 22:49:29 +00003295 if (!Previous.isSingleResult())
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003296 return;
3297
John McCall1f82f242009-11-18 22:49:29 +00003298 NamedDecl *PrevDecl = Previous.getFoundDecl();
3299
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003300 // If there was a previous declaration of this variable, it may be
3301 // in our identifier chain. Update the identifier chain with the new
3302 // declaration.
Douglas Gregorf4f296d2009-03-23 23:06:20 +00003303 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003304 // The previous declaration was found on the identifer resolver
3305 // chain, so remove it from its scope.
Douglas Gregor825faf72011-06-29 21:22:02 +00003306
3307 if (S->isDeclScope(PrevDecl)) {
3308 // Special case for redeclarations in the SAME scope.
3309 // Because this declaration is going to be added to the identifier chain
3310 // later, we should temporarily take it OFF the chain.
3311 IdResolver.RemoveDecl(ND);
3312
3313 } else {
3314 // Find the scope for the original declaration.
3315 while (S && !S->isDeclScope(PrevDecl))
3316 S = S->getParent();
3317 }
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003318
3319 if (S)
John McCall48871652010-08-21 09:40:31 +00003320 S->RemoveDecl(PrevDecl);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003321 }
3322}
3323
Eli Friedman574c7452009-04-07 19:37:57 +00003324/// \brief Diagnose function specifiers on a declaration of an identifier that
3325/// does not identify a function.
3326void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
3327 // FIXME: We should probably indicate the identifier in question to avoid
3328 // confusion for constructs like "inline int a(), b;"
3329 if (D.getDeclSpec().isInlineSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00003330 Diag(D.getDeclSpec().getInlineSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00003331 diag::err_inline_non_function);
3332
3333 if (D.getDeclSpec().isVirtualSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00003334 Diag(D.getDeclSpec().getVirtualSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00003335 diag::err_virtual_non_function);
3336
3337 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00003338 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Eli Friedman574c7452009-04-07 19:37:57 +00003339 diag::err_explicit_non_function);
3340}
3341
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003342NamedDecl*
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003343Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
John McCallbcd03502009-12-07 02:54:59 +00003344 QualType R, TypeSourceInfo *TInfo,
John McCall1f82f242009-11-18 22:49:29 +00003345 LookupResult &Previous, bool &Redeclaration) {
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003346 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
3347 if (D.getCXXScopeSpec().isSet()) {
3348 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
3349 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003350 D.setInvalidType();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003351 // Pretend we didn't see the scope specifier.
Douglas Gregorb525ef82010-03-23 15:26:55 +00003352 DC = CurContext;
3353 Previous.clear();
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003354 }
3355
Douglas Gregor0c880302009-03-11 23:00:04 +00003356 if (getLangOptions().CPlusPlus) {
3357 // Check that there are no default arguments (C++ only).
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003358 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00003359 }
3360
Eli Friedman574c7452009-04-07 19:37:57 +00003361 DiagnoseFunctionSpecifiers(D);
3362
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003363 if (D.getDeclSpec().isThreadSpecified())
3364 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
3365
Douglas Gregord8f446f2010-07-13 06:37:01 +00003366 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
3367 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
3368 << D.getName().getSourceRange();
3369 return 0;
3370 }
3371
John McCallbcd03502009-12-07 02:54:59 +00003372 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, TInfo);
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003373 if (!NewTD) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003374
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003375 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00003376 ProcessDeclAttributes(S, NewTD, D);
John McCall1f82f242009-11-18 22:49:29 +00003377
Richard Smith3f1b5d02011-05-05 21:57:07 +00003378 CheckTypedefForVariablyModifiedType(S, NewTD);
3379
Richard Smithdda56e42011-04-15 14:24:37 +00003380 return ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
3381}
3382
Richard Smith3f1b5d02011-05-05 21:57:07 +00003383void
3384Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
Chris Lattner9fecd742009-04-19 05:21:20 +00003385 // C99 6.7.7p2: If a typedef name specifies a variably modified type
3386 // then it shall have block scope.
Eli Friedman88f4ed92010-08-10 03:13:15 +00003387 // Note that variably modified types must be fixed before merging the decl so
3388 // that redeclarations will match.
Chris Lattner9fecd742009-04-19 05:21:20 +00003389 QualType T = NewTD->getUnderlyingType();
3390 if (T->isVariablyModifiedType()) {
John McCallaab3e412010-08-25 08:40:02 +00003391 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00003392
Chris Lattner9fecd742009-04-19 05:21:20 +00003393 if (S->getFnParent() == 0) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00003394 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003395 llvm::APSInt Oversized;
Eli Friedmana3b1d032009-02-21 00:44:51 +00003396 QualType FixedTy =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003397 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
3398 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003399 if (!FixedTy.isNull()) {
Richard Smithdda56e42011-04-15 14:24:37 +00003400 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
John McCallbcd03502009-12-07 02:54:59 +00003401 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
Eli Friedmana3b1d032009-02-21 00:44:51 +00003402 } else {
3403 if (SizeIsNegative)
Richard Smithdda56e42011-04-15 14:24:37 +00003404 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003405 else if (T->isVariableArrayType())
Richard Smithdda56e42011-04-15 14:24:37 +00003406 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003407 else if (Oversized.getBoolValue())
Richard Smithdda56e42011-04-15 14:24:37 +00003408 Diag(NewTD->getLocation(), diag::err_array_too_large) << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00003409 else
Richard Smithdda56e42011-04-15 14:24:37 +00003410 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003411 NewTD->setInvalidDecl();
Eli Friedmana3b1d032009-02-21 00:44:51 +00003412 }
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003413 }
3414 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00003415}
Douglas Gregor27821ce2009-07-07 16:35:42 +00003416
Richard Smith3f1b5d02011-05-05 21:57:07 +00003417
3418/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
3419/// declares a typedef-name, either using the 'typedef' type specifier or via
3420/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
3421NamedDecl*
3422Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
3423 LookupResult &Previous, bool &Redeclaration) {
Eli Friedman88f4ed92010-08-10 03:13:15 +00003424 // Merge the decl with the existing one if appropriate. If the decl is
3425 // in an outer scope, it isn't the same thing.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003426 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
Douglas Gregordb446112011-03-07 16:54:27 +00003427 /*ExplicitInstantiationOrSpecialization=*/false);
Eli Friedman88f4ed92010-08-10 03:13:15 +00003428 if (!Previous.empty()) {
3429 Redeclaration = true;
Richard Smithdda56e42011-04-15 14:24:37 +00003430 MergeTypedefNameDecl(NewTD, Previous);
Eli Friedman88f4ed92010-08-10 03:13:15 +00003431 }
3432
Douglas Gregor27821ce2009-07-07 16:35:42 +00003433 // If this is the C FILE type, notify the AST context.
3434 if (IdentifierInfo *II = NewTD->getIdentifier())
3435 if (!NewTD->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003436 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
Mike Stumpa4de80b2009-07-28 02:25:19 +00003437 if (II->isStr("FILE"))
3438 Context.setFILEDecl(NewTD);
3439 else if (II->isStr("jmp_buf"))
3440 Context.setjmp_bufDecl(NewTD);
3441 else if (II->isStr("sigjmp_buf"))
3442 Context.setsigjmp_bufDecl(NewTD);
Douglas Gregor2c2c4cd2010-10-05 15:41:24 +00003443 else if (II->isStr("__builtin_va_list"))
3444 Context.setBuiltinVaListType(Context.getTypedefType(NewTD));
Mike Stumpa4de80b2009-07-28 02:25:19 +00003445 }
3446
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00003447 return NewTD;
3448}
3449
Douglas Gregor5d68a202009-02-24 19:23:27 +00003450/// \brief Determines whether the given declaration is an out-of-scope
3451/// previous declaration.
3452///
3453/// This routine should be invoked when name lookup has found a
3454/// previous declaration (PrevDecl) that is not in the scope where a
3455/// new declaration by the same name is being introduced. If the new
3456/// declaration occurs in a local scope, previous declarations with
3457/// linkage may still be considered previous declarations (C99
3458/// 6.2.2p4-5, C++ [basic.link]p6).
3459///
3460/// \param PrevDecl the previous declaration found by name
3461/// lookup
Mike Stump11289f42009-09-09 15:08:12 +00003462///
Douglas Gregor5d68a202009-02-24 19:23:27 +00003463/// \param DC the context in which the new declaration is being
3464/// declared.
3465///
3466/// \returns true if PrevDecl is an out-of-scope previous declaration
3467/// for a new delcaration with the same name.
Mike Stump11289f42009-09-09 15:08:12 +00003468static bool
Douglas Gregor5d68a202009-02-24 19:23:27 +00003469isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
3470 ASTContext &Context) {
3471 if (!PrevDecl)
Sebastian Redl50c68252010-08-31 00:36:30 +00003472 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00003473
Douglas Gregoreddf4332009-02-24 20:03:32 +00003474 if (!PrevDecl->hasLinkage())
3475 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00003476
3477 if (Context.getLangOptions().CPlusPlus) {
3478 // C++ [basic.link]p6:
3479 // If there is a visible declaration of an entity with linkage
3480 // having the same name and type, ignoring entities declared
3481 // outside the innermost enclosing namespace scope, the block
3482 // scope declaration declares that same entity and receives the
3483 // linkage of the previous declaration.
Sebastian Redl50c68252010-08-31 00:36:30 +00003484 DeclContext *OuterContext = DC->getRedeclContext();
Douglas Gregor5d68a202009-02-24 19:23:27 +00003485 if (!OuterContext->isFunctionOrMethod())
3486 // This rule only applies to block-scope declarations.
3487 return false;
Douglas Gregorfcee9462010-08-27 22:55:10 +00003488
3489 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
3490 if (PrevOuterContext->isRecord())
3491 // We found a member function: ignore it.
3492 return false;
3493
3494 // Find the innermost enclosing namespace for the new and
3495 // previous declarations.
Sebastian Redl50c68252010-08-31 00:36:30 +00003496 OuterContext = OuterContext->getEnclosingNamespaceContext();
3497 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
Mike Stump11289f42009-09-09 15:08:12 +00003498
Douglas Gregorfcee9462010-08-27 22:55:10 +00003499 // The previous declaration is in a different namespace, so it
3500 // isn't the same function.
3501 if (!OuterContext->Equals(PrevOuterContext))
3502 return false;
Douglas Gregor5d68a202009-02-24 19:23:27 +00003503 }
3504
Douglas Gregor5d68a202009-02-24 19:23:27 +00003505 return true;
3506}
3507
John McCall3e11ebe2010-03-15 10:12:16 +00003508static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
3509 CXXScopeSpec &SS = D.getCXXScopeSpec();
3510 if (!SS.isSet()) return;
Douglas Gregor14454802011-02-25 02:25:35 +00003511 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
John McCall3e11ebe2010-03-15 10:12:16 +00003512}
3513
John McCall31168b02011-06-15 23:02:42 +00003514bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
3515 QualType type = decl->getType();
3516 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
3517 if (lifetime == Qualifiers::OCL_Autoreleasing) {
3518 // Various kinds of declaration aren't allowed to be __autoreleasing.
3519 unsigned kind = -1U;
3520 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
3521 if (var->hasAttr<BlocksAttr>())
3522 kind = 0; // __block
3523 else if (!var->hasLocalStorage())
3524 kind = 1; // global
3525 } else if (isa<ObjCIvarDecl>(decl)) {
3526 kind = 3; // ivar
3527 } else if (isa<FieldDecl>(decl)) {
3528 kind = 2; // field
3529 }
3530
3531 if (kind != -1U) {
3532 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
3533 << kind;
3534 }
3535 } else if (lifetime == Qualifiers::OCL_None) {
3536 // Try to infer lifetime.
3537 if (!type->isObjCLifetimeType())
3538 return false;
3539
3540 lifetime = type->getObjCARCImplicitLifetime();
3541 type = Context.getLifetimeQualifiedType(type, lifetime);
3542 decl->setType(type);
3543 }
3544
3545 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
3546 // Thread-local variables cannot have lifetime.
3547 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
3548 var->isThreadSpecified()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003549 Diag(var->getLocation(), diag::err_arc_thread_ownership)
John McCall31168b02011-06-15 23:02:42 +00003550 << var->getType();
3551 return true;
3552 }
3553 }
3554
3555 return false;
3556}
3557
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003558NamedDecl*
Chris Lattner88fdea82010-10-10 18:16:20 +00003559Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
John McCallbcd03502009-12-07 02:54:59 +00003560 QualType R, TypeSourceInfo *TInfo,
John McCall1f82f242009-11-18 22:49:29 +00003561 LookupResult &Previous,
Douglas Gregorb09f3d82009-07-22 17:18:37 +00003562 MultiTemplateParamsArg TemplateParamLists,
Douglas Gregor75a45ba2009-02-16 17:45:42 +00003563 bool &Redeclaration) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003564 DeclarationName Name = GetNameForDeclarator(D).getName();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003565
3566 // Check that there are no default arguments (C++ only).
3567 if (getLangOptions().CPlusPlus)
3568 CheckExtraCXXDefaultArguments(D);
3569
Douglas Gregorc4df4072010-04-19 22:54:31 +00003570 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
3571 assert(SCSpec != DeclSpec::SCS_typedef &&
3572 "Parser allowed 'typedef' as storage class VarDecl.");
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00003573 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
Douglas Gregorc4df4072010-04-19 22:54:31 +00003574 if (SCSpec == DeclSpec::SCS_mutable) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003575 // mutable can only appear on non-static class members, so it's always
3576 // an error here
3577 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003578 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003579 SC = SC_None;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003580 }
Douglas Gregorc4df4072010-04-19 22:54:31 +00003581 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
3582 VarDecl::StorageClass SCAsWritten
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00003583 = StorageClassSpecToVarDeclStorageClass(SCSpec);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003584
3585 IdentifierInfo *II = Name.getAsIdentifierInfo();
3586 if (!II) {
3587 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
3588 << Name.getAsString();
3589 return 0;
3590 }
3591
Eli Friedman574c7452009-04-07 19:37:57 +00003592 DiagnoseFunctionSpecifiers(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00003593
Douglas Gregor212cab32009-03-11 20:22:50 +00003594 if (!DC->isRecord() && S->getFnParent() == 0) {
3595 // C99 6.9p2: The storage-class specifiers auto and register shall not
3596 // appear in the declaration specifiers in an external declaration.
John McCall8e7d6562010-08-26 03:08:43 +00003597 if (SC == SC_Auto || SC == SC_Register) {
Mike Stump11289f42009-09-09 15:08:12 +00003598
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00003599 // If this is a register variable with an asm label specified, then this
3600 // is a GNU extension.
John McCall8e7d6562010-08-26 03:08:43 +00003601 if (SC == SC_Register && D.getAsmLabel())
Chris Lattnerd98e7cf72009-05-12 21:44:00 +00003602 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
3603 else
3604 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003605 D.setInvalidType();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003606 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003607 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003608
Ted Kremenek582a0992011-01-23 17:04:59 +00003609 bool isExplicitSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003610 VarDecl *NewVD;
3611 if (!getLangOptions().CPlusPlus) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003612 NewVD = VarDecl::Create(Context, DC, D.getSourceRange().getBegin(),
3613 D.getIdentifierLoc(), II,
3614 R, TInfo, SC, SCAsWritten);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003615
3616 if (D.isInvalidType())
3617 NewVD->setInvalidDecl();
3618 } else {
3619 if (DC->isRecord() && !CurContext->isRecord()) {
3620 // This is an out-of-line definition of a static data member.
3621 if (SC == SC_Static) {
3622 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
3623 diag::err_static_out_of_line)
3624 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3625 } else if (SC == SC_None)
3626 SC = SC_Static;
Anders Carlssond2e8adf2009-06-24 00:28:53 +00003627 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003628 if (SC == SC_Static) {
3629 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
3630 if (RD->isLocalClass())
3631 Diag(D.getIdentifierLoc(),
3632 diag::err_static_data_member_not_allowed_in_local_class)
3633 << Name << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003634
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003635 // C++ [class.union]p1: If a union contains a static data member,
3636 // the program is ill-formed.
3637 //
3638 // We also disallow static data members in anonymous structs.
3639 if (CurContext->isRecord() && (RD->isUnion() || !RD->getDeclName()))
3640 Diag(D.getIdentifierLoc(),
3641 diag::err_static_data_member_not_allowed_in_union_or_anon_struct)
3642 << Name << RD->isUnion();
3643 }
3644 }
3645
3646 // Match up the template parameter lists with the scope specifier, then
3647 // determine whether we have a template or a template specialization.
3648 isExplicitSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003649 bool Invalid = false;
3650 if (TemplateParameterList *TemplateParams
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003651 = MatchTemplateParametersToScopeSpecifier(
Douglas Gregor972fe532011-05-10 18:27:06 +00003652 D.getDeclSpec().getSourceRange().getBegin(),
3653 D.getIdentifierLoc(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003654 D.getCXXScopeSpec(),
John McCallace48cd2010-10-19 01:40:49 +00003655 TemplateParamLists.get(),
3656 TemplateParamLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00003657 /*never a friend*/ false,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00003658 isExplicitSpecialization,
3659 Invalid)) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003660 if (TemplateParams->size() > 0) {
3661 // There is no such thing as a variable template.
3662 Diag(D.getIdentifierLoc(), diag::err_template_variable)
3663 << II
3664 << SourceRange(TemplateParams->getTemplateLoc(),
3665 TemplateParams->getRAngleLoc());
3666 return 0;
3667 } else {
3668 // There is an extraneous 'template<>' for this variable. Complain
3669 // about it, but allow the declaration of the variable.
3670 Diag(TemplateParams->getTemplateLoc(),
3671 diag::err_template_variable_noparams)
3672 << II
3673 << SourceRange(TemplateParams->getTemplateLoc(),
3674 TemplateParams->getRAngleLoc());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003675 }
Douglas Gregorb09f3d82009-07-22 17:18:37 +00003676 }
Mike Stump11289f42009-09-09 15:08:12 +00003677
Abramo Bagnaradff19302011-03-08 08:55:46 +00003678 NewVD = VarDecl::Create(Context, DC, D.getSourceRange().getBegin(),
3679 D.getIdentifierLoc(), II,
3680 R, TInfo, SC, SCAsWritten);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003681
Richard Smithb2bc2e62011-02-21 20:05:19 +00003682 // If this decl has an auto type in need of deduction, make a note of the
3683 // Decl so we can diagnose uses of it in its own initializer.
3684 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
3685 R->getContainedAutoType())
3686 ParsingInitForAutoVars.insert(NewVD);
Richard Smith30482bc2011-02-20 03:19:35 +00003687
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003688 if (D.isInvalidType() || Invalid)
3689 NewVD->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003690
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003691 SetNestedNameSpecifier(NewVD, D);
John McCall3e11ebe2010-03-15 10:12:16 +00003692
Abramo Bagnara60804e12011-03-18 15:16:37 +00003693 if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003694 NewVD->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00003695 TemplateParamLists.size(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003696 TemplateParamLists.release());
3697 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003698 }
3699
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003700 if (D.getDeclSpec().isThreadSpecified()) {
3701 if (NewVD->hasLocalStorage())
3702 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
Eli Friedmandaea3f62009-04-19 21:48:33 +00003703 else if (!Context.Target.isTLSSupported())
3704 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
Eli Friedmand5c0eed2009-04-19 20:27:55 +00003705 else
3706 NewVD->setThreadSpecified(true);
3707 }
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003708
Douglas Gregor04e9a032009-03-11 23:52:16 +00003709 // Set the lexical context. If the declarator has a C++ scope specifier, the
3710 // lexical context will be different from the semantic context.
3711 NewVD->setLexicalDeclContext(CurContext);
3712
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003713 // Handle attributes prior to checking for duplicates in MergeVarDecl
Douglas Gregor758a8692009-06-17 21:51:59 +00003714 ProcessDeclAttributes(S, NewVD, D);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003715
John McCall31168b02011-06-15 23:02:42 +00003716 // In auto-retain/release, infer strong retension for variables of
3717 // retainable type.
3718 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
3719 NewVD->setInvalidDecl();
3720
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003721 // Handle GNU asm-label extension (encoded as an attribute).
Chris Lattner88fdea82010-10-10 18:16:20 +00003722 if (Expr *E = (Expr*)D.getAsmLabel()) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003723 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00003724 StringLiteral *SE = cast<StringLiteral>(E);
Rafael Espindola478abca2011-01-01 21:47:03 +00003725 llvm::StringRef Label = SE->getString();
Abramo Bagnara13392232011-01-11 15:16:52 +00003726 if (S->getFnParent() != 0) {
3727 switch (SC) {
3728 case SC_None:
3729 case SC_Auto:
3730 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
3731 break;
3732 case SC_Register:
3733 if (!Context.Target.isValidGCCRegisterName(Label))
3734 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
3735 break;
3736 case SC_Static:
3737 case SC_Extern:
3738 case SC_PrivateExtern:
3739 break;
3740 }
3741 }
3742
3743 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
Rafael Espindola478abca2011-01-01 21:47:03 +00003744 Context, Label));
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003745 }
3746
John McCalla2a3f7d2010-03-16 21:48:18 +00003747 // Diagnose shadowed variables before filtering for scope.
John McCall2d8c7602010-03-20 04:12:52 +00003748 if (!D.getCXXScopeSpec().isSet())
John McCalldf8b37c2010-03-22 09:20:08 +00003749 CheckShadow(S, NewVD, Previous);
John McCalla2a3f7d2010-03-16 21:48:18 +00003750
John McCall1f82f242009-11-18 22:49:29 +00003751 // Don't consider existing declarations that are in a different
3752 // scope and are out-of-semantic-context declarations (if the new
3753 // declaration has linkage).
Richard Smith3f1b5d02011-05-05 21:57:07 +00003754 FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(),
Douglas Gregordb446112011-03-07 16:54:27 +00003755 isExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00003756
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003757 if (!getLangOptions().CPlusPlus)
3758 CheckVariableDeclaration(NewVD, Previous, Redeclaration);
3759 else {
3760 // Merge the decl with the existing one if appropriate.
3761 if (!Previous.empty()) {
3762 if (Previous.isSingleResult() &&
3763 isa<FieldDecl>(Previous.getFoundDecl()) &&
3764 D.getCXXScopeSpec().isSet()) {
3765 // The user tried to define a non-static data member
3766 // out-of-line (C++ [dcl.meaning]p1).
3767 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
3768 << D.getCXXScopeSpec().getRange();
3769 Previous.clear();
3770 NewVD->setInvalidDecl();
3771 }
3772 } else if (D.getCXXScopeSpec().isSet()) {
3773 // No previous declaration in the qualifying scope.
3774 Diag(D.getIdentifierLoc(), diag::err_no_member)
3775 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003776 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003777 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003778 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003779
3780 CheckVariableDeclaration(NewVD, Previous, Redeclaration);
3781
3782 // This is an explicit specialization of a static data member. Check it.
3783 if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
3784 CheckMemberSpecialization(NewVD, Previous))
3785 NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003786 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003787
Ryan Flynne5dc8592009-07-25 22:29:44 +00003788 // attributes declared post-definition are currently ignored
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003789 // FIXME: This should be handled in attribute merging, not
3790 // here.
John McCall1f82f242009-11-18 22:49:29 +00003791 if (Previous.isSingleResult()) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00003792 VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl());
3793 if (Def && (Def = Def->getDefinition()) &&
3794 Def != NewVD && D.hasAttributes()) {
Ryan Flynne5dc8592009-07-25 22:29:44 +00003795 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
3796 Diag(Def->getLocation(), diag::note_previous_definition);
3797 }
3798 }
3799
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003800 // If this is a locally-scoped extern C variable, update the map of
3801 // such variables.
Douglas Gregor16618f22009-09-12 00:17:51 +00003802 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003803 !NewVD->isInvalidDecl())
John McCall1f82f242009-11-18 22:49:29 +00003804 RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003805
Eli Friedman570024a2010-08-05 06:57:20 +00003806 // If there's a #pragma GCC visibility in scope, and this isn't a class
3807 // member, set the visibility of this variable.
3808 if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord())
3809 AddPushedVisibilityAttribute(NewVD);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00003810
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00003811 MarkUnusedFileScopedDecl(NewVD);
3812
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003813 return NewVD;
3814}
3815
John McCalldf8b37c2010-03-22 09:20:08 +00003816/// \brief Diagnose variable or built-in function shadowing. Implements
3817/// -Wshadow.
John McCalla2a3f7d2010-03-16 21:48:18 +00003818///
John McCalldf8b37c2010-03-22 09:20:08 +00003819/// This method is called whenever a VarDecl is added to a "useful"
3820/// scope.
John McCalla2a3f7d2010-03-16 21:48:18 +00003821///
John McCall2d8c7602010-03-20 04:12:52 +00003822/// \param S the scope in which the shadowing name is being declared
3823/// \param R the lookup of the name
John McCalla2a3f7d2010-03-16 21:48:18 +00003824///
John McCalldf8b37c2010-03-22 09:20:08 +00003825void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
John McCalla2a3f7d2010-03-16 21:48:18 +00003826 // Return if warning is ignored.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003827 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
3828 Diagnostic::Ignored)
John McCalla2a3f7d2010-03-16 21:48:18 +00003829 return;
3830
Argyrios Kyrtzidis898fdbf2011-02-08 18:21:25 +00003831 // Don't diagnose declarations at file scope.
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00003832 if (D->hasGlobalStorage())
John McCalla2a3f7d2010-03-16 21:48:18 +00003833 return;
Argyrios Kyrtzidisbd0a3fe2011-04-25 21:39:50 +00003834
3835 DeclContext *NewDC = D->getDeclContext();
3836
John McCall2d8c7602010-03-20 04:12:52 +00003837 // Only diagnose if we're shadowing an unambiguous field or variable.
Douglas Gregor319aa6c2010-03-17 16:03:44 +00003838 if (R.getResultKind() != LookupResult::Found)
John McCalla2a3f7d2010-03-16 21:48:18 +00003839 return;
John McCalla2a3f7d2010-03-16 21:48:18 +00003840
John McCalla2a3f7d2010-03-16 21:48:18 +00003841 NamedDecl* ShadowedDecl = R.getFoundDecl();
3842 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
3843 return;
3844
Argyrios Kyrtzidisf46cc652011-01-31 07:04:54 +00003845 // Fields are not shadowed by variables in C++ static methods.
3846 if (isa<FieldDecl>(ShadowedDecl))
3847 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
3848 if (MD->isStatic())
3849 return;
3850
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00003851 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
3852 if (shadowedVar->isExternC()) {
Argyrios Kyrtzidis857dd062011-01-31 07:04:50 +00003853 // For shadowing external vars, make sure that we point to the global
3854 // declaration, not a locally scoped extern declaration.
3855 for (VarDecl::redecl_iterator
3856 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
3857 I != E; ++I)
3858 if (I->isFileVarDecl()) {
3859 ShadowedDecl = *I;
3860 break;
3861 }
3862 }
3863
3864 DeclContext *OldDC = ShadowedDecl->getDeclContext();
3865
John McCall2d8c7602010-03-20 04:12:52 +00003866 // Only warn about certain kinds of shadowing for class members.
3867 if (NewDC && NewDC->isRecord()) {
3868 // In particular, don't warn about shadowing non-class members.
3869 if (!OldDC->isRecord())
3870 return;
3871
3872 // TODO: should we warn about static data members shadowing
3873 // static data members from base classes?
3874
3875 // TODO: don't diagnose for inaccessible shadowed members.
3876 // This is hard to do perfectly because we might friend the
3877 // shadowing context, but that's just a false negative.
3878 }
3879
3880 // Determine what kind of declaration we're shadowing.
John McCalla2a3f7d2010-03-16 21:48:18 +00003881 unsigned Kind;
John McCall2d8c7602010-03-20 04:12:52 +00003882 if (isa<RecordDecl>(OldDC)) {
John McCalla2a3f7d2010-03-16 21:48:18 +00003883 if (isa<FieldDecl>(ShadowedDecl))
3884 Kind = 3; // field
3885 else
3886 Kind = 2; // static data member
John McCall2d8c7602010-03-20 04:12:52 +00003887 } else if (OldDC->isFileContext())
John McCalla2a3f7d2010-03-16 21:48:18 +00003888 Kind = 1; // global
3889 else
3890 Kind = 0; // local
3891
John McCall2d8c7602010-03-20 04:12:52 +00003892 DeclarationName Name = R.getLookupName();
3893
John McCalla2a3f7d2010-03-16 21:48:18 +00003894 // Emit warning and note.
John McCall2d8c7602010-03-20 04:12:52 +00003895 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
John McCalla2a3f7d2010-03-16 21:48:18 +00003896 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
3897}
3898
John McCalldf8b37c2010-03-22 09:20:08 +00003899/// \brief Check -Wshadow without the advantage of a previous lookup.
3900void Sema::CheckShadow(Scope *S, VarDecl *D) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003901 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
3902 Diagnostic::Ignored)
3903 return;
3904
John McCalldf8b37c2010-03-22 09:20:08 +00003905 LookupResult R(*this, D->getDeclName(), D->getLocation(),
3906 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
3907 LookupName(R, S);
3908 CheckShadow(S, D, R);
3909}
3910
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003911/// \brief Perform semantic checking on a newly-created variable
3912/// declaration.
3913///
3914/// This routine performs all of the type-checking required for a
Douglas Gregorf16a8a72009-05-01 15:47:09 +00003915/// variable declaration once it has been built. It is used both to
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003916/// check variables after they have been parsed and their declarators
Douglas Gregorf16a8a72009-05-01 15:47:09 +00003917/// have been translated into a declaration, and to check variables
3918/// that have been instantiated from a template.
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003919///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003920/// Sets NewVD->isInvalidDecl() if an error was encountered.
John McCall1f82f242009-11-18 22:49:29 +00003921void Sema::CheckVariableDeclaration(VarDecl *NewVD,
3922 LookupResult &Previous,
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003923 bool &Redeclaration) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003924 // If the decl is already known invalid, don't check it.
3925 if (NewVD->isInvalidDecl())
3926 return;
Mike Stump11289f42009-09-09 15:08:12 +00003927
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003928 QualType T = NewVD->getType();
3929
John McCall8b07ec22010-05-15 11:32:37 +00003930 if (T->isObjCObjectType()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003931 Diag(NewVD->getLocation(), diag::err_statically_allocated_object);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003932 return NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003933 }
Mike Stump11289f42009-09-09 15:08:12 +00003934
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003935 // Emit an error if an address space was applied to decl with local storage.
3936 // This includes arrays of objects with address space qualifiers, but not
3937 // automatic variables that point to other address spaces.
3938 // ISO/IEC TR 18037 S5.1.2
Chris Lattner88fdea82010-10-10 18:16:20 +00003939 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003940 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003941 return NewVD->setInvalidDecl();
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00003942 }
Fariborz Jahanian0c9404e2009-02-21 19:44:02 +00003943
Mike Stumpca5ae662009-04-14 00:57:29 +00003944 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
Fariborz Jahanianc32830c2011-06-07 20:15:46 +00003945 && !NewVD->hasAttr<BlocksAttr>()) {
3946 if (getLangOptions().getGCMode() != LangOptions::NonGC)
3947 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
3948 else
3949 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
3950 }
Chris Lattner88fdea82010-10-10 18:16:20 +00003951
Chris Lattner9fecd742009-04-19 05:21:20 +00003952 bool isVM = T->isVariablyModifiedType();
Chris Lattner9662cd32009-07-19 20:17:11 +00003953 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
John McCalld4e1b762010-08-01 01:24:59 +00003954 NewVD->hasAttr<BlocksAttr>())
John McCallaab3e412010-08-25 08:40:02 +00003955 getCurFunction()->setHasBranchProtectedScope();
Mike Stump11289f42009-09-09 15:08:12 +00003956
Chris Lattner9fecd742009-04-19 05:21:20 +00003957 if ((isVM && NewVD->hasLinkage()) ||
3958 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
Anders Carlsson6c885802009-02-28 21:56:50 +00003959 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003960 llvm::APSInt Oversized;
Anders Carlsson6c885802009-02-28 21:56:50 +00003961 QualType FixedTy =
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00003962 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
3963 Oversized);
Mike Stump11289f42009-09-09 15:08:12 +00003964
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003965 if (FixedTy.isNull() && T->isVariableArrayType()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00003966 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00003967 // FIXME: This won't give the correct result for
3968 // int a[10][n];
Anders Carlsson6c885802009-02-28 21:56:50 +00003969 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003970
Anders Carlsson6c885802009-02-28 21:56:50 +00003971 if (NewVD->isFileVarDecl())
3972 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003973 << SizeRange;
John McCall8e7d6562010-08-26 03:08:43 +00003974 else if (NewVD->getStorageClass() == SC_Static)
Anders Carlsson6c885802009-02-28 21:56:50 +00003975 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003976 << SizeRange;
Anders Carlsson6c885802009-02-28 21:56:50 +00003977 else
3978 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003979 << SizeRange;
3980 return NewVD->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003981 }
3982
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003983 if (FixedTy.isNull()) {
Anders Carlsson6c885802009-02-28 21:56:50 +00003984 if (NewVD->isFileVarDecl())
3985 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
3986 else
3987 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003988 return NewVD->setInvalidDecl();
Anders Carlsson6c885802009-02-28 21:56:50 +00003989 }
Mike Stump11289f42009-09-09 15:08:12 +00003990
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003991 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
3992 NewVD->setType(FixedTy);
Anders Carlsson6c885802009-02-28 21:56:50 +00003993 }
3994
John McCall1f82f242009-11-18 22:49:29 +00003995 if (Previous.empty() && NewVD->isExternC()) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00003996 // Since we did not find anything by this name and we're declaring
3997 // an extern "C" variable, look for a non-visible extern "C"
3998 // declaration with the same name.
3999 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004000 = LocallyScopedExternalDecls.find(NewVD->getDeclName());
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004001 if (Pos != LocallyScopedExternalDecls.end())
John McCall1f82f242009-11-18 22:49:29 +00004002 Previous.addDecl(Pos->second);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004003 }
4004
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004005 if (T->isVoidType() && !NewVD->hasExternalStorage()) {
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004006 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
4007 << T;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004008 return NewVD->setInvalidDecl();
Douglas Gregoref1a09a2009-03-25 23:32:15 +00004009 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004010
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004011 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00004012 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
4013 return NewVD->setInvalidDecl();
4014 }
Mike Stump11289f42009-09-09 15:08:12 +00004015
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004016 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
Mike Stumpa7128632009-05-01 23:41:47 +00004017 Diag(NewVD->getLocation(), diag::err_block_on_vm);
4018 return NewVD->setInvalidDecl();
4019 }
4020
Sebastian Redl5467c9f2010-07-12 23:11:43 +00004021 // Function pointers and references cannot have qualified function type, only
4022 // function pointer-to-members can do that.
4023 QualType Pointee;
4024 unsigned PtrOrRef = 0;
4025 if (const PointerType *Ptr = T->getAs<PointerType>())
4026 Pointee = Ptr->getPointeeType();
4027 else if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
4028 Pointee = Ref->getPointeeType();
4029 PtrOrRef = 1;
4030 }
4031 if (!Pointee.isNull() && Pointee->isFunctionProtoType() &&
4032 Pointee->getAs<FunctionProtoType>()->getTypeQuals() != 0) {
4033 Diag(NewVD->getLocation(), diag::err_invalid_qualified_function_pointer)
4034 << PtrOrRef;
4035 return NewVD->setInvalidDecl();
4036 }
4037
John McCall1f82f242009-11-18 22:49:29 +00004038 if (!Previous.empty()) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00004039 Redeclaration = true;
John McCall1f82f242009-11-18 22:49:29 +00004040 MergeVarDecl(NewVD, Previous);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004041 }
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00004042}
4043
Douglas Gregor36d1b142009-10-06 17:59:45 +00004044/// \brief Data used with FindOverriddenMethod
4045struct FindOverriddenMethodData {
4046 Sema *S;
4047 CXXMethodDecl *Method;
4048};
4049
4050/// \brief Member lookup function that determines whether a given C++
4051/// method overrides a method in a base class, to be used with
4052/// CXXRecordDecl::lookupInBases().
John McCall84c16cf2009-11-12 03:15:40 +00004053static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
Douglas Gregor36d1b142009-10-06 17:59:45 +00004054 CXXBasePath &Path,
4055 void *UserData) {
4056 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
Anders Carlssone985fae2009-11-26 20:50:40 +00004057
Douglas Gregor36d1b142009-10-06 17:59:45 +00004058 FindOverriddenMethodData *Data
4059 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
Anders Carlssone985fae2009-11-26 20:50:40 +00004060
4061 DeclarationName Name = Data->Method->getDeclName();
4062
4063 // FIXME: Do we care about other names here too?
4064 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
John McCalle9cccd82010-06-16 08:42:20 +00004065 // We really want to find the base class destructor here.
Anders Carlssone985fae2009-11-26 20:50:40 +00004066 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
4067 CanQualType CT = Data->S->Context.getCanonicalType(T);
4068
Anders Carlsson5a4f7722009-11-27 01:26:58 +00004069 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
Anders Carlssone985fae2009-11-26 20:50:40 +00004070 }
4071
4072 for (Path.Decls = BaseRecord->lookup(Name);
Douglas Gregor36d1b142009-10-06 17:59:45 +00004073 Path.Decls.first != Path.Decls.second;
4074 ++Path.Decls.first) {
John McCall38e5f432010-06-16 09:33:39 +00004075 NamedDecl *D = *Path.Decls.first;
John McCalle9cccd82010-06-16 08:42:20 +00004076 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4077 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
Douglas Gregor36d1b142009-10-06 17:59:45 +00004078 return true;
4079 }
4080 }
4081
4082 return false;
4083}
4084
Sebastian Redld5b24532009-11-18 21:51:29 +00004085/// AddOverriddenMethods - See if a method overrides any in the base classes,
4086/// and if so, check that it's a valid override and remember it.
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004087bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
Sebastian Redld5b24532009-11-18 21:51:29 +00004088 // Look for virtual methods in base classes that this method might override.
4089 CXXBasePaths Paths;
4090 FindOverriddenMethodData Data;
4091 Data.Method = MD;
4092 Data.S = this;
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004093 bool AddedAny = false;
Sebastian Redld5b24532009-11-18 21:51:29 +00004094 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
4095 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
4096 E = Paths.found_decls_end(); I != E; ++I) {
4097 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
Richard Trieu95d88092011-07-01 20:02:53 +00004098 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
Sebastian Redld5b24532009-11-18 21:51:29 +00004099 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
Alexis Hunt96d5c762009-11-21 08:43:09 +00004100 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
Anders Carlsson3f610c72011-01-20 16:25:36 +00004101 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004102 AddedAny = true;
4103 }
Sebastian Redld5b24532009-11-18 21:51:29 +00004104 }
4105 }
4106 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00004107
4108 return AddedAny;
Sebastian Redld5b24532009-11-18 21:51:29 +00004109}
4110
John McCallf7cfb222010-10-13 05:45:15 +00004111static void DiagnoseInvalidRedeclaration(Sema &S, FunctionDecl *NewFD) {
4112 LookupResult Prev(S, NewFD->getDeclName(), NewFD->getLocation(),
4113 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
4114 S.LookupQualifiedName(Prev, NewFD->getDeclContext());
4115 assert(!Prev.isAmbiguous() &&
4116 "Cannot have an ambiguity in previous-declaration lookup");
4117 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
4118 Func != FuncEnd; ++Func) {
4119 if (isa<FunctionDecl>(*Func) &&
4120 isNearlyMatchingFunction(S.Context, cast<FunctionDecl>(*Func), NewFD))
4121 S.Diag((*Func)->getLocation(), diag::note_member_def_close_match);
4122 }
4123}
4124
Mike Stump11289f42009-09-09 15:08:12 +00004125NamedDecl*
Nick Lewycky0bdf13e2011-07-02 02:05:12 +00004126Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
John McCallbcd03502009-12-07 02:54:59 +00004127 QualType R, TypeSourceInfo *TInfo,
John McCall1f82f242009-11-18 22:49:29 +00004128 LookupResult &Previous,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004129 MultiTemplateParamsArg TemplateParamLists,
Alexis Hunt5a7fa252011-05-12 06:15:49 +00004130 bool IsFunctionDefinition, bool &Redeclaration) {
Zhongxing Xubece5d62009-01-16 01:13:29 +00004131 assert(R.getTypePtr()->isFunctionType());
4132
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004133 // TODO: consider using NameInfo for diagnostic.
4134 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4135 DeclarationName Name = NameInfo.getName();
John McCall8e7d6562010-08-26 03:08:43 +00004136 FunctionDecl::StorageClass SC = SC_None;
Zhongxing Xubece5d62009-01-16 01:13:29 +00004137 switch (D.getDeclSpec().getStorageClassSpec()) {
4138 default: assert(0 && "Unknown storage class!");
4139 case DeclSpec::SCS_auto:
4140 case DeclSpec::SCS_register:
4141 case DeclSpec::SCS_mutable:
Mike Stump11289f42009-09-09 15:08:12 +00004142 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregore62c0a42009-02-24 01:23:02 +00004143 diag::err_typecheck_sclass_func);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004144 D.setInvalidType();
Zhongxing Xubece5d62009-01-16 01:13:29 +00004145 break;
John McCall8e7d6562010-08-26 03:08:43 +00004146 case DeclSpec::SCS_unspecified: SC = SC_None; break;
4147 case DeclSpec::SCS_extern: SC = SC_Extern; break;
Douglas Gregore62c0a42009-02-24 01:23:02 +00004148 case DeclSpec::SCS_static: {
Sebastian Redl50c68252010-08-31 00:36:30 +00004149 if (CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregore62c0a42009-02-24 01:23:02 +00004150 // C99 6.7.1p5:
4151 // The declaration of an identifier for a function that has
4152 // block scope shall have no explicit storage-class specifier
4153 // other than extern
4154 // See also (C++ [dcl.stc]p4).
Mike Stump11289f42009-09-09 15:08:12 +00004155 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
Douglas Gregore62c0a42009-02-24 01:23:02 +00004156 diag::err_static_block_func);
John McCall8e7d6562010-08-26 03:08:43 +00004157 SC = SC_None;
Douglas Gregore62c0a42009-02-24 01:23:02 +00004158 } else
John McCall8e7d6562010-08-26 03:08:43 +00004159 SC = SC_Static;
Douglas Gregore62c0a42009-02-24 01:23:02 +00004160 break;
4161 }
Gabor Greif80c21832010-09-08 00:31:13 +00004162 case DeclSpec::SCS_private_extern: SC = SC_PrivateExtern; break;
Zhongxing Xubece5d62009-01-16 01:13:29 +00004163 }
4164
Eli Friedmand5c0eed2009-04-19 20:27:55 +00004165 if (D.getDeclSpec().isThreadSpecified())
4166 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4167
Chris Lattner347eec92009-04-11 19:17:25 +00004168 // Do not allow returning a objc interface by-value.
John McCall8b07ec22010-05-15 11:32:37 +00004169 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
Chris Lattner347eec92009-04-11 19:17:25 +00004170 Diag(D.getIdentifierLoc(),
4171 diag::err_object_cannot_be_passed_returned_by_value) << 0
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004172 << R->getAs<FunctionType>()->getResultType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004173 D.setInvalidType();
Chris Lattner347eec92009-04-11 19:17:25 +00004174 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004175
Zhongxing Xubece5d62009-01-16 01:13:29 +00004176 FunctionDecl *NewFD;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004177 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor513e63c2010-12-10 19:28:19 +00004178 bool isFriend = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004179 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
4180 FunctionDecl::StorageClass SCAsWritten
4181 = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
Douglas Gregor513e63c2010-12-10 19:28:19 +00004182 FunctionTemplateDecl *FunctionTemplate = 0;
4183 bool isExplicitSpecialization = false;
4184 bool isFunctionTemplateSpecialization = false;
Abramo Bagnara60804e12011-03-18 15:16:37 +00004185
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004186 if (!getLangOptions().CPlusPlus) {
Douglas Gregor2797d322009-03-19 18:33:54 +00004187 // Determine whether the function was written with a
4188 // prototype. This true when:
Douglas Gregor2797d322009-03-19 18:33:54 +00004189 // - there is a prototype in the declarator, or
4190 // - the type R of the function is some kind of typedef or other reference
4191 // to a type name (which eventually refers to a function type).
Mike Stump11289f42009-09-09 15:08:12 +00004192 bool HasPrototype =
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004193 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004194 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
4195
Abramo Bagnaradff19302011-03-08 08:55:46 +00004196 NewFD = FunctionDecl::Create(Context, DC, D.getSourceRange().getBegin(),
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004197 NameInfo, R, TInfo, SC, SCAsWritten, isInline,
Douglas Gregorc4df4072010-04-19 22:54:31 +00004198 HasPrototype);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004199 if (D.isInvalidType())
4200 NewFD->setInvalidDecl();
4201
4202 // Set the lexical context.
4203 NewFD->setLexicalDeclContext(CurContext);
4204 // Filter out previous declarations that don't match the scope.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004205 FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(),
Douglas Gregordb446112011-03-07 16:54:27 +00004206 /*ExplicitInstantiationOrSpecialization=*/false);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004207 } else {
4208 isFriend = D.getDeclSpec().isFriendSpecified();
Douglas Gregor513e63c2010-12-10 19:28:19 +00004209 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
4210 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
4211 bool isVirtualOkay = false;
Zhongxing Xubece5d62009-01-16 01:13:29 +00004212
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004213 // Check that the return type is not an abstract class type.
4214 // For record types, this is done by the AbstractClassUsageDiagnoser once
4215 // the class has been completely parsed.
4216 if (!DC->isRecord() &&
4217 RequireNonAbstractType(D.getIdentifierLoc(),
4218 R->getAs<FunctionType>()->getResultType(),
4219 diag::err_abstract_type_in_decl,
4220 AbstractReturnType))
4221 D.setInvalidType();
Mike Stump11289f42009-09-09 15:08:12 +00004222
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004223 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
4224 // This is a C++ constructor declaration.
4225 assert(DC->isRecord() &&
4226 "Constructors can only be declared in a member context");
4227
4228 R = CheckConstructorDeclarator(D, R, SC);
4229
4230 // Create the new declaration
Alexis Hunt5dafebc2011-05-06 01:42:00 +00004231 CXXConstructorDecl *NewCD = CXXConstructorDecl::Create(
4232 Context,
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004233 cast<CXXRecordDecl>(DC),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004234 D.getSourceRange().getBegin(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004235 NameInfo, R, TInfo,
4236 isExplicit, isInline,
Alexis Hunt58dad7d2011-05-06 00:11:07 +00004237 /*isImplicitlyDeclared=*/false);
Alexis Hunt5dafebc2011-05-06 01:42:00 +00004238
4239 NewFD = NewCD;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004240 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4241 // This is a C++ destructor declaration.
4242 if (DC->isRecord()) {
4243 R = CheckDestructorDeclarator(D, R, SC);
Sebastian Redl623ea822011-05-19 05:13:44 +00004244 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004245
Sebastian Redl623ea822011-05-19 05:13:44 +00004246 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004247 D.getSourceRange().getBegin(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004248 NameInfo, R, TInfo,
4249 isInline,
4250 /*isImplicitlyDeclared=*/false);
Sebastian Redl623ea822011-05-19 05:13:44 +00004251 NewFD = NewDD;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004252 isVirtualOkay = true;
Sebastian Redl623ea822011-05-19 05:13:44 +00004253
4254 // If the class is complete, then we now create the implicit exception
4255 // specification. If the class is incomplete or dependent, we can't do
4256 // it yet.
4257 if (getLangOptions().CPlusPlus0x && !Record->isDependentType() &&
4258 Record->getDefinition() && !Record->isBeingDefined() &&
4259 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
4260 AdjustDestructorExceptionSpec(Record, NewDD);
4261 }
4262
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004263 } else {
4264 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
4265
4266 // Create a FunctionDecl to satisfy the function definition parsing
4267 // code path.
Abramo Bagnaradff19302011-03-08 08:55:46 +00004268 NewFD = FunctionDecl::Create(Context, DC, D.getSourceRange().getBegin(),
4269 D.getIdentifierLoc(), Name, R, TInfo,
4270 SC, SCAsWritten, isInline,
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004271 /*hasPrototype=*/true);
4272 D.setInvalidType();
4273 }
4274 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
4275 if (!DC->isRecord()) {
4276 Diag(D.getIdentifierLoc(),
4277 diag::err_conv_function_not_member);
4278 return 0;
4279 }
4280
4281 CheckConversionDeclarator(D, R, SC);
4282 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004283 D.getSourceRange().getBegin(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004284 NameInfo, R, TInfo,
Douglas Gregorf2f08062011-03-08 17:10:18 +00004285 isInline, isExplicit,
4286 SourceLocation());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004287
4288 isVirtualOkay = true;
4289 } else if (DC->isRecord()) {
4290 // If the of the function is the same as the name of the record, then this
4291 // must be an invalid constructor that has a return type.
4292 // (The parser checks for a return type and makes the declarator a
4293 // constructor if it has no return type).
4294 // must have an invalid constructor that has a return type
4295 if (Name.getAsIdentifierInfo() &&
4296 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
4297 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
4298 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4299 << SourceRange(D.getIdentifierLoc());
4300 return 0;
4301 }
4302
4303 bool isStatic = SC == SC_Static;
Sebastian Redl37588092011-03-14 18:08:30 +00004304
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004305 // [class.free]p1:
4306 // Any allocation function for a class T is a static member
4307 // (even if not explicitly declared static).
4308 if (Name.getCXXOverloadedOperator() == OO_New ||
4309 Name.getCXXOverloadedOperator() == OO_Array_New)
4310 isStatic = true;
4311
4312 // [class.free]p6 Any deallocation function for a class X is a static member
4313 // (even if not explicitly declared static).
4314 if (Name.getCXXOverloadedOperator() == OO_Delete ||
4315 Name.getCXXOverloadedOperator() == OO_Array_Delete)
4316 isStatic = true;
Sebastian Redl37588092011-03-14 18:08:30 +00004317
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004318 // This is a C++ method declaration.
Alexis Hunt5dafebc2011-05-06 01:42:00 +00004319 CXXMethodDecl *NewMD = CXXMethodDecl::Create(
4320 Context, cast<CXXRecordDecl>(DC),
4321 D.getSourceRange().getBegin(),
4322 NameInfo, R, TInfo,
4323 isStatic, SCAsWritten, isInline,
4324 SourceLocation());
4325 NewFD = NewMD;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004326
4327 isVirtualOkay = !isStatic;
4328 } else {
4329 // Determine whether the function was written with a
4330 // prototype. This true when:
4331 // - we're in C++ (where every function has a prototype),
Abramo Bagnaradff19302011-03-08 08:55:46 +00004332 NewFD = FunctionDecl::Create(Context, DC, D.getSourceRange().getBegin(),
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004333 NameInfo, R, TInfo, SC, SCAsWritten, isInline,
4334 true/*HasPrototype*/);
4335 }
Abramo Bagnaraa3088e62011-03-18 15:21:59 +00004336
4337 if (isFriend && !isInline && IsFunctionDefinition) {
4338 // C++ [class.friend]p5
4339 // A function can be defined in a friend declaration of a
4340 // class . . . . Such a function is implicitly inline.
4341 NewFD->setImplicitlyInline();
4342 }
4343
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004344 SetNestedNameSpecifier(NewFD, D);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004345 isExplicitSpecialization = false;
4346 isFunctionTemplateSpecialization = false;
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004347 if (D.isInvalidType())
4348 NewFD->setInvalidDecl();
4349
4350 // Set the lexical context. If the declarator has a C++
4351 // scope specifier, or is the object of a friend declaration, the
4352 // lexical context will be different from the semantic context.
4353 NewFD->setLexicalDeclContext(CurContext);
4354
4355 // Match up the template parameter lists with the scope specifier, then
4356 // determine whether we have a template or a template specialization.
4357 bool Invalid = false;
4358 if (TemplateParameterList *TemplateParams
Douglas Gregor93ded322011-03-04 22:45:55 +00004359 = MatchTemplateParametersToScopeSpecifier(
Douglas Gregord8d297c2009-07-21 23:53:31 +00004360 D.getDeclSpec().getSourceRange().getBegin(),
Douglas Gregor972fe532011-05-10 18:27:06 +00004361 D.getIdentifierLoc(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00004362 D.getCXXScopeSpec(),
John McCall2c2eb122010-10-16 06:59:13 +00004363 TemplateParamLists.get(),
4364 TemplateParamLists.size(),
4365 isFriend,
4366 isExplicitSpecialization,
4367 Invalid)) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00004368 if (TemplateParams->size() > 0) {
4369 // This is a function template
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00004370
Abramo Bagnara60804e12011-03-18 15:16:37 +00004371 // Check that we can declare a template here.
4372 if (CheckTemplateDeclScope(S, TemplateParams))
4373 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004374
Abramo Bagnara60804e12011-03-18 15:16:37 +00004375 // A destructor cannot be a template.
4376 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4377 Diag(NewFD->getLocation(), diag::err_destructor_template);
4378 return 0;
John McCall1f0479e2010-03-24 08:27:58 +00004379 }
4380
Abramo Bagnara60804e12011-03-18 15:16:37 +00004381 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
4382 NewFD->getLocation(),
4383 Name, TemplateParams,
4384 NewFD);
4385 FunctionTemplate->setLexicalDeclContext(CurContext);
4386 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
4387
4388 // For source fidelity, store the other template param lists.
4389 if (TemplateParamLists.size() > 1) {
4390 NewFD->setTemplateParameterListsInfo(Context,
4391 TemplateParamLists.size() - 1,
4392 TemplateParamLists.release());
4393 }
4394 } else {
4395 // This is a function template specialization.
4396 isFunctionTemplateSpecialization = true;
4397 // For source fidelity, store all the template param lists.
4398 NewFD->setTemplateParameterListsInfo(Context,
4399 TemplateParamLists.size(),
4400 TemplateParamLists.release());
4401
4402 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
4403 if (isFriend) {
4404 // We want to remove the "template<>", found here.
4405 SourceRange RemoveRange = TemplateParams->getSourceRange();
4406
4407 // If we remove the template<> and the name is not a
4408 // template-id, we're actually silently creating a problem:
4409 // the friend declaration will refer to an untemplated decl,
4410 // and clearly the user wants a template specialization. So
4411 // we need to insert '<>' after the name.
4412 SourceLocation InsertLoc;
4413 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
4414 InsertLoc = D.getName().getSourceRange().getEnd();
4415 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
4416 }
4417
4418 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
4419 << Name << RemoveRange
4420 << FixItHint::CreateRemoval(RemoveRange)
4421 << FixItHint::CreateInsertion(InsertLoc, "<>");
4422 }
4423 }
4424 }
4425 else {
4426 // All template param lists were matched against the scope specifier:
4427 // this is NOT (an explicit specialization of) a template.
4428 if (TemplateParamLists.size() > 0)
4429 // For source fidelity, store all the template param lists.
4430 NewFD->setTemplateParameterListsInfo(Context,
4431 TemplateParamLists.size(),
4432 TemplateParamLists.release());
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004433 }
4434
4435 if (Invalid) {
4436 NewFD->setInvalidDecl();
4437 if (FunctionTemplate)
4438 FunctionTemplate->setInvalidDecl();
4439 }
4440
4441 // C++ [dcl.fct.spec]p5:
4442 // The virtual specifier shall only be used in declarations of
4443 // nonstatic class member functions that appear within a
4444 // member-specification of a class declaration; see 10.3.
4445 //
4446 if (isVirtual && !NewFD->isInvalidDecl()) {
4447 if (!isVirtualOkay) {
4448 Diag(D.getDeclSpec().getVirtualSpecLoc(),
4449 diag::err_virtual_non_function);
4450 } else if (!CurContext->isRecord()) {
4451 // 'virtual' was specified outside of the class.
Anders Carlssone9738992011-01-22 14:43:56 +00004452 Diag(D.getDeclSpec().getVirtualSpecLoc(),
4453 diag::err_virtual_out_of_class)
4454 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
4455 } else if (NewFD->getDescribedFunctionTemplate()) {
4456 // C++ [temp.mem]p3:
4457 // A member function template shall not be virtual.
4458 Diag(D.getDeclSpec().getVirtualSpecLoc(),
4459 diag::err_virtual_member_function_template)
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004460 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
4461 } else {
4462 // Okay: Add virtual to the method.
4463 NewFD->setVirtualAsWritten(true);
John McCall816d75b2010-03-24 07:46:06 +00004464 }
Douglas Gregorc1da0f02009-06-24 00:23:40 +00004465 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00004466
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004467 // C++ [dcl.fct.spec]p3:
4468 // The inline specifier shall not appear on a block scope function declaration.
4469 if (isInline && !NewFD->isInvalidDecl()) {
4470 if (CurContext->isFunctionOrMethod()) {
4471 // 'inline' is not allowed on block scope function declaration.
4472 Diag(D.getDeclSpec().getInlineSpecLoc(),
4473 diag::err_inline_declaration_block_scope) << Name
4474 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
4475 }
4476 }
4477
4478 // C++ [dcl.fct.spec]p6:
4479 // The explicit specifier shall be used only in the declaration of a
4480 // constructor or conversion function within its class definition; see 12.3.1
4481 // and 12.3.2.
4482 if (isExplicit && !NewFD->isInvalidDecl()) {
4483 if (!CurContext->isRecord()) {
4484 // 'explicit' was specified outside of the class.
4485 Diag(D.getDeclSpec().getExplicitSpecLoc(),
4486 diag::err_explicit_out_of_class)
4487 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
4488 } else if (!isa<CXXConstructorDecl>(NewFD) &&
4489 !isa<CXXConversionDecl>(NewFD)) {
4490 // 'explicit' was specified on a function that wasn't a constructor
4491 // or conversion function.
4492 Diag(D.getDeclSpec().getExplicitSpecLoc(),
4493 diag::err_explicit_non_ctor_or_conv_function)
4494 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
4495 }
4496 }
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00004497
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004498 // Filter out previous declarations that don't match the scope.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004499 FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(),
Douglas Gregordb446112011-03-07 16:54:27 +00004500 isExplicitSpecialization ||
4501 isFunctionTemplateSpecialization);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004502
4503 if (isFriend) {
4504 // For now, claim that the objects have no previous declaration.
4505 if (FunctionTemplate) {
4506 FunctionTemplate->setObjectOfFriendDecl(false);
4507 FunctionTemplate->setAccess(AS_public);
4508 }
4509 NewFD->setObjectOfFriendDecl(false);
4510 NewFD->setAccess(AS_public);
4511 }
4512
John McCall357d0f32010-12-15 04:00:32 +00004513 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && IsFunctionDefinition) {
4514 // A method is implicitly inline if it's defined in its class
4515 // definition.
4516 NewFD->setImplicitlyInline();
4517 }
4518
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004519 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
4520 !CurContext->isRecord()) {
4521 // C++ [class.static]p1:
4522 // A data or function member of a class may be declared static
4523 // in a class definition, in which case it is a static member of
4524 // the class.
4525
4526 // Complain about the 'static' specifier if it's on an out-of-line
4527 // member function definition.
4528 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4529 diag::err_static_out_of_line)
4530 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4531 }
Douglas Gregor5f0e2522010-07-14 23:14:12 +00004532 }
4533
Zhongxing Xubece5d62009-01-16 01:13:29 +00004534 // Handle GNU asm-label extension (encoded as an attribute).
4535 if (Expr *E = (Expr*) D.getAsmLabel()) {
4536 // The parser guarantees this is a string.
Mike Stump11289f42009-09-09 15:08:12 +00004537 StringLiteral *SE = cast<StringLiteral>(E);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004538 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
4539 SE->getString()));
Zhongxing Xubece5d62009-01-16 01:13:29 +00004540 }
4541
Chris Lattner9af40c12009-04-25 06:12:16 +00004542 // Copy the parameter declarations from the declarator D to the function
4543 // declaration NewFD, if they are available. First scavenge them into Params.
4544 llvm::SmallVector<ParmVarDecl*, 16> Params;
Abramo Bagnara6d810632010-12-14 22:11:44 +00004545 if (D.isFunctionDeclarator()) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004546 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Zhongxing Xubece5d62009-01-16 01:13:29 +00004547
Zhongxing Xubece5d62009-01-16 01:13:29 +00004548 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
4549 // function that takes no arguments, not a function that takes a
4550 // single void argument.
4551 // We let through "const void" here because Sema::GetTypeForDeclarator
4552 // already checks for that case.
4553 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4554 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00004555 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
Chris Lattner9af40c12009-04-25 06:12:16 +00004556 // Empty arg list, don't push any params.
John McCall48871652010-08-21 09:40:31 +00004557 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[0].Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00004558
4559 // In C++, the empty parameter-type-list must be spelled "void"; a
4560 // typedef of void is not permitted.
4561 if (getLangOptions().CPlusPlus &&
Richard Smithdda56e42011-04-15 14:24:37 +00004562 Param->getType().getUnqualifiedType() != Context.VoidTy) {
4563 bool IsTypeAlias = false;
4564 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
4565 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00004566 else if (const TemplateSpecializationType *TST =
4567 Param->getType()->getAs<TemplateSpecializationType>())
4568 IsTypeAlias = TST->isTypeAlias();
Richard Smithdda56e42011-04-15 14:24:37 +00004569 Diag(Param->getLocation(), diag::err_param_typedef_of_void)
4570 << IsTypeAlias;
4571 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004572 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00004573 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +00004574 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00004575 assert(Param->getDeclContext() != NewFD && "Was set before ?");
4576 Param->setDeclContext(NewFD);
4577 Params.push_back(Param);
John McCallb7238602010-04-14 01:27:20 +00004578
4579 if (Param->isInvalidDecl())
4580 NewFD->setInvalidDecl();
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00004581 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00004582 }
Mike Stump11289f42009-09-09 15:08:12 +00004583
John McCall9dd450b2009-09-21 23:43:11 +00004584 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
Chris Lattner47c0d002009-04-25 06:03:53 +00004585 // When we're declaring a function with a typedef, typeof, etc as in the
Zhongxing Xubece5d62009-01-16 01:13:29 +00004586 // following example, we'll need to synthesize (unnamed)
4587 // parameters for use in the declaration.
4588 //
4589 // @code
4590 // typedef void fn(int);
4591 // fn f;
4592 // @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004593
Chris Lattner47c0d002009-04-25 06:03:53 +00004594 // Synthesize a parameter for each argument type.
Chris Lattner47c0d002009-04-25 06:03:53 +00004595 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
4596 AE = FT->arg_type_end(); AI != AE; ++AI) {
John McCalla3ccba02010-06-04 11:21:44 +00004597 ParmVarDecl *Param =
4598 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
John McCall8fb0d9d2011-05-01 22:35:37 +00004599 Param->setScopeInfo(0, Params.size());
Chris Lattner47c0d002009-04-25 06:03:53 +00004600 Params.push_back(Param);
Zhongxing Xubece5d62009-01-16 01:13:29 +00004601 }
Chris Lattner49303b22009-04-25 18:38:18 +00004602 } else {
4603 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
4604 "Should not need args for typedef of non-prototype fn");
Zhongxing Xubece5d62009-01-16 01:13:29 +00004605 }
Chris Lattner9af40c12009-04-25 06:12:16 +00004606 // Finally, we know we have the right number of parameters, install them.
Douglas Gregord5058122010-02-11 01:19:42 +00004607 NewFD->setParams(Params.data(), Params.size());
Mike Stump11289f42009-09-09 15:08:12 +00004608
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004609 // Process the non-inheritable attributes on this declaration.
4610 ProcessDeclAttributes(S, NewFD, D,
4611 /*NonInheritable=*/true, /*Inheritable=*/false);
4612
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004613 if (!getLangOptions().CPlusPlus) {
4614 // Perform semantic checking on the function declaration.
Douglas Gregor522d5eb2011-06-06 15:22:55 +00004615 bool isExplicitSpecialization=false;
4616 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization,
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004617 Redeclaration);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004618 assert((NewFD->isInvalidDecl() || !Redeclaration ||
4619 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
4620 "previous declaration set still overloaded");
4621 } else {
4622 // If the declarator is a template-id, translate the parser's template
4623 // argument list into our AST format.
4624 bool HasExplicitTemplateArgs = false;
4625 TemplateArgumentListInfo TemplateArgs;
4626 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
4627 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4628 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
4629 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
4630 ASTTemplateArgsPtr TemplateArgsPtr(*this,
4631 TemplateId->getTemplateArgs(),
4632 TemplateId->NumArgs);
4633 translateTemplateArguments(TemplateArgsPtr,
4634 TemplateArgs);
4635 TemplateArgsPtr.release();
Douglas Gregor0e876e02009-09-25 23:53:26 +00004636
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004637 HasExplicitTemplateArgs = true;
Douglas Gregor0e876e02009-09-25 23:53:26 +00004638
Douglas Gregor522d5eb2011-06-06 15:22:55 +00004639 if (NewFD->isInvalidDecl()) {
4640 HasExplicitTemplateArgs = false;
4641 } else if (FunctionTemplate) {
Douglas Gregora5f6f9c2011-01-24 18:54:39 +00004642 // Function template with explicit template arguments.
4643 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
4644 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
4645
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004646 HasExplicitTemplateArgs = false;
4647 } else if (!isFunctionTemplateSpecialization &&
4648 !D.getDeclSpec().isFriendSpecified()) {
4649 // We have encountered something that the user meant to be a
4650 // specialization (because it has explicitly-specified template
4651 // arguments) but that was not introduced with a "template<>" (or had
4652 // too few of them).
4653 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
4654 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
4655 << FixItHint::CreateInsertion(
4656 D.getDeclSpec().getSourceRange().getBegin(),
4657 "template<> ");
4658 isFunctionTemplateSpecialization = true;
John McCallf7cfb222010-10-13 05:45:15 +00004659 } else {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004660 // "friend void foo<>(int);" is an implicit specialization decl.
4661 isFunctionTemplateSpecialization = true;
Francois Pichet6d76e6c2010-10-01 21:19:28 +00004662 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004663 } else if (isFriend && isFunctionTemplateSpecialization) {
4664 // This combination is only possible in a recovery case; the user
4665 // wrote something like:
4666 // template <> friend void foo(int);
4667 // which we're recovering from as if the user had written:
4668 // friend void foo<>(int);
4669 // Go ahead and fake up a template id.
4670 HasExplicitTemplateArgs = true;
4671 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
4672 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004673 }
John McCallf7cfb222010-10-13 05:45:15 +00004674
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004675 // If it's a friend (and only if it's a friend), it's possible
4676 // that either the specialized function type or the specialized
4677 // template is dependent, and therefore matching will fail. In
4678 // this case, don't check the specialization yet.
4679 if (isFunctionTemplateSpecialization && isFriend &&
4680 (NewFD->getType()->isDependentType() || DC->isDependentContext())) {
4681 assert(HasExplicitTemplateArgs &&
4682 "friend function specialization without template args");
4683 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
4684 Previous))
4685 NewFD->setInvalidDecl();
4686 } else if (isFunctionTemplateSpecialization) {
Douglas Gregor63fab342011-03-16 19:27:09 +00004687 if (CurContext->isDependentContext() && CurContext->isRecord()
Francois Pichetb5037052011-06-03 13:59:45 +00004688 && !isFriend) {
Douglas Gregor63fab342011-03-16 19:27:09 +00004689 Diag(NewFD->getLocation(), diag::err_function_specialization_in_class)
4690 << NewFD->getDeclName();
4691 NewFD->setInvalidDecl();
4692 return 0;
4693 } else if (CheckFunctionTemplateSpecialization(NewFD,
4694 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
4695 Previous))
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004696 NewFD->setInvalidDecl();
Douglas Gregor781ba6e2011-05-21 18:53:30 +00004697
4698 // C++ [dcl.stc]p1:
4699 // A storage-class-specifier shall not be specified in an explicit
4700 // specialization (14.7.3)
4701 if (SC != SC_None) {
Douglas Gregor84265a02011-06-17 05:09:08 +00004702 if (SC != NewFD->getStorageClass())
4703 Diag(NewFD->getLocation(),
4704 diag::err_explicit_specialization_inconsistent_storage_class)
4705 << SC
4706 << FixItHint::CreateRemoval(
4707 D.getDeclSpec().getStorageClassSpecLoc());
4708
4709 else
4710 Diag(NewFD->getLocation(),
4711 diag::ext_explicit_specialization_storage_class)
4712 << FixItHint::CreateRemoval(
4713 D.getDeclSpec().getStorageClassSpecLoc());
Douglas Gregor781ba6e2011-05-21 18:53:30 +00004714 }
4715
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004716 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
4717 if (CheckMemberSpecialization(NewFD, Previous))
4718 NewFD->setInvalidDecl();
4719 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004720
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004721 // Perform semantic checking on the function declaration.
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004722 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization,
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004723 Redeclaration);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004724
4725 assert((NewFD->isInvalidDecl() || !Redeclaration ||
4726 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
4727 "previous declaration set still overloaded");
4728
4729 NamedDecl *PrincipalDecl = (FunctionTemplate
4730 ? cast<NamedDecl>(FunctionTemplate)
4731 : NewFD);
4732
4733 if (isFriend && Redeclaration) {
4734 AccessSpecifier Access = AS_public;
4735 if (!NewFD->isInvalidDecl())
4736 Access = NewFD->getPreviousDeclaration()->getAccess();
4737
4738 NewFD->setAccess(Access);
4739 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
4740
4741 PrincipalDecl->setObjectOfFriendDecl(true);
4742 }
4743
4744 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
4745 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4746 PrincipalDecl->setNonMemberOperator();
4747
4748 // If we have a function template, check the template parameter
4749 // list. This will check and merge default template arguments.
4750 if (FunctionTemplate) {
4751 FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration();
4752 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
4753 PrevTemplate? PrevTemplate->getTemplateParameters() : 0,
Douglas Gregora99fb4c2011-02-04 04:20:44 +00004754 D.getDeclSpec().isFriendSpecified()
4755 ? (IsFunctionDefinition
4756 ? TPC_FriendFunctionTemplateDefinition
4757 : TPC_FriendFunctionTemplate)
4758 : (D.getCXXScopeSpec().isSet() &&
Douglas Gregor4d5c2972011-02-04 12:22:53 +00004759 DC && DC->isRecord() &&
4760 DC->isDependentContext())
Douglas Gregora99fb4c2011-02-04 04:20:44 +00004761 ? TPC_ClassTemplateMember
4762 : TPC_FunctionTemplate);
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004763 }
4764
4765 if (NewFD->isInvalidDecl()) {
4766 // Ignore all the rest of this.
4767 } else if (!Redeclaration) {
4768 // Fake up an access specifier if it's supposed to be a class member.
4769 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
4770 NewFD->setAccess(AS_public);
4771
4772 // Qualified decls generally require a previous declaration.
4773 if (D.getCXXScopeSpec().isSet()) {
4774 // ...with the major exception of templated-scope or
4775 // dependent-scope friend declarations.
4776
4777 // TODO: we currently also suppress this check in dependent
4778 // contexts because (1) the parameter depth will be off when
4779 // matching friend templates and (2) we might actually be
4780 // selecting a friend based on a dependent factor. But there
4781 // are situations where these conditions don't apply and we
4782 // can actually do this check immediately.
4783 if (isFriend &&
Abramo Bagnara60804e12011-03-18 15:16:37 +00004784 (TemplateParamLists.size() ||
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004785 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
4786 CurContext->isDependentContext())) {
4787 // ignore these
4788 } else {
4789 // The user tried to provide an out-of-line definition for a
4790 // function that is a member of a class or namespace, but there
4791 // was no such member function declared (C++ [class.mfct]p2,
4792 // C++ [namespace.memdef]p2). For example:
4793 //
4794 // class X {
4795 // void f() const;
4796 // };
4797 //
4798 // void X::f() { } // ill-formed
4799 //
4800 // Complain about this problem, and attempt to suggest close
4801 // matches (e.g., those that differ only in cv-qualifiers and
4802 // whether the parameter types are references).
4803 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
4804 << Name << DC << D.getCXXScopeSpec().getRange();
4805 NewFD->setInvalidDecl();
4806
4807 DiagnoseInvalidRedeclaration(*this, NewFD);
4808 }
4809
4810 // Unqualified local friend declarations are required to resolve
4811 // to something.
4812 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
4813 Diag(D.getIdentifierLoc(), diag::err_no_matching_local_friend);
4814 NewFD->setInvalidDecl();
4815 DiagnoseInvalidRedeclaration(*this, NewFD);
4816 }
4817
4818 } else if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
4819 !isFriend && !isFunctionTemplateSpecialization &&
Alexis Hunt5a7fa252011-05-12 06:15:49 +00004820 !isExplicitSpecialization) {
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004821 // An out-of-line member function declaration must also be a
4822 // definition (C++ [dcl.meaning]p1).
4823 // Note that this is not the case for explicit specializations of
4824 // function templates or member functions of class templates, per
4825 // C++ [temp.expl.spec]p2. We also allow these declarations as an extension
4826 // for compatibility with old SWIG code which likes to generate them.
4827 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
4828 << D.getCXXScopeSpec().getRange();
4829 }
4830 }
Alexis Hunt5a7fa252011-05-12 06:15:49 +00004831
4832
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004833 // Handle attributes. We need to have merged decls when handling attributes
4834 // (for example to check for conflicts, etc).
4835 // FIXME: This needs to happen before we merge declarations. Then,
4836 // let attribute merging cope with attribute conflicts.
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004837 ProcessDeclAttributes(S, NewFD, D,
4838 /*NonInheritable=*/false, /*Inheritable=*/true);
Ryan Flynne5dc8592009-07-25 22:29:44 +00004839
4840 // attributes declared post-definition are currently ignored
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004841 // FIXME: This should happen during attribute merging
John McCall1f82f242009-11-18 22:49:29 +00004842 if (Redeclaration && Previous.isSingleResult()) {
4843 const FunctionDecl *Def;
4844 FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004845 if (PrevFD && PrevFD->isDefined(Def) && D.hasAttributes()) {
Ryan Flynne5dc8592009-07-25 22:29:44 +00004846 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
4847 Diag(Def->getLocation(), diag::note_previous_definition);
4848 }
4849 }
4850
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004851 AddKnownFunctionAttributes(NewFD);
4852
Douglas Gregor72609052010-08-06 13:50:58 +00004853 if (NewFD->hasAttr<OverloadableAttr>() &&
4854 !NewFD->getType()->getAs<FunctionProtoType>()) {
4855 Diag(NewFD->getLocation(),
4856 diag::err_attribute_overloadable_no_prototype)
4857 << NewFD;
4858
4859 // Turn this into a variadic function with no parameters.
4860 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
John McCalldb40c7f2010-12-14 08:05:40 +00004861 FunctionProtoType::ExtProtoInfo EPI;
4862 EPI.Variadic = true;
4863 EPI.ExtInfo = FT->getExtInfo();
4864
4865 QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI);
Douglas Gregor72609052010-08-06 13:50:58 +00004866 NewFD->setType(R);
4867 }
4868
Eli Friedman570024a2010-08-05 06:57:20 +00004869 // If there's a #pragma GCC visibility in scope, and this isn't a class
4870 // member, set the visibility of this function.
4871 if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
4872 AddPushedVisibilityAttribute(NewFD);
4873
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004874 // If this is a locally-scoped extern C function, update the
4875 // map of such names.
Douglas Gregor16618f22009-09-12 00:17:51 +00004876 if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004877 && !NewFD->isInvalidDecl())
John McCall1f82f242009-11-18 22:49:29 +00004878 RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004879
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00004880 // Set this FunctionDecl's range up to the right paren.
Abramo Bagnaraea947882011-03-08 16:41:52 +00004881 NewFD->setRangeEnd(D.getSourceRange().getEnd());
Argyrios Kyrtzidis16eecc42009-06-25 18:22:24 +00004882
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004883 if (getLangOptions().CPlusPlus) {
4884 if (FunctionTemplate) {
4885 if (NewFD->isInvalidDecl())
4886 FunctionTemplate->setInvalidDecl();
4887 return FunctionTemplate;
4888 }
Fariborz Jahanian31d6d842010-12-09 23:11:32 +00004889 }
Mike Stump11289f42009-09-09 15:08:12 +00004890
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00004891 MarkUnusedFileScopedDecl(NewFD);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004892
4893 if (getLangOptions().CUDA)
4894 if (IdentifierInfo *II = NewFD->getIdentifier())
4895 if (!NewFD->isInvalidDecl() &&
4896 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
4897 if (II->isStr("cudaConfigureCall")) {
4898 if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
4899 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
4900
4901 Context.setcudaConfigureCallDecl(NewFD);
4902 }
4903 }
4904
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004905 return NewFD;
4906}
4907
4908/// \brief Perform semantic checking of a new function declaration.
4909///
4910/// Performs semantic analysis of the new function declaration
4911/// NewFD. This routine performs all semantic checking that does not
4912/// require the actual declarator involved in the declaration, and is
4913/// used both for the declaration of functions as they are parsed
4914/// (called via ActOnDeclarator) and for the declaration of functions
4915/// that have been instantiated via C++ template instantiation (called
4916/// via InstantiateDecl).
4917///
Douglas Gregorcf915552009-10-13 16:30:37 +00004918/// \param IsExplicitSpecialiation whether this new function declaration is
4919/// an explicit specialization of the previous declaration.
4920///
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004921/// This sets NewFD->isInvalidDecl() to true if there was an error.
John McCall84d87672009-12-10 09:41:52 +00004922void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
John McCall1f82f242009-11-18 22:49:29 +00004923 LookupResult &Previous,
Douglas Gregorcf915552009-10-13 16:30:37 +00004924 bool IsExplicitSpecialization,
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004925 bool &Redeclaration) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004926 // If NewFD is already known erroneous, don't do any of this checking.
John McCall12d53da2010-08-12 00:57:17 +00004927 if (NewFD->isInvalidDecl()) {
4928 // If this is a class member, mark the class invalid immediately.
4929 // This avoids some consistency errors later.
4930 if (isa<CXXMethodDecl>(NewFD))
4931 cast<CXXMethodDecl>(NewFD)->getParent()->setInvalidDecl();
4932
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00004933 return;
John McCall12d53da2010-08-12 00:57:17 +00004934 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004935
Eli Friedman54135832009-05-16 12:15:55 +00004936 if (NewFD->getResultType()->isVariablyModifiedType()) {
4937 // Functions returning a variably modified type violate C99 6.7.5.2p2
4938 // because all functions have linkage.
4939 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
4940 return NewFD->setInvalidDecl();
4941 }
4942
Douglas Gregor16618f22009-09-12 00:17:51 +00004943 if (NewFD->isMain())
4944 CheckMain(NewFD);
John McCalld9baf6a2009-07-24 03:03:21 +00004945
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004946 // Check for a previous declaration of this name.
John McCall1f82f242009-11-18 22:49:29 +00004947 if (Previous.empty() && NewFD->isExternC()) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004948 // Since we did not find anything by this name and we're declaring
4949 // an extern "C" function, look for a non-visible extern "C"
4950 // declaration with the same name.
4951 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
Douglas Gregorf4f296d2009-03-23 23:06:20 +00004952 = LocallyScopedExternalDecls.find(NewFD->getDeclName());
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004953 if (Pos != LocallyScopedExternalDecls.end())
John McCall1f82f242009-11-18 22:49:29 +00004954 Previous.addDecl(Pos->second);
Douglas Gregor5a80bd12009-03-02 00:19:53 +00004955 }
4956
Douglas Gregore62c0a42009-02-24 01:23:02 +00004957 // Merge or overload the declaration with an existing declaration of
4958 // the same name, if appropriate.
John McCall1f82f242009-11-18 22:49:29 +00004959 if (!Previous.empty()) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00004960 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xubece5d62009-01-16 01:13:29 +00004961 // a declaration that requires merging. If it's an overload,
4962 // there's no more work to do here; we'll just add the new
4963 // function to the scope.
Douglas Gregor633b7372009-02-13 00:26:38 +00004964
John McCall1f82f242009-11-18 22:49:29 +00004965 NamedDecl *OldDecl = 0;
John McCalldaa3d6b2009-12-09 03:35:25 +00004966 if (!AllowOverloadingOfFunction(Previous, Context)) {
4967 Redeclaration = true;
4968 OldDecl = Previous.getFoundDecl();
4969 } else {
John McCalle9cccd82010-06-16 08:42:20 +00004970 switch (CheckOverload(S, NewFD, Previous, OldDecl,
4971 /*NewIsUsingDecl*/ false)) {
John McCalldaa3d6b2009-12-09 03:35:25 +00004972 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00004973 Redeclaration = true;
John McCalldaa3d6b2009-12-09 03:35:25 +00004974 break;
4975
4976 case Ovl_NonFunction:
4977 Redeclaration = true;
4978 break;
4979
4980 case Ovl_Overload:
4981 Redeclaration = false;
4982 break;
John McCall1f82f242009-11-18 22:49:29 +00004983 }
Peter Collingbourne9f2a9902011-01-21 02:08:54 +00004984
4985 if (!getLangOptions().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
4986 // If a function name is overloadable in C, then every function
4987 // with that name must be marked "overloadable".
4988 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
4989 << Redeclaration << NewFD;
4990 NamedDecl *OverloadedDecl = 0;
4991 if (Redeclaration)
4992 OverloadedDecl = OldDecl;
4993 else if (!Previous.empty())
4994 OverloadedDecl = Previous.getRepresentativeDecl();
4995 if (OverloadedDecl)
4996 Diag(OverloadedDecl->getLocation(),
4997 diag::note_attribute_overloadable_prev_overload);
4998 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
4999 Context));
5000 }
John McCall1f82f242009-11-18 22:49:29 +00005001 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005002
John McCall1f82f242009-11-18 22:49:29 +00005003 if (Redeclaration) {
Douglas Gregorf4f296d2009-03-23 23:06:20 +00005004 // NewFD and OldDecl represent declarations that need to be
Mike Stump11289f42009-09-09 15:08:12 +00005005 // merged.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00005006 if (MergeFunctionDecl(NewFD, OldDecl))
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005007 return NewFD->setInvalidDecl();
Zhongxing Xubece5d62009-01-16 01:13:29 +00005008
John McCall1f82f242009-11-18 22:49:29 +00005009 Previous.clear();
5010 Previous.addDecl(OldDecl);
5011
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005012 if (FunctionTemplateDecl *OldTemplateDecl
Douglas Gregorca027af2009-10-12 22:27:17 +00005013 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
Douglas Gregorcf915552009-10-13 16:30:37 +00005014 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
Douglas Gregorca027af2009-10-12 22:27:17 +00005015 FunctionTemplateDecl *NewTemplateDecl
5016 = NewFD->getDescribedFunctionTemplate();
5017 assert(NewTemplateDecl && "Template/non-template mismatch");
5018 if (CXXMethodDecl *Method
5019 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
5020 Method->setAccess(OldTemplateDecl->getAccess());
5021 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
5022 }
Douglas Gregorcf915552009-10-13 16:30:37 +00005023
5024 // If this is an explicit specialization of a member that is a function
5025 // template, mark it as a member specialization.
5026 if (IsExplicitSpecialization &&
5027 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
5028 NewTemplateDecl->setMemberSpecialization();
5029 assert(OldTemplateDecl->isMemberSpecialization());
5030 }
Douglas Gregorca027af2009-10-12 22:27:17 +00005031 } else {
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00005032 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
5033 NewFD->setAccess(OldDecl->getAccess());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005034 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
Argyrios Kyrtzidis11a846a2009-07-14 03:18:53 +00005035 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005036 }
Douglas Gregor8af63e42009-02-06 17:46:57 +00005037 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005038
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005039 // Semantic checking for this function declaration (in isolation).
5040 if (getLangOptions().CPlusPlus) {
5041 // C++-specific checks.
5042 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
5043 CheckConstructor(Constructor);
Anders Carlsson2a50e952009-11-15 22:49:34 +00005044 } else if (CXXDestructorDecl *Destructor =
5045 dyn_cast<CXXDestructorDecl>(NewFD)) {
5046 CXXRecordDecl *Record = Destructor->getParent();
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005047 QualType ClassType = Context.getTypeDeclType(Record);
Anders Carlsson2a50e952009-11-15 22:49:34 +00005048
Douglas Gregor7454c562010-07-02 20:37:36 +00005049 // FIXME: Shouldn't we be able to perform this check even when the class
Anders Carlsson2a50e952009-11-15 22:49:34 +00005050 // type is dependent? Both gcc and edg can handle that.
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005051 if (!ClassType->isDependentType()) {
5052 DeclarationName Name
5053 = Context.DeclarationNames.getCXXDestructorName(
5054 Context.getCanonicalType(ClassType));
5055 if (NewFD->getDeclName() != Name) {
5056 Diag(NewFD->getLocation(), diag::err_destructor_name);
5057 return NewFD->setInvalidDecl();
5058 }
5059 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005060 } else if (CXXConversionDecl *Conversion
Douglas Gregor21920e372009-12-01 17:24:26 +00005061 = dyn_cast<CXXConversionDecl>(NewFD)) {
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005062 ActOnConversionDeclarator(Conversion);
Douglas Gregor21920e372009-12-01 17:24:26 +00005063 }
5064
5065 // Find any virtual functions that this function overrides.
Douglas Gregor6be3de32009-12-01 17:35:23 +00005066 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
5067 if (!Method->isFunctionTemplateSpecialization() &&
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005068 !Method->getDescribedFunctionTemplate()) {
5069 if (AddOverriddenMethods(Method->getParent(), Method)) {
5070 // If the function was marked as "static", we have a problem.
5071 if (NewFD->getStorageClass() == SC_Static) {
5072 Diag(NewFD->getLocation(), diag::err_static_overrides_virtual)
5073 << NewFD->getDeclName();
5074 for (CXXMethodDecl::method_iterator
5075 Overridden = Method->begin_overridden_methods(),
5076 OverriddenEnd = Method->end_overridden_methods();
5077 Overridden != OverriddenEnd;
5078 ++Overridden) {
5079 Diag((*Overridden)->getLocation(),
5080 diag::note_overridden_virtual_function);
5081 }
5082 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005083 }
Douglas Gregor5a2bb5b2010-10-13 22:55:32 +00005084 }
Douglas Gregor6be3de32009-12-01 17:35:23 +00005085 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005086
5087 // Extra checking for C++ overloaded operators (C++ [over.oper]).
5088 if (NewFD->isOverloadedOperator() &&
5089 CheckOverloadedOperatorDeclaration(NewFD))
5090 return NewFD->setInvalidDecl();
Alexis Huntc88db062010-01-13 09:01:02 +00005091
5092 // Extra checking for C++0x literal operators (C++0x [over.literal]).
5093 if (NewFD->getLiteralIdentifier() &&
5094 CheckLiteralOperatorDeclaration(NewFD))
5095 return NewFD->setInvalidDecl();
5096
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005097 // In C++, check default arguments now that we have merged decls. Unless
5098 // the lexical context is the class, because in this case this is done
5099 // during delayed parsing anyway.
5100 if (!CurContext->isRecord())
5101 CheckCXXDefaultArguments(NewFD);
Douglas Gregor9246b682010-12-21 19:47:46 +00005102
5103 // If this function declares a builtin function, check the type of this
5104 // declaration against the expected type for the builtin.
5105 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
5106 ASTContext::GetBuiltinTypeError Error;
5107 QualType T = Context.GetBuiltinType(BuiltinID, Error);
5108 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
5109 // The type of this function differs from the type of the builtin,
5110 // so forget about the builtin entirely.
5111 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
5112 }
5113 }
Anders Carlsson1b12ed42009-09-13 21:33:06 +00005114 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00005115}
5116
John McCalld9baf6a2009-07-24 03:03:21 +00005117void Sema::CheckMain(FunctionDecl* FD) {
John McCall02dee0a2009-07-25 04:36:53 +00005118 // C++ [basic.start.main]p3: A program that declares main to be inline
5119 // or static is ill-formed.
5120 // C99 6.7.4p4: In a hosted environment, the inline function specifier
5121 // shall not appear in a declaration of main.
5122 // static main is not an error under C99, but we should warn about it.
Douglas Gregor35b57532009-10-27 21:01:01 +00005123 bool isInline = FD->isInlineSpecified();
John McCall8e7d6562010-08-26 03:08:43 +00005124 bool isStatic = FD->getStorageClass() == SC_Static;
John McCall02dee0a2009-07-25 04:36:53 +00005125 if (isInline || isStatic) {
5126 unsigned diagID = diag::warn_unusual_main_decl;
5127 if (isInline || getLangOptions().CPlusPlus)
5128 diagID = diag::err_unusual_main_decl;
5129
5130 int which = isStatic + (isInline << 1) - 1;
5131 Diag(FD->getLocation(), diagID) << which;
5132 }
5133
5134 QualType T = FD->getType();
5135 assert(T->isFunctionType() && "function decl is not of function type");
John McCall9dd450b2009-09-21 23:43:11 +00005136 const FunctionType* FT = T->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00005137
John McCall02dee0a2009-07-25 04:36:53 +00005138 if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
Douglas Gregorf05c0952011-02-19 19:04:23 +00005139 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
John McCall02dee0a2009-07-25 04:36:53 +00005140 FD->setInvalidDecl(true);
5141 }
5142
5143 // Treat protoless main() as nullary.
5144 if (isa<FunctionNoProtoType>(FT)) return;
5145
5146 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
5147 unsigned nparams = FTP->getNumArgs();
5148 assert(FD->getNumParams() == nparams);
5149
John McCall0e21fcc2009-12-24 09:58:38 +00005150 bool HasExtraParameters = (nparams > 3);
5151
5152 // Darwin passes an undocumented fourth argument of type char**. If
5153 // other platforms start sprouting these, the logic below will start
5154 // getting shifty.
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00005155 if (nparams == 4 && Context.Target.getTriple().isOSDarwin())
John McCall0e21fcc2009-12-24 09:58:38 +00005156 HasExtraParameters = false;
5157
5158 if (HasExtraParameters) {
John McCall02dee0a2009-07-25 04:36:53 +00005159 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
5160 FD->setInvalidDecl(true);
5161 nparams = 3;
5162 }
5163
5164 // FIXME: a lot of the following diagnostics would be improved
5165 // if we had some location information about types.
5166
5167 QualType CharPP =
5168 Context.getPointerType(Context.getPointerType(Context.CharTy));
John McCall0e21fcc2009-12-24 09:58:38 +00005169 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
John McCall02dee0a2009-07-25 04:36:53 +00005170
5171 for (unsigned i = 0; i < nparams; ++i) {
5172 QualType AT = FTP->getArgType(i);
5173
5174 bool mismatch = true;
5175
5176 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
5177 mismatch = false;
5178 else if (Expected[i] == CharPP) {
5179 // As an extension, the following forms are okay:
5180 // char const **
5181 // char const * const *
5182 // char * const *
5183
John McCall8ccfcb52009-09-24 19:53:00 +00005184 QualifierCollector qs;
John McCall02dee0a2009-07-25 04:36:53 +00005185 const PointerType* PT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005186 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
5187 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
John McCall02dee0a2009-07-25 04:36:53 +00005188 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
5189 qs.removeConst();
5190 mismatch = !qs.empty();
5191 }
5192 }
5193
5194 if (mismatch) {
5195 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
5196 // TODO: suggest replacing given type with expected type
5197 FD->setInvalidDecl(true);
5198 }
5199 }
5200
5201 if (nparams == 1 && !FD->isInvalidDecl()) {
5202 Diag(FD->getLocation(), diag::warn_main_one_arg);
5203 }
Douglas Gregorbff62032010-10-21 16:57:46 +00005204
5205 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
5206 Diag(FD->getLocation(), diag::err_main_template_decl);
5207 FD->setInvalidDecl();
5208 }
John McCalld9baf6a2009-07-24 03:03:21 +00005209}
5210
Eli Friedmand5a55bd2008-05-20 13:48:25 +00005211bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00005212 // FIXME: Need strict checking. In C89, we need to check for
5213 // any assignment, increment, decrement, function-calls, or
5214 // commas outside of a sizeof. In C99, it's the same list,
5215 // except that the aforementioned are allowed in unevaluated
5216 // expressions. Everything else falls under the
5217 // "may accept other forms of constant expressions" exception.
5218 // (We never end up here for C++, so the constant expression
5219 // rules there don't matter.)
John McCall8b0f4ff2010-08-02 21:13:48 +00005220 if (Init->isConstantInitializer(Context, false))
Eli Friedman7bfab362009-02-22 06:45:27 +00005221 return false;
Eli Friedman4f294cf2009-02-26 04:47:58 +00005222 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
5223 << Init->getSourceRange();
Eli Friedmand5a55bd2008-05-20 13:48:25 +00005224 return true;
Steve Naroff98f72032008-01-10 22:15:12 +00005225}
5226
Chandler Carruth33bf3e72011-03-27 09:46:56 +00005227namespace {
5228 // Visits an initialization expression to see if OrigDecl is evaluated in
5229 // its own initialization and throws a warning if it does.
5230 class SelfReferenceChecker
5231 : public EvaluatedExprVisitor<SelfReferenceChecker> {
5232 Sema &S;
5233 Decl *OrigDecl;
5234
5235 public:
5236 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
5237
5238 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
5239 S(S), OrigDecl(OrigDecl) { }
5240
5241 void VisitExpr(Expr *E) {
5242 if (isa<ObjCMessageExpr>(*E)) return;
5243 Inherited::VisitExpr(E);
5244 }
5245
5246 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
5247 CheckForSelfReference(E);
5248 Inherited::VisitImplicitCastExpr(E);
5249 }
5250
5251 void CheckForSelfReference(ImplicitCastExpr *E) {
5252 if (E->getCastKind() != CK_LValueToRValue) return;
5253 Expr* SubExpr = E->getSubExpr()->IgnoreParenImpCasts();
5254 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr);
5255 if (!DRE) return;
5256 Decl* ReferenceDecl = DRE->getDecl();
5257 if (OrigDecl != ReferenceDecl) return;
5258 LookupResult Result(S, DRE->getNameInfo(), Sema::LookupOrdinaryName,
5259 Sema::NotForRedeclaration);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005260 S.DiagRuntimeBehavior(SubExpr->getLocStart(), SubExpr,
5261 S.PDiag(diag::warn_uninit_self_reference_in_init)
5262 << Result.getLookupName()
5263 << OrigDecl->getLocation()
5264 << SubExpr->getSourceRange());
Chandler Carruth33bf3e72011-03-27 09:46:56 +00005265 }
5266 };
5267}
5268
Douglas Gregor5fb53972009-01-14 15:45:31 +00005269/// AddInitializerToDecl - Adds the initializer Init to the
5270/// declaration dcl. If DirectInit is true, this is C++ direct
5271/// initialization rather than copy initialization.
Richard Smith30482bc2011-02-20 03:19:35 +00005272void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
5273 bool DirectInit, bool TypeMayContainAuto) {
Chris Lattner8beb9de2007-10-19 20:10:30 +00005274 // If there is no declaration, there was an error parsing it. Just ignore
5275 // the initializer.
Richard Smith30482bc2011-02-20 03:19:35 +00005276 if (RealDecl == 0 || RealDecl->isInvalidDecl())
Chris Lattner8beb9de2007-10-19 20:10:30 +00005277 return;
Mike Stump11289f42009-09-09 15:08:12 +00005278
Ted Kremenek37881932011-04-04 23:29:12 +00005279 // Check for self-references within variable initializers.
5280 if (VarDecl *vd = dyn_cast<VarDecl>(RealDecl)) {
5281 // Variables declared within a function/method body are handled
5282 // by a dataflow analysis.
5283 if (!vd->hasLocalStorage() && !vd->isStaticLocal())
5284 SelfReferenceChecker(*this, RealDecl).VisitExpr(Init);
5285 }
5286 else {
5287 SelfReferenceChecker(*this, RealDecl).VisitExpr(Init);
5288 }
Chandler Carruth33bf3e72011-03-27 09:46:56 +00005289
Douglas Gregor0c880302009-03-11 23:00:04 +00005290 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
5291 // With declarators parsed the way they are, the parser cannot
5292 // distinguish between a normal initializer and a pure-specifier.
5293 // Thus this grotesque test.
5294 IntegerLiteral *IL;
Douglas Gregor0c880302009-03-11 23:00:04 +00005295 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
Douglas Gregor21920e372009-12-01 17:24:26 +00005296 Context.getCanonicalType(IL->getType()) == Context.IntTy)
5297 CheckPureMethod(Method, Init->getSourceRange());
5298 else {
Douglas Gregor0c880302009-03-11 23:00:04 +00005299 Diag(Method->getLocation(), diag::err_member_function_initialization)
5300 << Method->getDeclName() << Init->getSourceRange();
5301 Method->setInvalidDecl();
5302 }
5303 return;
5304 }
5305
Steve Naroff437b4d82007-09-12 20:13:48 +00005306 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5307 if (!VDecl) {
Richard Smith4a4beec2011-06-12 11:43:46 +00005308 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
5309 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +00005310 RealDecl->setInvalidDecl();
5311 return;
Eli Friedman2c7bd6b2009-02-27 04:17:12 +00005312 }
5313
Richard Smith30482bc2011-02-20 03:19:35 +00005314 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
5315 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith9647d3c2011-03-17 16:11:59 +00005316 TypeSourceInfo *DeducedType = 0;
5317 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith30482bc2011-02-20 03:19:35 +00005318 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
5319 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
5320 << Init->getSourceRange();
Richard Smith9647d3c2011-03-17 16:11:59 +00005321 if (!DeducedType) {
Richard Smith30482bc2011-02-20 03:19:35 +00005322 RealDecl->setInvalidDecl();
5323 return;
5324 }
Richard Smith9647d3c2011-03-17 16:11:59 +00005325 VDecl->setTypeSourceInfo(DeducedType);
5326 VDecl->setType(DeducedType->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00005327
John McCall31168b02011-06-15 23:02:42 +00005328 // In ARC, infer lifetime.
5329 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
5330 VDecl->setInvalidDecl();
5331
Richard Smith30482bc2011-02-20 03:19:35 +00005332 // If this is a redeclaration, check that the type we just deduced matches
5333 // the previously declared type.
5334 if (VarDecl *Old = VDecl->getPreviousDeclaration())
5335 MergeVarDeclTypes(VDecl, Old);
5336 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00005337
5338
Eli Friedmanc9827d12009-11-14 03:40:14 +00005339 // A definition must end up with a complete type, which means it must be
5340 // complete with the restriction that an array type might be completed by the
5341 // initializer; note that later code assumes this restriction.
5342 QualType BaseDeclType = VDecl->getType();
5343 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
5344 BaseDeclType = Array->getElementType();
5345 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
Eli Friedman337cd3a2009-04-13 21:28:54 +00005346 diag::err_typecheck_decl_incomplete_type)) {
5347 RealDecl->setInvalidDecl();
5348 return;
5349 }
5350
Douglas Gregorc99f1552009-12-03 18:33:45 +00005351 // The variable can not have an abstract class type.
5352 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5353 diag::err_abstract_type_in_decl,
5354 AbstractVariableType))
5355 VDecl->setInvalidDecl();
5356
Sebastian Redl5ca79842010-02-01 20:16:42 +00005357 const VarDecl *Def;
5358 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00005359 Diag(VDecl->getLocation(), diag::err_redefinition)
Douglas Gregor0760fa12009-03-10 23:43:53 +00005360 << VDecl->getDeclName();
5361 Diag(Def->getLocation(), diag::note_previous_definition);
5362 VDecl->setInvalidDecl();
5363 return;
5364 }
Douglas Gregorf0f83692010-08-24 05:27:49 +00005365
Douglas Gregorf0f83692010-08-24 05:27:49 +00005366 const VarDecl* PrevInit = 0;
Douglas Gregor71f39c92010-12-16 01:31:22 +00005367 if (getLangOptions().CPlusPlus) {
5368 // C++ [class.static.data]p4
5369 // If a static data member is of const integral or const
5370 // enumeration type, its declaration in the class definition can
5371 // specify a constant-initializer which shall be an integral
5372 // constant expression (5.19). In that case, the member can appear
5373 // in integral constant expressions. The member shall still be
5374 // defined in a namespace scope if it is used in the program and the
5375 // namespace scope definition shall not contain an initializer.
5376 //
5377 // We already performed a redefinition check above, but for static
5378 // data members we also need to check whether there was an in-class
5379 // declaration with an initializer.
5380 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5381 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5382 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5383 return;
5384 }
Douglas Gregor0760fa12009-03-10 23:43:53 +00005385
Douglas Gregor71f39c92010-12-16 01:31:22 +00005386 if (VDecl->hasLocalStorage())
5387 getCurFunction()->setHasBranchProtectedScope();
5388
5389 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
5390 VDecl->setInvalidDecl();
5391 return;
5392 }
5393 }
John McCalld4e1b762010-08-01 01:24:59 +00005394
Douglas Gregor85dabae2009-12-16 01:38:02 +00005395 // Capture the variable that is being initialized and the style of
5396 // initialization.
5397 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5398
5399 // FIXME: Poor source location information.
5400 InitializationKind Kind
5401 = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(),
5402 Init->getLocStart(),
5403 Init->getLocEnd())
5404 : InitializationKind::CreateCopy(VDecl->getLocation(),
5405 Init->getLocStart());
5406
Steve Naroff61091402007-09-12 14:07:44 +00005407 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +00005408 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +00005409 QualType DclT = VDecl->getType(), SavT = DclT;
John McCall1c9c3fd2010-10-15 04:57:14 +00005410 if (VDecl->isLocalVarDecl()) {
Daniel Dunbar0ca16602009-04-14 02:25:56 +00005411 if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
Steve Naroff437b4d82007-09-12 20:13:48 +00005412 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff08899ff2008-04-15 22:42:06 +00005413 VDecl->setInvalidDecl();
5414 } else if (!VDecl->isInvalidDecl()) {
Eli Friedman78275202009-12-19 08:11:05 +00005415 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
John McCalldadc5752010-08-24 06:29:42 +00005416 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00005417 MultiExprArg(*this, &Init, 1),
Eli Friedman463e5232009-12-22 02:10:53 +00005418 &DclT);
5419 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00005420 VDecl->setInvalidDecl();
Eli Friedman78275202009-12-19 08:11:05 +00005421 return;
5422 }
Mike Stump11289f42009-09-09 15:08:12 +00005423
Eli Friedman463e5232009-12-22 02:10:53 +00005424 Init = Result.takeAs<Expr>();
5425
Anders Carlsson41e08812008-08-22 05:00:02 +00005426 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmance982572009-02-20 01:34:21 +00005427 // Don't check invalid declarations to avoid emitting useless diagnostics.
5428 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
John McCall8e7d6562010-08-26 03:08:43 +00005429 if (VDecl->getStorageClass() == SC_Static) // C99 6.7.8p4.
Anders Carlsson41e08812008-08-22 05:00:02 +00005430 CheckForConstantInitializer(Init, DclT);
5431 }
Steve Naroff61091402007-09-12 14:07:44 +00005432 }
Mike Stump11289f42009-09-09 15:08:12 +00005433 } else if (VDecl->isStaticDataMember() &&
Douglas Gregor0c880302009-03-11 23:00:04 +00005434 VDecl->getLexicalDeclContext()->isRecord()) {
5435 // This is an in-class initialization for a static data member, e.g.,
5436 //
5437 // struct S {
5438 // static const int value = 17;
5439 // };
5440
John McCalldb768922010-09-10 23:21:22 +00005441 // Try to perform the initialization regardless.
5442 if (!VDecl->isInvalidDecl()) {
5443 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
5444 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
5445 MultiExprArg(*this, &Init, 1),
5446 &DclT);
5447 if (Result.isInvalid()) {
5448 VDecl->setInvalidDecl();
5449 return;
5450 }
5451
5452 Init = Result.takeAs<Expr>();
5453 }
Douglas Gregor0c880302009-03-11 23:00:04 +00005454
5455 // C++ [class.mem]p4:
5456 // A member-declarator can contain a constant-initializer only
5457 // if it declares a static member (9.4) of const integral or
5458 // const enumeration type, see 9.4.2.
5459 QualType T = VDecl->getType();
John McCalldb768922010-09-10 23:21:22 +00005460
5461 // Do nothing on dependent types.
5462 if (T->isDependentType()) {
5463
5464 // Require constness.
5465 } else if (!T.isConstQualified()) {
5466 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
5467 << Init->getSourceRange();
Douglas Gregor0c880302009-03-11 23:00:04 +00005468 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00005469
5470 // We allow integer constant expressions in all cases.
5471 } else if (T->isIntegralOrEnumerationType()) {
Chris Lattner9925ec82011-06-14 05:46:29 +00005472 // Check whether the expression is a constant expression.
5473 SourceLocation Loc;
5474 if (Init->isValueDependent())
5475 ; // Nothing to check.
5476 else if (Init->isIntegerConstantExpr(Context, &Loc))
5477 ; // Ok, it's an ICE!
5478 else if (Init->isEvaluatable(Context)) {
5479 // If we can constant fold the initializer through heroics, accept it,
5480 // but report this as a use of an extension for -pedantic.
5481 Diag(Loc, diag::ext_in_class_initializer_non_constant)
5482 << Init->getSourceRange();
5483 } else {
5484 // Otherwise, this is some crazy unknown case. Report the issue at the
5485 // location provided by the isIntegerConstantExpr failed check.
5486 Diag(Loc, diag::err_in_class_initializer_non_constant)
5487 << Init->getSourceRange();
5488 VDecl->setInvalidDecl();
John McCalldb768922010-09-10 23:21:22 +00005489 }
5490
5491 // We allow floating-point constants as an extension in C++03, and
5492 // C++0x has far more complicated rules that we don't really
5493 // implement fully.
5494 } else {
5495 bool Allowed = false;
5496 if (getLangOptions().CPlusPlus0x) {
5497 Allowed = T->isLiteralType();
5498 } else if (T->isFloatingType()) { // also permits complex, which is ok
5499 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
5500 << T << Init->getSourceRange();
5501 Allowed = true;
5502 }
5503
5504 if (!Allowed) {
5505 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
5506 << T << Init->getSourceRange();
5507 VDecl->setInvalidDecl();
5508
5509 // TODO: there are probably expressions that pass here that shouldn't.
5510 } else if (!Init->isValueDependent() &&
5511 !Init->isConstantInitializer(Context, false)) {
5512 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
5513 << Init->getSourceRange();
5514 VDecl->setInvalidDecl();
Douglas Gregor0c880302009-03-11 23:00:04 +00005515 }
5516 }
Steve Naroff08899ff2008-04-15 22:42:06 +00005517 } else if (VDecl->isFileVarDecl()) {
Douglas Gregord4e1fb52010-10-15 01:21:46 +00005518 if (VDecl->getStorageClassAsWritten() == SC_Extern &&
Douglas Gregorfceea362010-04-22 14:36:26 +00005519 (!getLangOptions().CPlusPlus ||
5520 !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
Steve Naroff437b4d82007-09-12 20:13:48 +00005521 Diag(VDecl->getLocation(), diag::warn_extern_init);
Eli Friedman463e5232009-12-22 02:10:53 +00005522 if (!VDecl->isInvalidDecl()) {
5523 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
John McCalldadc5752010-08-24 06:29:42 +00005524 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00005525 MultiExprArg(*this, &Init, 1),
Eli Friedman463e5232009-12-22 02:10:53 +00005526 &DclT);
5527 if (Result.isInvalid()) {
Steve Naroff08899ff2008-04-15 22:42:06 +00005528 VDecl->setInvalidDecl();
Eli Friedman463e5232009-12-22 02:10:53 +00005529 return;
5530 }
5531
5532 Init = Result.takeAs<Expr>();
5533 }
Mike Stump11289f42009-09-09 15:08:12 +00005534
Anders Carlsson41e08812008-08-22 05:00:02 +00005535 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmance982572009-02-20 01:34:21 +00005536 // Don't check invalid declarations to avoid emitting useless diagnostics.
5537 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
Anders Carlsson41e08812008-08-22 05:00:02 +00005538 // C99 6.7.8p4. All file scoped initializers need to be constant.
5539 CheckForConstantInitializer(Init, DclT);
5540 }
Steve Naroff61091402007-09-12 14:07:44 +00005541 }
5542 // If the type changed, it means we had an incomplete type that was
Mike Stump11289f42009-09-09 15:08:12 +00005543 // completed by the initializer. For example:
Steve Naroff61091402007-09-12 14:07:44 +00005544 // int ary[] = { 1, 3, 5 };
5545 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb2ed9afd2007-11-29 19:09:19 +00005546 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff437b4d82007-09-12 20:13:48 +00005547 VDecl->setType(DclT);
Christopher Lamb2ed9afd2007-11-29 19:09:19 +00005548 Init->setType(DclT);
5549 }
Mike Stump11289f42009-09-09 15:08:12 +00005550
Chris Lattner88fdea82010-10-10 18:16:20 +00005551
5552 // If this variable is a local declaration with record type, make sure it
5553 // doesn't have a flexible member initialization. We only support this as a
5554 // global/static definition.
5555 if (VDecl->hasLocalStorage())
5556 if (const RecordType *RT = VDecl->getType()->getAs<RecordType>())
Douglas Gregor1f81ced2010-10-15 23:53:28 +00005557 if (RT->getDecl()->hasFlexibleArrayMember()) {
5558 // Check whether the initializer tries to initialize the flexible
5559 // array member itself to anything other than an empty initializer list.
5560 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5561 unsigned Index = std::distance(RT->getDecl()->field_begin(),
5562 RT->getDecl()->field_end()) - 1;
5563 if (Index < ILE->getNumInits() &&
5564 !(isa<InitListExpr>(ILE->getInit(Index)) &&
5565 cast<InitListExpr>(ILE->getInit(Index))->getNumInits() == 0)) {
5566 Diag(VDecl->getLocation(), diag::err_nonstatic_flexible_variable);
5567 VDecl->setInvalidDecl();
5568 }
5569 }
Chris Lattner88fdea82010-10-10 18:16:20 +00005570 }
5571
John McCallacf0ee52010-10-08 02:01:28 +00005572 // Check any implicit conversions within the expression.
5573 CheckImplicitConversions(Init, VDecl->getLocation());
John McCall31168b02011-06-15 23:02:42 +00005574
5575 if (!VDecl->isInvalidDecl())
5576 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
5577
John McCall5d413782010-12-06 08:20:24 +00005578 Init = MaybeCreateExprWithCleanups(Init);
Steve Naroff61091402007-09-12 14:07:44 +00005579 // Attach the initializer to the decl.
Douglas Gregord5058122010-02-11 01:19:42 +00005580 VDecl->setInit(Init);
Douglas Gregorbeecd582009-04-21 17:11:58 +00005581
John McCall8b7fd8f12011-01-19 11:48:09 +00005582 CheckCompleteVariableDeclaration(VDecl);
Steve Naroff61091402007-09-12 14:07:44 +00005583}
5584
John McCalleae5acb2010-03-31 02:13:20 +00005585/// ActOnInitializerError - Given that there was an error parsing an
5586/// initializer for the given declaration, try to return to some form
5587/// of sanity.
John McCall48871652010-08-21 09:40:31 +00005588void Sema::ActOnInitializerError(Decl *D) {
John McCalleae5acb2010-03-31 02:13:20 +00005589 // Our main concern here is re-establishing invariants like "a
5590 // variable's type is either dependent or complete".
John McCalleae5acb2010-03-31 02:13:20 +00005591 if (!D || D->isInvalidDecl()) return;
5592
5593 VarDecl *VD = dyn_cast<VarDecl>(D);
5594 if (!VD) return;
5595
Richard Smith30482bc2011-02-20 03:19:35 +00005596 // Auto types are meaningless if we can't make sense of the initializer.
Richard Smithb2bc2e62011-02-21 20:05:19 +00005597 if (ParsingInitForAutoVars.count(D)) {
5598 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00005599 return;
5600 }
5601
John McCalleae5acb2010-03-31 02:13:20 +00005602 QualType Ty = VD->getType();
5603 if (Ty->isDependentType()) return;
5604
5605 // Require a complete type.
5606 if (RequireCompleteType(VD->getLocation(),
5607 Context.getBaseElementType(Ty),
5608 diag::err_typecheck_decl_incomplete_type)) {
5609 VD->setInvalidDecl();
5610 return;
5611 }
5612
5613 // Require an abstract type.
5614 if (RequireNonAbstractType(VD->getLocation(), Ty,
5615 diag::err_abstract_type_in_decl,
5616 AbstractVariableType)) {
5617 VD->setInvalidDecl();
5618 return;
5619 }
5620
5621 // Don't bother complaining about constructors or destructors,
5622 // though.
5623}
5624
John McCall48871652010-08-21 09:40:31 +00005625void Sema::ActOnUninitializedDecl(Decl *RealDecl,
Richard Smith30482bc2011-02-20 03:19:35 +00005626 bool TypeMayContainAuto) {
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00005627 // If there is no declaration, there was an error parsing it. Just ignore it.
5628 if (RealDecl == 0)
5629 return;
5630
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005631 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
5632 QualType Type = Var->getType();
Douglas Gregorbeecd582009-04-21 17:11:58 +00005633
Anders Carlssonae019932009-07-11 00:34:39 +00005634 // C++0x [dcl.spec.auto]p3
Richard Smith30482bc2011-02-20 03:19:35 +00005635 if (TypeMayContainAuto && Type->getContainedAutoType()) {
Anders Carlssonae019932009-07-11 00:34:39 +00005636 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
5637 << Var->getDeclName() << Type;
5638 Var->setInvalidDecl();
5639 return;
5640 }
Mike Stump11289f42009-09-09 15:08:12 +00005641
Douglas Gregore6565622010-02-09 07:26:29 +00005642 switch (Var->isThisDeclarationADefinition()) {
5643 case VarDecl::Definition:
5644 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
5645 break;
5646
5647 // We have an out-of-line definition of a static data member
5648 // that has an in-class initializer, so we type-check this like
5649 // a declaration.
5650 //
5651 // Fall through
5652
5653 case VarDecl::DeclarationOnly:
5654 // It's only a declaration.
5655
5656 // Block scope. C99 6.7p7: If an identifier for an object is
5657 // declared with no linkage (C99 6.2.2p6), the type for the
5658 // object shall be complete.
John McCall1c9c3fd2010-10-15 04:57:14 +00005659 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
Douglas Gregore6565622010-02-09 07:26:29 +00005660 !Var->getLinkage() && !Var->isInvalidDecl() &&
5661 RequireCompleteType(Var->getLocation(), Type,
5662 diag::err_typecheck_decl_incomplete_type))
5663 Var->setInvalidDecl();
5664
5665 // Make sure that the type is not abstract.
5666 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
5667 RequireNonAbstractType(Var->getLocation(), Type,
5668 diag::err_abstract_type_in_decl,
5669 AbstractVariableType))
5670 Var->setInvalidDecl();
5671 return;
5672
5673 case VarDecl::TentativeDefinition:
5674 // File scope. C99 6.9.2p2: A declaration of an identifier for an
5675 // object that has file scope without an initializer, and without a
5676 // storage-class specifier or with the storage-class specifier "static",
5677 // constitutes a tentative definition. Note: A tentative definition with
5678 // external linkage is valid (C99 6.2.2p5).
5679 if (!Var->isInvalidDecl()) {
5680 if (const IncompleteArrayType *ArrayT
5681 = Context.getAsIncompleteArrayType(Type)) {
5682 if (RequireCompleteType(Var->getLocation(),
5683 ArrayT->getElementType(),
5684 diag::err_illegal_decl_array_incomplete_type))
5685 Var->setInvalidDecl();
John McCall8e7d6562010-08-26 03:08:43 +00005686 } else if (Var->getStorageClass() == SC_Static) {
Douglas Gregore6565622010-02-09 07:26:29 +00005687 // C99 6.9.2p3: If the declaration of an identifier for an object is
5688 // a tentative definition and has internal linkage (C99 6.2.2p3), the
5689 // declared type shall not be an incomplete type.
5690 // NOTE: code such as the following
5691 // static struct s;
5692 // struct s { int a; };
5693 // is accepted by gcc. Hence here we issue a warning instead of
5694 // an error and we do not invalidate the static declaration.
5695 // NOTE: to avoid multiple warnings, only check the first declaration.
5696 if (Var->getPreviousDeclaration() == 0)
5697 RequireCompleteType(Var->getLocation(), Type,
5698 diag::ext_typecheck_decl_incomplete_type);
5699 }
5700 }
5701
5702 // Record the tentative definition; we're done.
5703 if (!Var->isInvalidDecl())
5704 TentativeDefinitions.push_back(Var);
5705 return;
5706 }
5707
5708 // Provide a specific diagnostic for uninitialized variable
5709 // definitions with incomplete array type.
5710 if (Type->isIncompleteArrayType()) {
Sebastian Redl10600672009-11-05 19:47:47 +00005711 Diag(Var->getLocation(),
5712 diag::err_typecheck_incomplete_array_needs_initializer);
5713 Var->setInvalidDecl();
5714 return;
5715 }
5716
John McCalla755f0f2010-08-01 01:25:24 +00005717 // Provide a specific diagnostic for uninitialized variable
5718 // definitions with reference type.
5719 if (Type->isReferenceType()) {
5720 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
5721 << Var->getDeclName()
5722 << SourceRange(Var->getLocation(), Var->getLocation());
5723 Var->setInvalidDecl();
5724 return;
5725 }
Douglas Gregore6565622010-02-09 07:26:29 +00005726
5727 // Do not attempt to type-check the default initializer for a
5728 // variable with dependent type.
5729 if (Type->isDependentType())
Douglas Gregor86d142a2009-10-08 07:24:58 +00005730 return;
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005731
Douglas Gregore6565622010-02-09 07:26:29 +00005732 if (Var->isInvalidDecl())
5733 return;
Douglas Gregorc99f1552009-12-03 18:33:45 +00005734
Douglas Gregore6565622010-02-09 07:26:29 +00005735 if (RequireCompleteType(Var->getLocation(),
5736 Context.getBaseElementType(Type),
5737 diag::err_typecheck_decl_incomplete_type)) {
5738 Var->setInvalidDecl();
5739 return;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00005740 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005741
Douglas Gregore6565622010-02-09 07:26:29 +00005742 // The variable can not have an abstract class type.
5743 if (RequireNonAbstractType(Var->getLocation(), Type,
5744 diag::err_abstract_type_in_decl,
5745 AbstractVariableType)) {
5746 Var->setInvalidDecl();
5747 return;
5748 }
5749
Douglas Gregor9574af62011-05-21 17:52:48 +00005750 // Check for jumps past the implicit initializer. C++0x
5751 // clarifies that this applies to a "variable with automatic
5752 // storage duration", not a "local variable".
5753 // C++0x [stmt.dcl]p3
5754 // A program that jumps from a point where a variable with automatic
5755 // storage duration is not in scope to a point where it is in scope is
5756 // ill-formed unless the variable has scalar type, class type with a
5757 // trivial default constructor and a trivial destructor, a cv-qualified
5758 // version of one of these types, or an array of one of the preceding
5759 // types and is declared without an initializer.
5760 if (getLangOptions().CPlusPlus && Var->hasLocalStorage()) {
5761 if (const RecordType *Record
5762 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
Alexis Hunt466627c2011-05-11 22:50:12 +00005763 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor9574af62011-05-21 17:52:48 +00005764 if ((!getLangOptions().CPlusPlus0x && !CXXRecord->isPOD()) ||
5765 (getLangOptions().CPlusPlus0x &&
5766 (!CXXRecord->hasTrivialDefaultConstructor() ||
Douglas Gregor22ae6962011-05-27 21:28:00 +00005767 !CXXRecord->hasTrivialDestructor())))
Alexis Hunt466627c2011-05-11 22:50:12 +00005768 getCurFunction()->setHasBranchProtectedScope();
5769 }
Douglas Gregore6565622010-02-09 07:26:29 +00005770 }
Douglas Gregor9574af62011-05-21 17:52:48 +00005771
5772 // C++03 [dcl.init]p9:
5773 // If no initializer is specified for an object, and the
5774 // object is of (possibly cv-qualified) non-POD class type (or
5775 // array thereof), the object shall be default-initialized; if
5776 // the object is of const-qualified type, the underlying class
5777 // type shall have a user-declared default
5778 // constructor. Otherwise, if no initializer is specified for
5779 // a non- static object, the object and its subobjects, if
5780 // any, have an indeterminate initial value); if the object
5781 // or any of its subobjects are of const-qualified type, the
5782 // program is ill-formed.
5783 // C++0x [dcl.init]p11:
5784 // If no initializer is specified for an object, the object is
5785 // default-initialized; [...].
5786 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
5787 InitializationKind Kind
5788 = InitializationKind::CreateDefault(Var->getLocation());
5789
5790 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
5791 ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
5792 MultiExprArg(*this, 0, 0));
5793 if (Init.isInvalid())
5794 Var->setInvalidDecl();
5795 else if (Init.get())
5796 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
Douglas Gregor589973b2010-03-08 02:45:10 +00005797
John McCall8b7fd8f12011-01-19 11:48:09 +00005798 CheckCompleteVariableDeclaration(Var);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005799 }
5800}
5801
Richard Smith02e85f32011-04-14 22:09:26 +00005802void Sema::ActOnCXXForRangeDecl(Decl *D) {
5803 VarDecl *VD = dyn_cast<VarDecl>(D);
5804 if (!VD) {
5805 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
5806 D->setInvalidDecl();
5807 return;
5808 }
5809
5810 VD->setCXXForRangeDecl(true);
5811
5812 // for-range-declaration cannot be given a storage class specifier.
5813 int Error = -1;
5814 switch (VD->getStorageClassAsWritten()) {
5815 case SC_None:
5816 break;
5817 case SC_Extern:
5818 Error = 0;
5819 break;
5820 case SC_Static:
5821 Error = 1;
5822 break;
5823 case SC_PrivateExtern:
5824 Error = 2;
5825 break;
5826 case SC_Auto:
5827 Error = 3;
5828 break;
5829 case SC_Register:
5830 Error = 4;
5831 break;
5832 }
5833 // FIXME: constexpr isn't allowed here.
5834 //if (DS.isConstexprSpecified())
5835 // Error = 5;
5836 if (Error != -1) {
5837 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
5838 << VD->getDeclName() << Error;
5839 D->setInvalidDecl();
5840 }
5841}
5842
John McCall8b7fd8f12011-01-19 11:48:09 +00005843void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
5844 if (var->isInvalidDecl()) return;
5845
John McCall31168b02011-06-15 23:02:42 +00005846 // In ARC, don't allow jumps past the implicit initialization of a
5847 // local retaining variable.
5848 if (getLangOptions().ObjCAutoRefCount &&
5849 var->hasLocalStorage()) {
5850 switch (var->getType().getObjCLifetime()) {
5851 case Qualifiers::OCL_None:
5852 case Qualifiers::OCL_ExplicitNone:
5853 case Qualifiers::OCL_Autoreleasing:
5854 break;
5855
5856 case Qualifiers::OCL_Weak:
5857 case Qualifiers::OCL_Strong:
5858 getCurFunction()->setHasBranchProtectedScope();
5859 break;
5860 }
5861 }
5862
John McCall8b7fd8f12011-01-19 11:48:09 +00005863 // All the following checks are C++ only.
5864 if (!getLangOptions().CPlusPlus) return;
5865
5866 QualType baseType = Context.getBaseElementType(var->getType());
5867 if (baseType->isDependentType()) return;
5868
5869 // __block variables might require us to capture a copy-initializer.
5870 if (var->hasAttr<BlocksAttr>()) {
5871 // It's currently invalid to ever have a __block variable with an
5872 // array type; should we diagnose that here?
5873
5874 // Regardless, we don't want to ignore array nesting when
5875 // constructing this copy.
5876 QualType type = var->getType();
5877
5878 if (type->isStructureOrClassType()) {
5879 SourceLocation poi = var->getLocation();
5880 Expr *varRef = new (Context) DeclRefExpr(var, type, VK_LValue, poi);
5881 ExprResult result =
5882 PerformCopyInitialization(
5883 InitializedEntity::InitializeBlock(poi, type, false),
5884 poi, Owned(varRef));
5885 if (!result.isInvalid()) {
5886 result = MaybeCreateExprWithCleanups(result);
5887 Expr *init = result.takeAs<Expr>();
5888 Context.setBlockVarCopyInits(var, init);
5889 }
5890 }
5891 }
5892
5893 // Check for global constructors.
5894 if (!var->getDeclContext()->isDependentContext() &&
5895 var->hasGlobalStorage() &&
5896 !var->isStaticLocal() &&
5897 var->getInit() &&
5898 !var->getInit()->isConstantInitializer(Context,
5899 baseType->isReferenceType()))
5900 Diag(var->getLocation(), diag::warn_global_constructor)
5901 << var->getInit()->getSourceRange();
5902
5903 // Require the destructor.
5904 if (const RecordType *recordType = baseType->getAs<RecordType>())
5905 FinalizeVarWithDestructor(var, recordType);
5906}
5907
Richard Smithb2bc2e62011-02-21 20:05:19 +00005908/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
5909/// any semantic actions necessary after any initializer has been attached.
5910void
5911Sema::FinalizeDeclaration(Decl *ThisDecl) {
5912 // Note that we are no longer parsing the initializer for this declaration.
5913 ParsingInitForAutoVars.erase(ThisDecl);
5914}
5915
John McCallba7bf592010-08-24 05:47:05 +00005916Sema::DeclGroupPtrTy
5917Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
5918 Decl **Group, unsigned NumDecls) {
Chris Lattner5bbb3c82009-03-29 16:50:03 +00005919 llvm::SmallVector<Decl*, 8> Decls;
Eli Friedman55b9ecb2009-05-29 01:49:24 +00005920
5921 if (DS.isTypeSpecOwned())
John McCallba7bf592010-08-24 05:47:05 +00005922 Decls.push_back(DS.getRepAsDecl());
Eli Friedman55b9ecb2009-05-29 01:49:24 +00005923
Richard Smith2abf6762011-02-23 00:37:57 +00005924 for (unsigned i = 0; i != NumDecls; ++i)
5925 if (Decl *D = Group[i])
5926 Decls.push_back(D);
5927
Chandler Carruth33bf3e72011-03-27 09:46:56 +00005928 return BuildDeclaratorGroup(Decls.data(), Decls.size(),
Richard Smith2abf6762011-02-23 00:37:57 +00005929 DS.getTypeSpecType() == DeclSpec::TST_auto);
5930}
5931
5932/// BuildDeclaratorGroup - convert a list of declarations into a declaration
5933/// group, performing any necessary semantic checking.
5934Sema::DeclGroupPtrTy
5935Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
5936 bool TypeMayContainAuto) {
Richard Smith30482bc2011-02-20 03:19:35 +00005937 // C++0x [dcl.spec.auto]p7:
5938 // If the type deduced for the template parameter U is not the same in each
5939 // deduction, the program is ill-formed.
5940 // FIXME: When initializer-list support is added, a distinction is needed
5941 // between the deduced type U and the deduced type which 'auto' stands for.
5942 // auto a = 0, b = { 1, 2, 3 };
5943 // is legal because the deduced type U is 'int' in both cases.
Richard Smith2abf6762011-02-23 00:37:57 +00005944 if (TypeMayContainAuto && NumDecls > 1) {
Richard Smith30482bc2011-02-20 03:19:35 +00005945 QualType Deduced;
5946 CanQualType DeducedCanon;
5947 VarDecl *DeducedDecl = 0;
5948 for (unsigned i = 0; i != NumDecls; ++i) {
5949 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
5950 AutoType *AT = D->getType()->getContainedAutoType();
Richard Smith2abf6762011-02-23 00:37:57 +00005951 // Don't reissue diagnostics when instantiating a template.
5952 if (AT && D->isInvalidDecl())
5953 break;
Richard Smith30482bc2011-02-20 03:19:35 +00005954 if (AT && AT->isDeduced()) {
5955 QualType U = AT->getDeducedType();
5956 CanQualType UCanon = Context.getCanonicalType(U);
5957 if (Deduced.isNull()) {
5958 Deduced = U;
5959 DeducedCanon = UCanon;
5960 DeducedDecl = D;
5961 } else if (DeducedCanon != UCanon) {
Richard Smith2abf6762011-02-23 00:37:57 +00005962 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
5963 diag::err_auto_different_deductions)
Richard Smith30482bc2011-02-20 03:19:35 +00005964 << Deduced << DeducedDecl->getDeclName()
5965 << U << D->getDeclName()
5966 << DeducedDecl->getInit()->getSourceRange()
5967 << D->getInit()->getSourceRange();
Richard Smith2abf6762011-02-23 00:37:57 +00005968 D->setInvalidDecl();
Richard Smith30482bc2011-02-20 03:19:35 +00005969 break;
5970 }
5971 }
5972 }
5973 }
5974 }
5975
Richard Smith2abf6762011-02-23 00:37:57 +00005976 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls));
Chris Lattner776fac82007-06-09 00:53:06 +00005977}
Steve Naroff7e6f7c22007-08-28 03:03:08 +00005978
Chris Lattner5bbb3c82009-03-29 16:50:03 +00005979
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005980/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
5981/// to introduce parameters into function prototype scope.
John McCall48871652010-08-21 09:40:31 +00005982Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattnercf31de32008-06-26 06:49:43 +00005983 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorad590502008-12-15 23:53:10 +00005984
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005985 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
John McCall8e7d6562010-08-26 03:08:43 +00005986 VarDecl::StorageClass StorageClass = SC_None;
5987 VarDecl::StorageClass StorageClassAsWritten = SC_None;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00005988 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
John McCall8e7d6562010-08-26 03:08:43 +00005989 StorageClass = SC_Register;
5990 StorageClassAsWritten = SC_Register;
Daniel Dunbar0ff41922008-09-03 21:54:21 +00005991 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005992 Diag(DS.getStorageClassSpecLoc(),
5993 diag::err_invalid_storage_class_in_func_decl);
Chris Lattnercf31de32008-06-26 06:49:43 +00005994 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00005995 }
Eli Friedmand5c0eed2009-04-19 20:27:55 +00005996
5997 if (D.getDeclSpec().isThreadSpecified())
5998 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
5999
Eli Friedman574c7452009-04-07 19:37:57 +00006000 DiagnoseFunctionSpecifiers(D);
6001
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00006002 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00006003 QualType parmDeclType = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00006004
Douglas Gregor27b4c162010-12-23 22:44:42 +00006005 if (getLangOptions().CPlusPlus) {
6006 // Check that there are no default arguments inside the type of this
6007 // parameter.
6008 CheckExtraCXXDefaultArguments(D);
Douglas Gregor27b4c162010-12-23 22:44:42 +00006009
6010 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
6011 if (D.getCXXScopeSpec().isSet()) {
6012 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
6013 << D.getCXXScopeSpec().getRange();
6014 D.getCXXScopeSpec().clear();
6015 }
Douglas Gregord6ab8742009-05-28 23:31:59 +00006016 }
6017
Alexis Hunta56cbcc2010-11-03 01:07:06 +00006018 // Ensure we have a valid name
6019 IdentifierInfo *II = 0;
6020 if (D.hasName()) {
6021 II = D.getIdentifier();
6022 if (!II) {
6023 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
6024 << GetNameForDeclarator(D).getName().getAsString();
6025 D.setInvalidType(true);
6026 }
6027 }
6028
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00006029 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
Chris Lattnerd9773512009-01-21 02:38:50 +00006030 if (II) {
John McCall84f02672010-03-18 06:42:38 +00006031 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
6032 ForRedeclaration);
6033 LookupName(R, S);
6034 if (R.isSingleResult()) {
6035 NamedDecl *PrevDecl = R.getFoundDecl();
Chris Lattnerd9773512009-01-21 02:38:50 +00006036 if (PrevDecl->isTemplateParameter()) {
6037 // Maybe we will complain about the shadowed template parameter.
6038 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
6039 // Just pretend that we didn't see the previous declaration.
6040 PrevDecl = 0;
John McCall48871652010-08-21 09:40:31 +00006041 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerd9773512009-01-21 02:38:50 +00006042 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattnerdd1cb5b2010-02-22 00:40:25 +00006043 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006044
Chris Lattnerd9773512009-01-21 02:38:50 +00006045 // Recover by removing the name
6046 II = 0;
6047 D.SetIdentifier(0, D.getIdentifierLoc());
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00006048 D.setInvalidType(true);
Chris Lattnerd9773512009-01-21 02:38:50 +00006049 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006050 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00006051 }
Steve Naroff773df5c2007-08-07 22:44:21 +00006052
John McCallf7b2fb52010-01-22 00:28:27 +00006053 // Temporarily put parameter variables in the translation unit, not
6054 // the enclosing context. This prevents them from accidentally
6055 // looking like class members in C++.
Douglas Gregor940bca72010-04-12 07:48:19 +00006056 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00006057 D.getSourceRange().getBegin(),
6058 D.getIdentifierLoc(), II,
6059 parmDeclType, TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00006060 StorageClass, StorageClassAsWritten);
Mike Stump11289f42009-09-09 15:08:12 +00006061
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006062 if (D.isInvalidType())
John McCall8fb0d9d2011-05-01 22:35:37 +00006063 New->setInvalidDecl();
6064
6065 assert(S->isFunctionPrototypeScope());
6066 assert(S->getFunctionPrototypeDepth() >= 1);
6067 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
6068 S->getNextFunctionPrototypeIndex());
Douglas Gregor940bca72010-04-12 07:48:19 +00006069
Douglas Gregor91f84212008-12-11 16:49:14 +00006070 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00006071 S->AddDecl(New);
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00006072 if (II)
Douglas Gregor91f84212008-12-11 16:49:14 +00006073 IdResolver.AddDecl(New);
Nate Begemand8c41562008-02-17 21:20:31 +00006074
Douglas Gregor758a8692009-06-17 21:51:59 +00006075 ProcessDeclAttributes(S, New, D);
Mike Stumpe9efa802009-04-30 00:19:40 +00006076
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006077 if (New->hasAttr<BlocksAttr>()) {
Mike Stumpe9efa802009-04-30 00:19:40 +00006078 Diag(New->getLocation(), diag::err_block_on_nonlocal);
6079 }
John McCall48871652010-08-21 09:40:31 +00006080 return New;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00006081}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +00006082
John McCalla3ccba02010-06-04 11:21:44 +00006083/// \brief Synthesizes a variable for a parameter arising from a
6084/// typedef.
6085ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
6086 SourceLocation Loc,
6087 QualType T) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00006088 /* FIXME: setting StartLoc == Loc.
6089 Would it be worth to modify callers so as to provide proper source
6090 location for the unnamed parameters, embedding the parameter's type? */
6091 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
John McCalla3ccba02010-06-04 11:21:44 +00006092 T, Context.getTrivialTypeSourceInfo(T, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00006093 SC_None, SC_None, 0);
John McCalla3ccba02010-06-04 11:21:44 +00006094 Param->setImplicit();
6095 return Param;
6096}
6097
John McCallc5990642010-08-24 09:05:15 +00006098void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
6099 ParmVarDecl * const *ParamEnd) {
John McCallc5990642010-08-24 09:05:15 +00006100 // Don't diagnose unused-parameter errors in template instantiations; we
6101 // will already have done so in the template itself.
6102 if (!ActiveTemplateInstantiations.empty())
6103 return;
6104
6105 for (; Param != ParamEnd; ++Param) {
6106 if (!(*Param)->isUsed() && (*Param)->getDeclName() &&
6107 !(*Param)->hasAttr<UnusedAttr>()) {
6108 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
6109 << (*Param)->getDeclName();
6110 }
6111 }
6112}
6113
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006114void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
6115 ParmVarDecl * const *ParamEnd,
6116 QualType ReturnTy,
6117 NamedDecl *D) {
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00006118 if (LangOpts.NumLargeByValueCopy == 0) // No check.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006119 return;
6120
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00006121 // Warn if the return value is pass-by-value and larger than the specified
6122 // threshold.
John McCall31168b02011-06-15 23:02:42 +00006123 if (ReturnTy.isPODType(Context)) {
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006124 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00006125 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006126 Diag(D->getLocation(), diag::warn_return_value_size)
6127 << D->getDeclName() << Size;
6128 }
6129
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00006130 // Warn if any parameter is pass-by-value and larger than the specified
6131 // threshold.
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006132 for (; Param != ParamEnd; ++Param) {
6133 QualType T = (*Param)->getType();
John McCall31168b02011-06-15 23:02:42 +00006134 if (!T.isPODType(Context))
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006135 continue;
6136 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
Argyrios Kyrtzidisef6c8da2010-11-18 00:20:36 +00006137 if (Size > LangOpts.NumLargeByValueCopy)
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006138 Diag((*Param)->getLocation(), diag::warn_parameter_size)
6139 << (*Param)->getDeclName() << Size;
6140 }
6141}
6142
Abramo Bagnaradff19302011-03-08 08:55:46 +00006143ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
6144 SourceLocation NameLoc, IdentifierInfo *Name,
6145 QualType T, TypeSourceInfo *TSInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00006146 VarDecl::StorageClass StorageClass,
6147 VarDecl::StorageClass StorageClassAsWritten) {
John McCall31168b02011-06-15 23:02:42 +00006148 // In ARC, infer a lifetime qualifier for appropriate parameter types.
6149 if (getLangOptions().ObjCAutoRefCount &&
6150 T.getObjCLifetime() == Qualifiers::OCL_None &&
6151 T->isObjCLifetimeType()) {
6152
6153 Qualifiers::ObjCLifetime lifetime;
6154
6155 // Special cases for arrays:
6156 // - if it's const, use __unsafe_unretained
6157 // - otherwise, it's an error
6158 if (T->isArrayType()) {
6159 if (!T.isConstQualified()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00006160 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
John McCall31168b02011-06-15 23:02:42 +00006161 << TSInfo->getTypeLoc().getSourceRange();
6162 }
6163 lifetime = Qualifiers::OCL_ExplicitNone;
6164 } else {
6165 lifetime = T->getObjCARCImplicitLifetime();
6166 }
6167 T = Context.getLifetimeQualifiedType(T, lifetime);
6168 }
6169
Abramo Bagnaradff19302011-03-08 08:55:46 +00006170 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
Douglas Gregor84280642011-07-12 04:42:08 +00006171 Context.getAdjustedParameterType(T),
6172 TSInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00006173 StorageClass, StorageClassAsWritten,
6174 0);
Douglas Gregor940bca72010-04-12 07:48:19 +00006175
6176 // Parameters can not be abstract class types.
6177 // For record types, this is done by the AbstractClassUsageDiagnoser once
6178 // the class has been completely parsed.
6179 if (!CurContext->isRecord() &&
6180 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
6181 AbstractParamType))
6182 New->setInvalidDecl();
6183
6184 // Parameter declarators cannot be interface types. All ObjC objects are
6185 // passed by reference.
John McCall8b07ec22010-05-15 11:32:37 +00006186 if (T->isObjCObjectType()) {
Douglas Gregor940bca72010-04-12 07:48:19 +00006187 Diag(NameLoc,
6188 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
6189 New->setInvalidDecl();
6190 }
6191
6192 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
6193 // duration shall not be qualified by an address-space qualifier."
6194 // Since all parameters have automatic store duration, they can not have
6195 // an address space.
6196 if (T.getAddressSpace() != 0) {
6197 Diag(NameLoc, diag::err_arg_with_address_space);
6198 New->setInvalidDecl();
6199 }
6200
6201 return New;
6202}
6203
Douglas Gregor170512f2009-04-01 23:51:29 +00006204void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
6205 SourceLocation LocAfterDecls) {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006206 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006207
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00006208 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
6209 // for a K&R function.
6210 if (!FTI.hasPrototype) {
Douglas Gregor862ffb12009-04-02 03:14:12 +00006211 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
6212 --i;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006213 if (FTI.ArgInfo[i].Param == 0) {
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00006214 llvm::SmallString<256> Code;
6215 llvm::raw_svector_ostream(Code) << " int "
Daniel Dunbar07d07852009-10-18 21:17:35 +00006216 << FTI.ArgInfo[i].Ident->getName()
Daniel Dunbar70e7ead2009-10-18 20:26:27 +00006217 << ";\n";
Chris Lattner4bd8dd82008-11-19 08:23:25 +00006218 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
Douglas Gregor170512f2009-04-01 23:51:29 +00006219 << FTI.ArgInfo[i].Ident
Douglas Gregora771f462010-03-31 17:46:05 +00006220 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
Douglas Gregor170512f2009-04-01 23:51:29 +00006221
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00006222 // Implicitly declare the argument as type 'int' for lack of a better
6223 // type.
John McCall084e83d2011-03-24 11:26:52 +00006224 AttributeFactory attrs;
6225 DeclSpec DS(attrs);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006226 const char* PrevSpec; // unused
John McCall49bfce42009-08-03 20:12:06 +00006227 unsigned DiagID; // unused
Mike Stump11289f42009-09-09 15:08:12 +00006228 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
John McCall49bfce42009-08-03 20:12:06 +00006229 PrevSpec, DiagID);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006230 Declarator ParamD(DS, Declarator::KNRTypeListContext);
6231 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregor9aa89042009-01-23 16:23:13 +00006232 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00006233 }
6234 }
Mike Stump11289f42009-09-09 15:08:12 +00006235 }
Douglas Gregor9aa89042009-01-23 16:23:13 +00006236}
6237
John McCall48871652010-08-21 09:40:31 +00006238Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
6239 Declarator &D) {
Douglas Gregor9aa89042009-01-23 16:23:13 +00006240 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006241 assert(D.isFunctionDeclarator() && "Not a function declarator!");
Douglas Gregorad590502008-12-15 23:53:10 +00006242 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +00006243
John McCall48871652010-08-21 09:40:31 +00006244 Decl *DP = HandleDeclarator(ParentScope, D,
6245 MultiTemplateParamsArg(*this),
6246 /*IsFunctionDefinition=*/true);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00006247 return ActOnStartOfFunctionDef(FnBodyScope, DP);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006248}
6249
Anders Carlsson31c7e882009-12-09 03:30:09 +00006250static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
6251 // Don't warn about invalid declarations.
6252 if (FD->isInvalidDecl())
6253 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00006254
Anders Carlsson31c7e882009-12-09 03:30:09 +00006255 // Or declarations that aren't global.
6256 if (!FD->isGlobal())
6257 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00006258
Anders Carlsson31c7e882009-12-09 03:30:09 +00006259 // Don't warn about C++ member functions.
6260 if (isa<CXXMethodDecl>(FD))
6261 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00006262
Anders Carlsson31c7e882009-12-09 03:30:09 +00006263 // Don't warn about 'main'.
6264 if (FD->isMain())
6265 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00006266
Anders Carlsson31c7e882009-12-09 03:30:09 +00006267 // Don't warn about inline functions.
John McCall30cd20a2011-03-22 07:16:37 +00006268 if (FD->isInlined())
Anders Carlsson31c7e882009-12-09 03:30:09 +00006269 return false;
Anders Carlssona0388252009-12-09 03:44:46 +00006270
6271 // Don't warn about function templates.
6272 if (FD->getDescribedFunctionTemplate())
6273 return false;
6274
6275 // Don't warn about function template specializations.
6276 if (FD->isFunctionTemplateSpecialization())
6277 return false;
6278
Anders Carlsson31c7e882009-12-09 03:30:09 +00006279 bool MissingPrototype = true;
6280 for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
6281 Prev; Prev = Prev->getPreviousDeclaration()) {
6282 // Ignore any declarations that occur in function or method
6283 // scope, because they aren't visible from the header.
6284 if (Prev->getDeclContext()->isFunctionOrMethod())
6285 continue;
6286
6287 MissingPrototype = !Prev->getType()->isFunctionProtoType();
6288 break;
6289 }
6290
6291 return MissingPrototype;
6292}
6293
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00006294void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) {
6295 // Don't complain if we're in GNU89 mode and the previous definition
6296 // was an extern inline function.
6297 const FunctionDecl *Definition;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00006298 if (FD->isDefined(Definition) &&
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00006299 !canRedefineFunction(Definition, getLangOptions())) {
6300 if (getLangOptions().GNUMode && Definition->isInlineSpecified() &&
6301 Definition->getStorageClass() == SC_Extern)
6302 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
6303 << FD->getDeclName() << getLangOptions().CPlusPlus;
6304 else
6305 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
6306 Diag(Definition->getLocation(), diag::note_previous_definition);
6307 }
6308}
6309
John McCall48871652010-08-21 09:40:31 +00006310Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
Anders Carlsson561f7932009-10-29 15:46:07 +00006311 // Clear the last template instantiation error context.
6312 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
6313
Douglas Gregor17a7c122009-06-24 00:54:41 +00006314 if (!D)
6315 return D;
Douglas Gregorc45a40a2009-08-22 00:34:47 +00006316 FunctionDecl *FD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00006317
John McCall48871652010-08-21 09:40:31 +00006318 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
Douglas Gregorc45a40a2009-08-22 00:34:47 +00006319 FD = FunTmpl->getTemplatedDecl();
6320 else
John McCall48871652010-08-21 09:40:31 +00006321 FD = cast<FunctionDecl>(D);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00006322
Douglas Gregor9a28e842010-03-01 23:15:13 +00006323 // Enter a new function scope
6324 PushFunctionScope();
Mike Stump11289f42009-09-09 15:08:12 +00006325
Douglas Gregorcad304ba2008-10-29 15:10:40 +00006326 // See if this is a redefinition.
Francois Pichetdcb3ebe2011-04-22 23:20:44 +00006327 if (!FD->isLateTemplateParsed())
6328 CheckForFunctionRedefinition(FD);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00006329
Douglas Gregor75a45ba2009-02-16 17:45:42 +00006330 // Builtin functions cannot be defined.
Douglas Gregor15fc9562009-09-12 00:22:50 +00006331 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregor7a0febe2009-02-17 16:03:01 +00006332 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00006333 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor7a0febe2009-02-17 16:03:01 +00006334 FD->setInvalidDecl();
6335 }
Douglas Gregor75a45ba2009-02-16 17:45:42 +00006336 }
6337
Eli Friedman9ad72442009-03-04 07:30:59 +00006338 // The return type of a function definition must be complete
Douglas Gregorac1fb652009-03-24 19:52:54 +00006339 // (C99 6.9.1p3, C++ [dcl.fct]p6).
6340 QualType ResultType = FD->getResultType();
6341 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
Chris Lattner0f94c5a2009-04-29 05:12:23 +00006342 !FD->isInvalidDecl() &&
Douglas Gregorac1fb652009-03-24 19:52:54 +00006343 RequireCompleteType(FD->getLocation(), ResultType,
6344 diag::err_func_def_incomplete_result))
Eli Friedman9ad72442009-03-04 07:30:59 +00006345 FD->setInvalidDecl();
Eli Friedman9ad72442009-03-04 07:30:59 +00006346
Douglas Gregorf1b876d2009-03-31 16:35:03 +00006347 // GNU warning -Wmissing-prototypes:
6348 // Warn if a global function is defined without a previous
6349 // prototype declaration. This warning is issued even if the
6350 // definition itself provides a prototype. The aim is to detect
6351 // global functions that fail to be declared in header files.
Anders Carlsson31c7e882009-12-09 03:30:09 +00006352 if (ShouldWarnAboutMissingPrototype(FD))
6353 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
Douglas Gregorf1b876d2009-03-31 16:35:03 +00006354
Douglas Gregor67da0d92009-05-15 17:59:04 +00006355 if (FnBodyScope)
6356 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00006357
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006358 // Check the validity of our function parameters
Douglas Gregorb524d902010-11-01 18:37:59 +00006359 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
6360 /*CheckParameterNames=*/true);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006361
6362 // Introduce our parameters into the function scope
6363 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
6364 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc72e6452009-01-09 18:51:29 +00006365 Param->setOwningFunction(FD);
6366
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006367 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00006368 if (Param->getIdentifier() && FnBodyScope) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00006369 CheckShadow(FnBodyScope, Param);
John McCalldf8b37c2010-03-22 09:20:08 +00006370
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00006371 PushOnScopeChains(Param, FnBodyScope);
John McCalldf8b37c2010-03-22 09:20:08 +00006372 }
Chris Lattnerf61c8a82007-01-21 19:04:43 +00006373 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00006374
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00006375 // Checking attributes of current function definition
6376 // dllimport attribute.
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006377 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
6378 if (DA && (!FD->getAttr<DLLExportAttr>())) {
6379 // dllimport attribute cannot be directly applied to definition.
Francois Pichet3096d202011-03-29 10:39:17 +00006380 // Microsoft accepts dllimport for functions defined within class scope.
6381 if (!DA->isInherited() &&
6382 !(LangOpts.Microsoft && FD->getLexicalDeclContext()->isRecord())) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00006383 Diag(FD->getLocation(),
6384 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
6385 << "dllimport";
6386 FD->setInvalidDecl();
John McCall48871652010-08-21 09:40:31 +00006387 return FD;
Ted Kremeneka3cfc4d2010-02-21 05:12:53 +00006388 }
6389
6390 // Visual C++ appears to not think this is an issue, so only issue
6391 // a warning when Microsoft extensions are disabled.
6392 if (!LangOpts.Microsoft) {
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00006393 // If a symbol previously declared dllimport is later defined, the
6394 // attribute is ignored in subsequent references, and a warning is
6395 // emitted.
6396 Diag(FD->getLocation(),
6397 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
Daniel Dunbar56df9772010-08-17 22:39:59 +00006398 << FD->getName() << "dllimport";
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00006399 }
6400 }
John McCall48871652010-08-21 09:40:31 +00006401 return FD;
Chris Lattnere168f762006-11-10 05:29:30 +00006402}
6403
Douglas Gregor6fd1b182010-05-15 06:01:05 +00006404/// \brief Given the set of return statements within a function body,
6405/// compute the variables that are subject to the named return value
6406/// optimization.
6407///
6408/// Each of the variables that is subject to the named return value
6409/// optimization will be marked as NRVO variables in the AST, and any
6410/// return statement that has a marked NRVO variable as its NRVO candidate can
6411/// use the named return value optimization.
6412///
6413/// This function applies a very simplistic algorithm for NRVO: if every return
6414/// statement in the function has the same NRVO candidate, that candidate is
6415/// the NRVO variable.
6416///
6417/// FIXME: Employ a smarter algorithm that accounts for multiple return
6418/// statements and the lifetimes of the NRVO candidates. We should be able to
6419/// find a maximal set of NRVO variables.
John McCallaab3e412010-08-25 08:40:02 +00006420static void ComputeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
6421 ReturnStmt **Returns = Scope->Returns.data();
6422
Douglas Gregor6fd1b182010-05-15 06:01:05 +00006423 const VarDecl *NRVOCandidate = 0;
John McCallaab3e412010-08-25 08:40:02 +00006424 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
Douglas Gregor6fd1b182010-05-15 06:01:05 +00006425 if (!Returns[I]->getNRVOCandidate())
6426 return;
6427
6428 if (!NRVOCandidate)
6429 NRVOCandidate = Returns[I]->getNRVOCandidate();
6430 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
6431 return;
6432 }
6433
6434 if (NRVOCandidate)
6435 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
6436}
6437
John McCallfaf5fb42010-08-26 23:41:50 +00006438Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
Douglas Gregor67da0d92009-05-15 17:59:04 +00006439 return ActOnFinishFunctionBody(D, move(BodyArg), false);
6440}
6441
John McCallb268a282010-08-23 23:25:46 +00006442Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
6443 bool IsInstantiation) {
Douglas Gregorc45a40a2009-08-22 00:34:47 +00006444 FunctionDecl *FD = 0;
6445 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
6446 if (FunTmpl)
6447 FD = FunTmpl->getTemplatedDecl();
6448 else
6449 FD = dyn_cast_or_null<FunctionDecl>(dcl);
6450
Ted Kremenek0b405322010-03-23 00:13:23 +00006451 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
Ted Kremenek1767a272011-02-23 01:51:48 +00006452 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
Ted Kremenek918fe842010-03-20 21:06:02 +00006453
Douglas Gregorc45a40a2009-08-22 00:34:47 +00006454 if (FD) {
Chris Lattner960cc522009-04-18 09:36:27 +00006455 FD->setBody(Body);
Ted Kremenek918fe842010-03-20 21:06:02 +00006456 if (FD->isMain()) {
Mike Stump8e79f992009-07-24 02:49:01 +00006457 // C and C++ allow for main to automagically return 0.
John McCallcaa19452009-07-28 01:00:58 +00006458 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
6459 FD->setHasImplicitReturnZero(true);
Ted Kremenek0b405322010-03-23 00:13:23 +00006460 WP.disableCheckFallThrough();
Douglas Gregor9824aec2011-07-11 15:24:01 +00006461 } else if (FD->hasAttr<NakedAttr>()) {
6462 // If the function is marked 'naked', don't complain about missing return
6463 // statements.
6464 WP.disableCheckFallThrough();
Ted Kremenek918fe842010-03-20 21:06:02 +00006465 }
Mike Stump11289f42009-09-09 15:08:12 +00006466
Francois Pichet3abc9b82011-05-11 02:14:46 +00006467 // MSVC permits the use of pure specifier (=0) on function definition,
6468 // defined at class scope, warn about this non standard construct.
6469 if (getLangOptions().Microsoft && FD->isPure())
6470 Diag(FD->getLocation(), diag::warn_pure_function_definition);
6471
Douglas Gregor88d292c2010-05-13 16:44:06 +00006472 if (!FD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006473 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006474 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
6475 FD->getResultType(), FD);
Douglas Gregor88d292c2010-05-13 16:44:06 +00006476
6477 // If this is a constructor, we need a vtable.
6478 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
6479 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
Douglas Gregor6fd1b182010-05-15 06:01:05 +00006480
John McCallaab3e412010-08-25 08:40:02 +00006481 ComputeNRVO(Body, getCurFunction());
Douglas Gregor88d292c2010-05-13 16:44:06 +00006482 }
6483
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00006484 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff542cd5d2008-07-25 17:57:26 +00006485 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattner1598a3a2009-02-16 19:27:54 +00006486 assert(MD == getCurMethodDecl() && "Method parsing confused");
Chris Lattner960cc522009-04-18 09:36:27 +00006487 MD->setBody(Body);
Argyrios Kyrtzidisd5756a62011-01-03 22:33:06 +00006488 if (Body)
6489 MD->setEndLoc(Body->getLocEnd());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006490 if (!MD->isInvalidDecl()) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006491 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
Argyrios Kyrtzidisaf84ec02010-11-17 23:11:54 +00006492 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
6493 MD->getResultType(), MD);
6494 }
Ted Kremenek5a201952009-02-07 01:47:29 +00006495 } else {
John McCall48871652010-08-21 09:40:31 +00006496 return 0;
Ted Kremenek5a201952009-02-07 01:47:29 +00006497 }
Douglas Gregor67da0d92009-05-15 17:59:04 +00006498
Chris Lattnere2473062007-05-28 06:28:18 +00006499 // Verify and clean out per-function state.
Douglas Gregor9a28e842010-03-01 23:15:13 +00006500 if (Body) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00006501 // C++ constructors that have function-try-blocks can't have return
6502 // statements in the handlers of that block. (C++ [except.handle]p14)
6503 // Verify this.
6504 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
6505 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
6506
Ted Kremenek918fe842010-03-20 21:06:02 +00006507 // Verify that that gotos and switch cases don't jump into scopes illegally.
6508 // Verify that that gotos and switch cases don't jump into scopes illegally.
John McCallaab3e412010-08-25 08:40:02 +00006509 if (getCurFunction()->NeedsScopeChecking() &&
John McCall58efb8e2010-05-20 07:13:26 +00006510 !dcl->isInvalidDecl() &&
John McCall31168b02011-06-15 23:02:42 +00006511 !hasAnyUnrecoverableErrorsInThisFunction())
Douglas Gregor9a28e842010-03-01 23:15:13 +00006512 DiagnoseInvalidJumps(Body);
Mike Stump11289f42009-09-09 15:08:12 +00006513
John McCalldeb646e2010-08-04 01:04:25 +00006514 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
6515 if (!Destructor->getParent()->isDependentType())
6516 CheckDestructor(Destructor);
6517
John McCalla6309952010-03-16 21:39:52 +00006518 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6519 Destructor->getParent());
John McCalldeb646e2010-08-04 01:04:25 +00006520 }
Douglas Gregor9a28e842010-03-01 23:15:13 +00006521
6522 // If any errors have occurred, clear out any temporaries that may have
6523 // been leftover. This ensures that these temporaries won't be picked up for
6524 // deletion in some later function.
Douglas Gregor550b98b2011-03-04 23:08:02 +00006525 if (PP.getDiagnostics().hasErrorOccurred() ||
John McCall31168b02011-06-15 23:02:42 +00006526 PP.getDiagnostics().getSuppressAllDiagnostics()) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00006527 ExprTemporaries.clear();
John McCall31168b02011-06-15 23:02:42 +00006528 ExprNeedsCleanups = false;
6529 } else if (!isa<FunctionTemplateDecl>(dcl)) {
Ted Kremenek918fe842010-03-20 21:06:02 +00006530 // Since the body is valid, issue any analysis-based warnings that are
6531 // enabled.
Ted Kremenek1767a272011-02-23 01:51:48 +00006532 ActivePolicy = &WP;
Ted Kremenek918fe842010-03-20 21:06:02 +00006533 }
6534
Douglas Gregor9a28e842010-03-01 23:15:13 +00006535 assert(ExprTemporaries.empty() && "Leftover temporaries in function");
John McCall31168b02011-06-15 23:02:42 +00006536 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
Douglas Gregor9a28e842010-03-01 23:15:13 +00006537 }
6538
John McCalle99d5f32010-03-25 22:08:03 +00006539 if (!IsInstantiation)
6540 PopDeclContext();
6541
Ted Kremenek1767a272011-02-23 01:51:48 +00006542 PopFunctionOrBlockScope(ActivePolicy, dcl);
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00006543
Douglas Gregora7e3ea32009-11-15 07:07:58 +00006544 // If any errors have occurred, clear out any temporaries that may have
6545 // been leftover. This ensures that these temporaries won't be picked up for
6546 // deletion in some later function.
John McCall31168b02011-06-15 23:02:42 +00006547 if (getDiagnostics().hasErrorOccurred()) {
Douglas Gregora7e3ea32009-11-15 07:07:58 +00006548 ExprTemporaries.clear();
John McCall31168b02011-06-15 23:02:42 +00006549 ExprNeedsCleanups = false;
6550 }
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00006551
John McCall48871652010-08-21 09:40:31 +00006552 return dcl;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +00006553}
6554
Chris Lattnerac18be92006-11-20 06:49:47 +00006555/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
6556/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Mike Stump11289f42009-09-09 15:08:12 +00006557NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00006558 IdentifierInfo &II, Scope *S) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00006559 // Before we produce a declaration for an implicitly defined
6560 // function, see whether there was a locally-scoped declaration of
6561 // this name as a function or variable. If so, use that
6562 // (non-visible) declaration, and complain about it.
6563 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
6564 = LocallyScopedExternalDecls.find(&II);
6565 if (Pos != LocallyScopedExternalDecls.end()) {
6566 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
6567 Diag(Pos->second->getLocation(), diag::note_previous_declaration);
6568 return Pos->second;
6569 }
6570
Chris Lattner00e26072008-05-05 21:18:06 +00006571 // Extension in C99. Legal in C90, but warn about it.
Daniel Dunbar07d07852009-10-18 21:17:35 +00006572 if (II.getName().startswith("__builtin_"))
Douglas Gregor56fbc372009-09-28 21:14:19 +00006573 Diag(Loc, diag::warn_builtin_unknown) << &II;
6574 else if (getLangOptions().C99)
Chris Lattner4bd8dd82008-11-19 08:23:25 +00006575 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner00e26072008-05-05 21:18:06 +00006576 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +00006577 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Mike Stump11289f42009-09-09 15:08:12 +00006578
Chris Lattnerac18be92006-11-20 06:49:47 +00006579 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +00006580 const char *Dummy;
John McCall084e83d2011-03-24 11:26:52 +00006581 AttributeFactory attrFactory;
6582 DeclSpec DS(attrFactory);
John McCall49bfce42009-08-03 20:12:06 +00006583 unsigned DiagID;
6584 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00006585 (void)Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +00006586 assert(!Error && "Error setting up implicit decl!");
Chris Lattnerac18be92006-11-20 06:49:47 +00006587 Declarator D(DS, Declarator::BlockContext);
John McCall084e83d2011-03-24 11:26:52 +00006588 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
Douglas Gregor54992352011-01-26 03:43:54 +00006589 0, 0, true, SourceLocation(),
Douglas Gregorad69e652011-07-13 21:47:47 +00006590 SourceLocation(),
Sebastian Redl802a4532011-03-05 22:42:13 +00006591 EST_None, SourceLocation(),
6592 0, 0, 0, 0, Loc, Loc, D),
John McCall084e83d2011-03-24 11:26:52 +00006593 DS.getAttributes(),
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006594 SourceLocation());
Chris Lattnerac18be92006-11-20 06:49:47 +00006595 D.SetIdentifier(&II, Loc);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00006596
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00006597 // Insert this function into translation-unit scope.
6598
6599 DeclContext *PrevDC = CurContext;
6600 CurContext = Context.getTranslationUnitDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006601
John McCall48871652010-08-21 09:40:31 +00006602 FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
Steve Naroff3913ea42008-04-04 14:32:09 +00006603 FD->setImplicit();
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00006604
6605 CurContext = PrevDC;
6606
Douglas Gregore711f702009-02-14 18:57:46 +00006607 AddKnownFunctionAttributes(FD);
6608
Steve Naroff3913ea42008-04-04 14:32:09 +00006609 return FD;
Chris Lattnerac18be92006-11-20 06:49:47 +00006610}
6611
Douglas Gregore711f702009-02-14 18:57:46 +00006612/// \brief Adds any function attributes that we know a priori based on
6613/// the declaration of this function.
6614///
6615/// These attributes can apply both to implicitly-declared builtins
6616/// (like __builtin___printf_chk) or to library-declared functions
6617/// like NSLog or printf.
Douglas Gregor88336832011-06-15 05:45:11 +00006618///
6619/// We need to check for duplicate attributes both here and where user-written
6620/// attributes are applied to declarations.
Douglas Gregore711f702009-02-14 18:57:46 +00006621void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
6622 if (FD->isInvalidDecl())
6623 return;
6624
6625 // If this is a built-in function, map its builtin attributes to
6626 // actual attributes.
Douglas Gregor15fc9562009-09-12 00:22:50 +00006627 if (unsigned BuiltinID = FD->getBuiltinID()) {
Douglas Gregore711f702009-02-14 18:57:46 +00006628 // Handle printf-formatting attributes.
6629 unsigned FormatIdx;
6630 bool HasVAListArg;
6631 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006632 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006633 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
6634 "printf", FormatIdx+1,
Ted Kremenek7f4945a2010-02-11 05:28:37 +00006635 HasVAListArg ? 0 : FormatIdx+2));
Douglas Gregore711f702009-02-14 18:57:46 +00006636 }
Ted Kremenek5932c352010-07-16 02:11:15 +00006637 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
6638 HasVAListArg)) {
6639 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006640 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
6641 "scanf", FormatIdx+1,
Ted Kremenek5932c352010-07-16 02:11:15 +00006642 HasVAListArg ? 0 : FormatIdx+2));
6643 }
Daniel Dunbar8eb018a2009-02-16 22:43:43 +00006644
6645 // Mark const if we don't care about errno and that is the only
6646 // thing preventing the function from being const. This allows
6647 // IRgen to use LLVM intrinsics for such functions.
6648 if (!getLangOptions().MathErrno &&
6649 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006650 if (!FD->getAttr<ConstAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006651 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Daniel Dunbar8eb018a2009-02-16 22:43:43 +00006652 }
Mike Stumpca6c8752009-07-27 19:14:18 +00006653
Douglas Gregor88336832011-06-15 05:45:11 +00006654 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006655 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
Douglas Gregor88336832011-06-15 05:45:11 +00006656 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006657 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
Douglas Gregore711f702009-02-14 18:57:46 +00006658 }
6659
6660 IdentifierInfo *Name = FD->getIdentifier();
6661 if (!Name)
6662 return;
Mike Stump11289f42009-09-09 15:08:12 +00006663 if ((!getLangOptions().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +00006664 FD->getDeclContext()->isTranslationUnit()) ||
6665 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +00006666 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
Douglas Gregore711f702009-02-14 18:57:46 +00006667 LinkageSpecDecl::lang_c)) {
6668 // Okay: this could be a libc/libm/Objective-C function we know
6669 // about.
6670 } else
6671 return;
6672
Douglas Gregorfedd4282009-04-22 20:56:09 +00006673 if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
Mike Stump82a9e442009-07-28 00:07:08 +00006674 // FIXME: NSLog and NSLogv should be target specific
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006675 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
Douglas Gregore711f702009-02-14 18:57:46 +00006676 // FIXME: We known better than our headers.
Ted Kremenek7f4945a2010-02-11 05:28:37 +00006677 const_cast<FormatAttr *>(Format)->setType(Context, "printf");
Mike Stump11289f42009-09-09 15:08:12 +00006678 } else
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006679 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
6680 "printf", 1,
Eli Friedmanf4799842009-06-10 04:01:38 +00006681 Name->isStr("NSLogv") ? 0 : 2));
Douglas Gregorfedd4282009-04-22 20:56:09 +00006682 } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
Mike Stump82a9e442009-07-28 00:07:08 +00006683 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
Mike Stump11289f42009-09-09 15:08:12 +00006684 // target-specific builtins, perhaps?
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006685 if (!FD->getAttr<FormatAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00006686 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
6687 "printf", 2,
Eli Friedmanf4799842009-06-10 04:01:38 +00006688 Name->isStr("vasprintf") ? 0 : 3));
Mike Stumpa4de80b2009-07-28 02:25:19 +00006689 }
Douglas Gregore711f702009-02-14 18:57:46 +00006690}
Chris Lattner302b4be2006-11-19 02:31:38 +00006691
John McCall703a3f82009-10-24 08:00:42 +00006692TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
John McCallbcd03502009-12-07 02:54:59 +00006693 TypeSourceInfo *TInfo) {
Chris Lattner776fac82007-06-09 00:53:06 +00006694 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +00006695 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Mike Stump11289f42009-09-09 15:08:12 +00006696
John McCallbcd03502009-12-07 02:54:59 +00006697 if (!TInfo) {
John McCall703a3f82009-10-24 08:00:42 +00006698 assert(D.isInvalidType() && "no declarator info for valid type");
John McCallbcd03502009-12-07 02:54:59 +00006699 TInfo = Context.getTrivialTypeSourceInfo(T);
John McCall703a3f82009-10-24 08:00:42 +00006700 }
6701
Chris Lattner18b19622007-01-22 07:39:13 +00006702 // Scope manipulation handled by caller.
Chris Lattnerc5ffed42008-04-04 06:12:32 +00006703 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00006704 D.getSourceRange().getBegin(),
Chris Lattnerc5ffed42008-04-04 06:12:32 +00006705 D.getIdentifierLoc(),
Mike Stump11289f42009-09-09 15:08:12 +00006706 D.getIdentifier(),
John McCallbcd03502009-12-07 02:54:59 +00006707 TInfo);
Mike Stump11289f42009-09-09 15:08:12 +00006708
John McCall04fcd0d2011-02-01 08:20:08 +00006709 // Bail out immediately if we have an invalid declaration.
6710 if (D.isInvalidType()) {
6711 NewTD->setInvalidDecl();
6712 return NewTD;
Anders Carlsson02751152009-03-10 17:07:44 +00006713 }
6714
John McCall04fcd0d2011-02-01 08:20:08 +00006715 // C++ [dcl.typedef]p8:
6716 // If the typedef declaration defines an unnamed class (or
6717 // enum), the first typedef-name declared by the declaration
6718 // to be that class type (or enum type) is used to denote the
6719 // class type (or enum type) for linkage purposes only.
6720 // We need to check whether the type was declared in the declaration.
6721 switch (D.getDeclSpec().getTypeSpecType()) {
6722 case TST_enum:
6723 case TST_struct:
6724 case TST_union:
6725 case TST_class: {
6726 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
6727
6728 // Do nothing if the tag is not anonymous or already has an
6729 // associated typedef (from an earlier typedef in this decl group).
6730 if (tagFromDeclSpec->getIdentifier()) break;
Richard Smithdda56e42011-04-15 14:24:37 +00006731 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
John McCall04fcd0d2011-02-01 08:20:08 +00006732
6733 // A well-formed anonymous tag must always be a TUK_Definition.
6734 assert(tagFromDeclSpec->isThisDeclarationADefinition());
6735
6736 // The type must match the tag exactly; no qualifiers allowed.
6737 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
6738 break;
6739
6740 // Otherwise, set this is the anon-decl typedef for the tag.
Richard Smithdda56e42011-04-15 14:24:37 +00006741 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
John McCall04fcd0d2011-02-01 08:20:08 +00006742 break;
6743 }
6744
6745 default:
6746 break;
6747 }
6748
Steve Narofff93b6722007-08-28 20:14:24 +00006749 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +00006750}
6751
Douglas Gregord9034f02009-05-14 16:41:31 +00006752
6753/// \brief Determine whether a tag with a given kind is acceptable
6754/// as a redeclaration of the given tag declaration.
6755///
6756/// \returns true if the new tag kind is acceptable, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00006757bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
Richard Trieucaa33d32011-06-10 03:11:26 +00006758 TagTypeKind NewTag, bool isDefinition,
Douglas Gregord9034f02009-05-14 16:41:31 +00006759 SourceLocation NewTagLoc,
6760 const IdentifierInfo &Name) {
6761 // C++ [dcl.type.elab]p3:
6762 // The class-key or enum keyword present in the
6763 // elaborated-type-specifier shall agree in kind with the
Abramo Bagnara6150c882010-05-11 21:36:43 +00006764 // declaration to which the name in the elaborated-type-specifier
Douglas Gregord9034f02009-05-14 16:41:31 +00006765 // refers. This rule also applies to the form of
6766 // elaborated-type-specifier that declares a class-name or
6767 // friend class since it can be construed as referring to the
6768 // definition of the class. Thus, in any
6769 // elaborated-type-specifier, the enum keyword shall be used to
Abramo Bagnara6150c882010-05-11 21:36:43 +00006770 // refer to an enumeration (7.2), the union class-key shall be
Douglas Gregord9034f02009-05-14 16:41:31 +00006771 // used to refer to a union (clause 9), and either the class or
6772 // struct class-key shall be used to refer to a class (clause 9)
6773 // declared using the class or struct class-key.
Abramo Bagnara6150c882010-05-11 21:36:43 +00006774 TagTypeKind OldTag = Previous->getTagKind();
Richard Trieucaa33d32011-06-10 03:11:26 +00006775 if (!isDefinition || (NewTag != TTK_Class && NewTag != TTK_Struct))
6776 if (OldTag == NewTag)
6777 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006778
Abramo Bagnara6150c882010-05-11 21:36:43 +00006779 if ((OldTag == TTK_Struct || OldTag == TTK_Class) &&
6780 (NewTag == TTK_Struct || NewTag == TTK_Class)) {
Douglas Gregord9034f02009-05-14 16:41:31 +00006781 // Warn about the struct/class tag mismatch.
6782 bool isTemplate = false;
6783 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
6784 isTemplate = Record->getDescribedClassTemplate();
6785
Richard Trieucaa33d32011-06-10 03:11:26 +00006786 if (!ActiveTemplateInstantiations.empty()) {
6787 // In a template instantiation, do not offer fix-its for tag mismatches
6788 // since they usually mess up the template instead of fixing the problem.
6789 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
6790 << (NewTag == TTK_Class) << isTemplate << &Name;
6791 return true;
6792 }
6793
6794 if (isDefinition) {
6795 // On definitions, check previous tags and issue a fix-it for each
6796 // one that doesn't match the current tag.
6797 if (Previous->getDefinition()) {
6798 // Don't suggest fix-its for redefinitions.
6799 return true;
6800 }
6801
6802 bool previousMismatch = false;
6803 for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
6804 E(Previous->redecls_end()); I != E; ++I) {
6805 if (I->getTagKind() != NewTag) {
6806 if (!previousMismatch) {
6807 previousMismatch = true;
6808 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
6809 << (NewTag == TTK_Class) << isTemplate << &Name;
6810 }
6811 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
6812 << (NewTag == TTK_Class)
6813 << FixItHint::CreateReplacement(I->getInnerLocStart(),
6814 NewTag == TTK_Class?
6815 "class" : "struct");
6816 }
6817 }
6818 return true;
6819 }
6820
6821 // Check for a previous definition. If current tag and definition
6822 // are same type, do nothing. If no definition, but disagree with
6823 // with previous tag type, give a warning, but no fix-it.
6824 const TagDecl *Redecl = Previous->getDefinition() ?
6825 Previous->getDefinition() : Previous;
6826 if (Redecl->getTagKind() == NewTag) {
6827 return true;
6828 }
6829
Douglas Gregord9034f02009-05-14 16:41:31 +00006830 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
Abramo Bagnara6150c882010-05-11 21:36:43 +00006831 << (NewTag == TTK_Class)
Richard Trieucaa33d32011-06-10 03:11:26 +00006832 << isTemplate << &Name;
6833 Diag(Redecl->getLocation(), diag::note_previous_use);
6834
6835 // If there is a previous defintion, suggest a fix-it.
6836 if (Previous->getDefinition()) {
6837 Diag(NewTagLoc, diag::note_struct_class_suggestion)
6838 << (Redecl->getTagKind() == TTK_Class)
6839 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
6840 Redecl->getTagKind() == TTK_Class? "class" : "struct");
6841 }
6842
Douglas Gregord9034f02009-05-14 16:41:31 +00006843 return true;
6844 }
6845 return false;
6846}
6847
Steve Naroff30d242c2007-09-15 18:49:24 +00006848/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +00006849/// former case, Name will be non-null. In the later case, Name will be null.
John McCall9bb74a52009-07-31 02:45:11 +00006850/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
Chris Lattner1300fb92007-01-23 23:42:53 +00006851/// reference/declaration/definition of a tag.
John McCall48871652010-08-21 09:40:31 +00006852Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
Douglas Gregor009f6992010-09-16 23:58:57 +00006853 SourceLocation KWLoc, CXXScopeSpec &SS,
6854 IdentifierInfo *Name, SourceLocation NameLoc,
6855 AttributeList *Attr, AccessSpecifier AS,
6856 MultiTemplateParamsArg TemplateParameterLists,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00006857 bool &OwnedDecl, bool &IsDependent,
6858 bool ScopedEnum, bool ScopedEnumUsesClassTag,
Douglas Gregor0bf31402010-10-08 23:50:27 +00006859 TypeResult UnderlyingType) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +00006860 // If this is not a definition, it must have a name.
John McCall9bb74a52009-07-31 02:45:11 +00006861 assert((Name != 0 || TUK == TUK_Definition) &&
Chris Lattner7b9ace62007-01-23 20:11:08 +00006862 "Nameless record must be a definition!");
John McCallace48cd2010-10-19 01:40:49 +00006863 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
Douglas Gregorded2d7b2009-02-04 19:02:06 +00006864
Douglas Gregord6ab8742009-05-28 23:31:59 +00006865 OwnedDecl = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +00006866 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00006867
Douglas Gregor5c0405d2009-10-07 22:35:40 +00006868 // FIXME: Check explicit specializations more carefully.
6869 bool isExplicitSpecialization = false;
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006870 bool Invalid = false;
John McCallace48cd2010-10-19 01:40:49 +00006871
6872 // We only need to do this matching if we have template parameters
6873 // or a scope specifier, which also conveniently avoids this work
6874 // for non-C++ cases.
Abramo Bagnara60804e12011-03-18 15:16:37 +00006875 if (TemplateParameterLists.size() > 0 ||
John McCallace48cd2010-10-19 01:40:49 +00006876 (SS.isNotEmpty() && TUK != TUK_Reference)) {
Douglas Gregore93e46c2009-07-22 23:48:44 +00006877 if (TemplateParameterList *TemplateParams
Douglas Gregor972fe532011-05-10 18:27:06 +00006878 = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS,
John McCallc9739e32010-10-16 07:23:36 +00006879 TemplateParameterLists.get(),
Abramo Bagnara60804e12011-03-18 15:16:37 +00006880 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00006881 TUK == TUK_Friend,
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006882 isExplicitSpecialization,
6883 Invalid)) {
Douglas Gregor3dad8422009-09-26 06:47:28 +00006884 if (TemplateParams->size() > 0) {
Douglas Gregore93e46c2009-07-22 23:48:44 +00006885 // This is a declaration or definition of a class template (which may
6886 // be a member of another template).
Abramo Bagnara60804e12011-03-18 15:16:37 +00006887
Douglas Gregor5f0e2522010-07-14 23:14:12 +00006888 if (Invalid)
John McCall48871652010-08-21 09:40:31 +00006889 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00006890
Douglas Gregore93e46c2009-07-22 23:48:44 +00006891 OwnedDecl = false;
John McCall9bb74a52009-07-31 02:45:11 +00006892 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +00006893 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00006894 TemplateParams, AS,
Abramo Bagnara60804e12011-03-18 15:16:37 +00006895 TemplateParameterLists.size() - 1,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00006896 (TemplateParameterList**) TemplateParameterLists.release());
Douglas Gregore93e46c2009-07-22 23:48:44 +00006897 return Result.get();
6898 } else {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006899 // The "template<>" header is extraneous.
6900 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
Abramo Bagnara6150c882010-05-11 21:36:43 +00006901 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Douglas Gregorbbe8f462009-10-08 15:14:33 +00006902 isExplicitSpecialization = true;
Douglas Gregore93e46c2009-07-22 23:48:44 +00006903 }
Mike Stump11289f42009-09-09 15:08:12 +00006904 }
6905 }
6906
Douglas Gregor0bf31402010-10-08 23:50:27 +00006907 // Figure out the underlying type if this a enum declaration. We need to do
6908 // this early, because it's needed to detect if this is an incompatible
6909 // redeclaration.
6910 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
6911
6912 if (Kind == TTK_Enum) {
6913 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
6914 // No underlying type explicitly specified, or we failed to parse the
6915 // type, default to int.
6916 EnumUnderlying = Context.IntTy.getTypePtr();
6917 else if (UnderlyingType.get()) {
6918 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
6919 // integral type; any cv-qualification is ignored.
6920 TypeSourceInfo *TI = 0;
6921 QualType T = GetTypeFromParser(UnderlyingType.get(), &TI);
6922 EnumUnderlying = TI;
6923
6924 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
6925
6926 if (!T->isDependentType() && !T->isIntegralType(Context)) {
6927 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
6928 << T;
6929 // Recover by falling back to int.
6930 EnumUnderlying = Context.IntTy.getTypePtr();
6931 }
Douglas Gregor2b988fd2010-12-16 00:24:44 +00006932
6933 if (DiagnoseUnexpandedParameterPack(UnderlyingLoc, TI,
6934 UPPC_FixedUnderlyingType))
6935 EnumUnderlying = Context.IntTy.getTypePtr();
6936
Francois Picheta3108062010-10-18 15:01:13 +00006937 } else if (getLangOptions().Microsoft)
6938 // Microsoft enums are always of int type.
6939 EnumUnderlying = Context.IntTy.getTypePtr();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006940 }
6941
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00006942 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00006943 DeclContext *DC = CurContext;
Douglas Gregor87f54062009-09-15 22:30:29 +00006944 bool isStdBadAlloc = false;
Douglas Gregordee1be82009-01-17 00:42:38 +00006945
Chandler Carrutha419dbb2010-03-01 21:17:36 +00006946 RedeclarationKind Redecl = ForRedeclaration;
6947 if (TUK == TUK_Friend || TUK == TUK_Reference)
6948 Redecl = NotForRedeclaration;
John McCall1f82f242009-11-18 22:49:29 +00006949
6950 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
John McCall6538c932009-10-10 05:48:19 +00006951
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00006952 if (Name && SS.isNotEmpty()) {
6953 // We have a nested-name tag ('struct foo::bar').
6954
6955 // Check for invalid 'foo::'.
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00006956 if (SS.isInvalid()) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00006957 Name = 0;
6958 goto CreateNewDecl;
6959 }
6960
John McCall7f41d982009-09-11 04:59:25 +00006961 // If this is a friend or a reference to a class in a dependent
6962 // context, don't try to make a decl for it.
6963 if (TUK == TUK_Friend || TUK == TUK_Reference) {
6964 DC = computeDeclContext(SS, false);
6965 if (!DC) {
6966 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +00006967 return 0;
John McCall7f41d982009-09-11 04:59:25 +00006968 }
John McCall0b66eb32010-05-01 00:40:08 +00006969 } else {
6970 DC = computeDeclContext(SS, true);
6971 if (!DC) {
6972 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
6973 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00006974 return 0;
John McCall0b66eb32010-05-01 00:40:08 +00006975 }
John McCall7f41d982009-09-11 04:59:25 +00006976 }
6977
John McCall0b66eb32010-05-01 00:40:08 +00006978 if (RequireCompleteDeclContext(SS, DC))
John McCall48871652010-08-21 09:40:31 +00006979 return 0;
Douglas Gregor2ec748c2009-05-14 00:28:11 +00006980
Douglas Gregor8761da52009-02-03 00:34:39 +00006981 SearchDC = DC;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00006982 // Look-up name inside 'foo::'.
John McCall1f82f242009-11-18 22:49:29 +00006983 LookupQualifiedName(Previous, DC);
John McCall6538c932009-10-10 05:48:19 +00006984
John McCall1f82f242009-11-18 22:49:29 +00006985 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006986 return 0;
John McCall6538c932009-10-10 05:48:19 +00006987
John McCall1f82f242009-11-18 22:49:29 +00006988 if (Previous.empty()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00006989 // Name lookup did not find anything. However, if the
6990 // nested-name-specifier refers to the current instantiation,
6991 // and that current instantiation has any dependent base
6992 // classes, we might find something at instantiation time: treat
6993 // this as a dependent elaborated-type-specifier.
John McCallace48cd2010-10-19 01:40:49 +00006994 // But this only makes any sense for reference-like lookups.
6995 if (Previous.wasNotFoundInCurrentInstantiation() &&
6996 (TUK == TUK_Reference || TUK == TUK_Friend)) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00006997 IsDependent = true;
John McCall48871652010-08-21 09:40:31 +00006998 return 0;
Douglas Gregord2e6a452010-01-14 17:47:39 +00006999 }
7000
7001 // A tag 'foo::bar' must already exist.
Douglas Gregorf5af3582010-03-31 23:17:41 +00007002 Diag(NameLoc, diag::err_not_tag_in_scope)
7003 << Kind << Name << DC << SS.getRange();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00007004 Name = 0;
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007005 Invalid = true;
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00007006 goto CreateNewDecl;
7007 }
Chris Lattnerd9773512009-01-21 02:38:50 +00007008 } else if (Name) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00007009 // If this is a named struct, check to see if there was a previous forward
7010 // declaration or definition.
Douglas Gregor889ceb72009-02-03 19:21:40 +00007011 // FIXME: We're looking into outer scopes here, even when we
7012 // shouldn't be. Doing so can result in ambiguities that we
7013 // shouldn't be diagnosing.
John McCall1f82f242009-11-18 22:49:29 +00007014 LookupName(Previous, S);
7015
Douglas Gregor5d1d9e32011-05-09 21:46:33 +00007016 if (Previous.isAmbiguous() &&
7017 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
Douglas Gregored8a29b2011-05-04 00:25:33 +00007018 LookupResult::Filter F = Previous.makeFilter();
7019 while (F.hasNext()) {
7020 NamedDecl *ND = F.next();
7021 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
7022 F.erase();
7023 }
7024 F.done();
Douglas Gregored8a29b2011-05-04 00:25:33 +00007025 }
7026
John McCall1f82f242009-11-18 22:49:29 +00007027 // Note: there used to be some attempt at recovery here.
7028 if (Previous.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00007029 return 0;
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007030
John McCall9bb74a52009-07-31 02:45:11 +00007031 if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007032 // FIXME: This makes sure that we ignore the contexts associated
7033 // with C structs, unions, and enums when looking for a matching
7034 // tag declaration or definition. See the similar lookup tweak
Douglas Gregored8f2882009-01-30 01:04:22 +00007035 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00007036 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
7037 SearchDC = SearchDC->getParent();
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007038 }
Douglas Gregor009f6992010-09-16 23:58:57 +00007039 } else if (S->isFunctionPrototypeScope()) {
7040 // If this is an enum declaration in function prototype scope, set its
7041 // initial context to the translation unit.
7042 SearchDC = Context.getTranslationUnitDecl();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00007043 }
7044
John McCall1f82f242009-11-18 22:49:29 +00007045 if (Previous.isSingleResult() &&
7046 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00007047 // Maybe we will complain about the shadowed template parameter.
John McCall1f82f242009-11-18 22:49:29 +00007048 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
Douglas Gregor5101c242008-12-05 18:15:24 +00007049 // Just pretend that we didn't see the previous declaration.
John McCall1f82f242009-11-18 22:49:29 +00007050 Previous.clear();
Douglas Gregor5101c242008-12-05 18:15:24 +00007051 }
7052
Douglas Gregor87f54062009-09-15 22:30:29 +00007053 if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007054 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
Douglas Gregor87f54062009-09-15 22:30:29 +00007055 // This is a declaration of or a reference to "std::bad_alloc".
7056 isStdBadAlloc = true;
7057
John McCall1f82f242009-11-18 22:49:29 +00007058 if (Previous.empty() && StdBadAlloc) {
Douglas Gregor87f54062009-09-15 22:30:29 +00007059 // std::bad_alloc has been implicitly declared (but made invisible to
7060 // name lookup). Fill in this implicit declaration as the previous
7061 // declaration, so that the declarations get chained appropriately.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007062 Previous.addDecl(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +00007063 }
7064 }
John McCall1f82f242009-11-18 22:49:29 +00007065
John McCalle9eaf8e2010-03-25 21:28:06 +00007066 // If we didn't find a previous declaration, and this is a reference
7067 // (or friend reference), move to the correct scope. In C++, we
7068 // also need to do a redeclaration lookup there, just in case
7069 // there's a shadow friend decl.
7070 if (Name && Previous.empty() &&
7071 (TUK == TUK_Reference || TUK == TUK_Friend)) {
7072 if (Invalid) goto CreateNewDecl;
7073 assert(SS.isEmpty());
7074
7075 if (TUK == TUK_Reference) {
7076 // C++ [basic.scope.pdecl]p5:
7077 // -- for an elaborated-type-specifier of the form
7078 //
7079 // class-key identifier
7080 //
7081 // if the elaborated-type-specifier is used in the
7082 // decl-specifier-seq or parameter-declaration-clause of a
7083 // function defined in namespace scope, the identifier is
7084 // declared as a class-name in the namespace that contains
7085 // the declaration; otherwise, except as a friend
7086 // declaration, the identifier is declared in the smallest
7087 // non-class, non-function-prototype scope that contains the
7088 // declaration.
7089 //
7090 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
7091 // C structs and unions.
7092 //
7093 // It is an error in C++ to declare (rather than define) an enum
7094 // type, including via an elaborated type specifier. We'll
7095 // diagnose that later; for now, declare the enum in the same
7096 // scope as we would have picked for any other tag type.
7097 //
7098 // GNU C also supports this behavior as part of its incomplete
7099 // enum types extension, while GNU C++ does not.
7100 //
7101 // Find the context where we'll be declaring the tag.
7102 // FIXME: We would like to maintain the current DeclContext as the
7103 // lexical context,
Rafael Espindola9e976dc2011-01-20 02:26:24 +00007104 while (SearchDC->isRecord() || SearchDC->isTransparentContext())
John McCalle9eaf8e2010-03-25 21:28:06 +00007105 SearchDC = SearchDC->getParent();
7106
7107 // Find the scope where we'll be declaring the tag.
7108 while (S->isClassScope() ||
7109 (getLangOptions().CPlusPlus &&
7110 S->isFunctionPrototypeScope()) ||
7111 ((S->getFlags() & Scope::DeclScope) == 0) ||
7112 (S->getEntity() &&
7113 ((DeclContext *)S->getEntity())->isTransparentContext()))
7114 S = S->getParent();
7115 } else {
7116 assert(TUK == TUK_Friend);
7117 // C++ [namespace.memdef]p3:
7118 // If a friend declaration in a non-local class first declares a
7119 // class or function, the friend class or function is a member of
7120 // the innermost enclosing namespace.
7121 SearchDC = SearchDC->getEnclosingNamespaceContext();
John McCalle9eaf8e2010-03-25 21:28:06 +00007122 }
7123
John McCalle87beb22010-04-23 18:46:30 +00007124 // In C++, we need to do a redeclaration lookup to properly
7125 // diagnose some problems.
John McCalle9eaf8e2010-03-25 21:28:06 +00007126 if (getLangOptions().CPlusPlus) {
7127 Previous.setRedeclarationKind(ForRedeclaration);
7128 LookupQualifiedName(Previous, SearchDC);
7129 }
7130 }
7131
John McCall1f82f242009-11-18 22:49:29 +00007132 if (!Previous.empty()) {
Douglas Gregorce40e2e2010-04-12 16:00:01 +00007133 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
John McCalle87beb22010-04-23 18:46:30 +00007134
7135 // It's okay to have a tag decl in the same scope as a typedef
7136 // which hides a tag decl in the same scope. Finding this
7137 // insanity with a redeclaration lookup can only actually happen
7138 // in C++.
7139 //
7140 // This is also okay for elaborated-type-specifiers, which is
7141 // technically forbidden by the current standard but which is
7142 // okay according to the likely resolution of an open issue;
7143 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
7144 if (getLangOptions().CPlusPlus) {
Richard Smithdda56e42011-04-15 14:24:37 +00007145 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
John McCalle87beb22010-04-23 18:46:30 +00007146 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
7147 TagDecl *Tag = TT->getDecl();
7148 if (Tag->getDeclName() == Name &&
Sebastian Redl50c68252010-08-31 00:36:30 +00007149 Tag->getDeclContext()->getRedeclContext()
7150 ->Equals(TD->getDeclContext()->getRedeclContext())) {
John McCalle87beb22010-04-23 18:46:30 +00007151 PrevDecl = Tag;
7152 Previous.clear();
7153 Previous.addDecl(Tag);
Douglas Gregorfcee9462010-08-27 22:55:10 +00007154 Previous.resolveKind();
John McCalle87beb22010-04-23 18:46:30 +00007155 }
7156 }
7157 }
7158 }
7159
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007160 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +00007161 // If this is a use of a previous tag, or if the tag is already declared
7162 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007163 // rementions the tag), reuse the decl.
John McCall07e91c02009-08-06 02:15:43 +00007164 if (TUK == TUK_Reference || TUK == TUK_Friend ||
Douglas Gregordb446112011-03-07 16:54:27 +00007165 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +00007166 // Make sure that this wasn't declared as an enum and now used as a
7167 // struct or something similar.
Richard Trieucaa33d32011-06-10 03:11:26 +00007168 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
7169 TUK == TUK_Definition, KWLoc,
7170 *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +00007171 bool SafeToContinue
Abramo Bagnara6150c882010-05-11 21:36:43 +00007172 = (PrevTagDecl->getTagKind() != TTK_Enum &&
7173 Kind != TTK_Enum);
Douglas Gregor170512f2009-04-01 23:51:29 +00007174 if (SafeToContinue)
Mike Stump11289f42009-09-09 15:08:12 +00007175 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00007176 << Name
Douglas Gregora771f462010-03-31 17:46:05 +00007177 << FixItHint::CreateReplacement(SourceRange(KWLoc),
7178 PrevTagDecl->getKindName());
Douglas Gregor170512f2009-04-01 23:51:29 +00007179 else
7180 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
John McCall1f82f242009-11-18 22:49:29 +00007181 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +00007182
Mike Stump11289f42009-09-09 15:08:12 +00007183 if (SafeToContinue)
Douglas Gregor170512f2009-04-01 23:51:29 +00007184 Kind = PrevTagDecl->getTagKind();
7185 else {
7186 // Recover by making this an anonymous redefinition.
7187 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00007188 Previous.clear();
Douglas Gregor170512f2009-04-01 23:51:29 +00007189 Invalid = true;
7190 }
7191 }
7192
Douglas Gregor0bf31402010-10-08 23:50:27 +00007193 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
7194 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
7195
7196 // All conflicts with previous declarations are recovered by
7197 // returning the previous declaration.
7198 if (ScopedEnum != PrevEnum->isScoped()) {
7199 Diag(KWLoc, diag::err_enum_redeclare_scoped_mismatch)
7200 << PrevEnum->isScoped();
7201 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
7202 return PrevTagDecl;
7203 }
7204 else if (EnumUnderlying && PrevEnum->isFixed()) {
7205 QualType T;
7206 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
7207 T = TI->getType();
7208 else
7209 T = QualType(EnumUnderlying.get<const Type*>(), 0);
7210
7211 if (!Context.hasSameUnqualifiedType(T, PrevEnum->getIntegerType())) {
Douglas Gregor1a099ba2010-12-01 16:10:38 +00007212 Diag(NameLoc.isValid() ? NameLoc : KWLoc,
7213 diag::err_enum_redeclare_type_mismatch)
7214 << T
7215 << PrevEnum->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00007216 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
7217 return PrevTagDecl;
7218 }
7219 }
7220 else if (!EnumUnderlying.isNull() != PrevEnum->isFixed()) {
7221 Diag(KWLoc, diag::err_enum_redeclare_fixed_mismatch)
7222 << PrevEnum->isFixed();
7223 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
7224 return PrevTagDecl;
7225 }
7226 }
7227
Douglas Gregor170512f2009-04-01 23:51:29 +00007228 if (!Invalid) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007229 // If this is a use, just return the declaration we found.
Chris Lattner9ff58d72008-07-03 03:30:58 +00007230
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007231 // FIXME: In the future, return a variant or some other clue
7232 // for the consumer of this Decl to know it doesn't own it.
7233 // For our current ASTs this shouldn't be a problem, but will
7234 // need to be changed with DeclGroups.
Francois Pichete37eeba2011-06-01 04:14:20 +00007235 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
7236 getLangOptions().Microsoft)) || TUK == TUK_Friend)
John McCall48871652010-08-21 09:40:31 +00007237 return PrevTagDecl;
Douglas Gregorded2d7b2009-02-04 19:02:06 +00007238
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007239 // Diagnose attempts to redefine a tag.
John McCall9bb74a52009-07-31 02:45:11 +00007240 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00007241 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00007242 // If we're defining a specialization and the previous definition
7243 // is from an implicit instantiation, don't emit an error
7244 // here; we'll catch this in the general case below.
7245 if (!isExplicitSpecialization ||
7246 !isa<CXXRecordDecl>(Def) ||
7247 cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
7248 == TSK_ExplicitSpecialization) {
7249 Diag(NameLoc, diag::err_redefinition) << Name;
7250 Diag(Def->getLocation(), diag::note_previous_definition);
7251 // If this is a redefinition, recover by making this
7252 // struct be anonymous, which will make any later
7253 // references get the previous definition.
7254 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00007255 Previous.clear();
Douglas Gregor06db9f52009-10-12 20:18:28 +00007256 Invalid = true;
7257 }
Douglas Gregordee1be82009-01-17 00:42:38 +00007258 } else {
7259 // If the type is currently being defined, complain
7260 // about a nested redefinition.
John McCall424cec92011-01-19 06:33:43 +00007261 const TagType *Tag
7262 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
Douglas Gregordee1be82009-01-17 00:42:38 +00007263 if (Tag->isBeingDefined()) {
7264 Diag(NameLoc, diag::err_nested_redefinition) << Name;
Mike Stump11289f42009-09-09 15:08:12 +00007265 Diag(PrevTagDecl->getLocation(),
Douglas Gregordee1be82009-01-17 00:42:38 +00007266 diag::note_previous_definition);
7267 Name = 0;
John McCall1f82f242009-11-18 22:49:29 +00007268 Previous.clear();
Douglas Gregordee1be82009-01-17 00:42:38 +00007269 Invalid = true;
7270 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007271 }
Douglas Gregordee1be82009-01-17 00:42:38 +00007272
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007273 // Okay, this is definition of a previously declared or referenced
7274 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregordee1be82009-01-17 00:42:38 +00007275 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007276 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007277 // If we get here we have (another) forward declaration or we
John McCall07e91c02009-08-06 02:15:43 +00007278 // have a definition. Just create a new decl.
7279
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007280 } else {
7281 // If we get here, this is a definition of a new tag type in a nested
Mike Stump11289f42009-09-09 15:08:12 +00007282 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007283 // new decl/type. We set PrevDecl to NULL so that the entities
7284 // have distinct types.
John McCall1f82f242009-11-18 22:49:29 +00007285 Previous.clear();
Chris Lattner7b9ace62007-01-23 20:11:08 +00007286 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007287 // If we get here, we're going to create a new Decl. If PrevDecl
7288 // is non-NULL, it's a definition of the tag declared by
7289 // PrevDecl. If it's NULL, we have a new definition.
John McCalle87beb22010-04-23 18:46:30 +00007290
7291
7292 // Otherwise, PrevDecl is not a tag, but was found with tag
7293 // lookup. This is only actually possible in C++, where a few
7294 // things like templates still live in the tag namespace.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007295 } else {
John McCalle87beb22010-04-23 18:46:30 +00007296 assert(getLangOptions().CPlusPlus);
7297
7298 // Use a better diagnostic if an elaborated-type-specifier
7299 // found the wrong kind of type on the first
7300 // (non-redeclaration) lookup.
7301 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
7302 !Previous.isForRedeclaration()) {
7303 unsigned Kind = 0;
7304 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +00007305 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
7306 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +00007307 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
7308 Diag(PrevDecl->getLocation(), diag::note_declared_at);
7309 Invalid = true;
7310
7311 // Otherwise, only diagnose if the declaration is in scope.
Douglas Gregordb446112011-03-07 16:54:27 +00007312 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
7313 isExplicitSpecialization)) {
John McCalle87beb22010-04-23 18:46:30 +00007314 // do nothing
7315
7316 // Diagnose implicit declarations introduced by elaborated types.
7317 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
7318 unsigned Kind = 0;
7319 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
Richard Smithdda56e42011-04-15 14:24:37 +00007320 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
7321 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
John McCalle87beb22010-04-23 18:46:30 +00007322 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
7323 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
7324 Invalid = true;
7325
7326 // Otherwise it's a declaration. Call out a particularly common
7327 // case here.
Richard Smithdda56e42011-04-15 14:24:37 +00007328 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
7329 unsigned Kind = 0;
7330 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
John McCalle87beb22010-04-23 18:46:30 +00007331 Diag(NameLoc, diag::err_tag_definition_of_typedef)
Richard Smithdda56e42011-04-15 14:24:37 +00007332 << Name << Kind << TND->getUnderlyingType();
John McCalle87beb22010-04-23 18:46:30 +00007333 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
7334 Invalid = true;
7335
7336 // Otherwise, diagnose.
7337 } else {
7338 // The tag name clashes with something else in the target scope,
7339 // issue an error and recover by making this tag be anonymous.
Chris Lattner4bd8dd82008-11-19 08:23:25 +00007340 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner0369c572008-11-23 23:12:31 +00007341 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +00007342 Name = 0;
Douglas Gregordee1be82009-01-17 00:42:38 +00007343 Invalid = true;
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +00007344 }
John McCalle87beb22010-04-23 18:46:30 +00007345
7346 // The existing declaration isn't relevant to us; we're in a
7347 // new scope, so clear out the previous declaration.
7348 Previous.clear();
Chris Lattner8799cf22007-01-23 01:57:16 +00007349 }
Chris Lattner18b19622007-01-22 07:39:13 +00007350 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00007351
Chris Lattner438e5012008-12-17 07:13:27 +00007352CreateNewDecl:
Mike Stump11289f42009-09-09 15:08:12 +00007353
John McCall1f82f242009-11-18 22:49:29 +00007354 TagDecl *PrevDecl = 0;
7355 if (Previous.isSingleResult())
7356 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
7357
Chris Lattnerbf0b7982007-01-23 04:27:41 +00007358 // If there is an identifier, use the location of the identifier as the
7359 // location of the decl, otherwise use the location of the struct/union
7360 // keyword.
7361 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
Mike Stump11289f42009-09-09 15:08:12 +00007362
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007363 // Otherwise, create a new declaration. If there is a previous
7364 // declaration of the same entity, the two will be linked via
7365 // PrevDecl.
Chris Lattner7b9ace62007-01-23 20:11:08 +00007366 TagDecl *New;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00007367
Douglas Gregor0bf31402010-10-08 23:50:27 +00007368 bool IsForwardReference = false;
Abramo Bagnara6150c882010-05-11 21:36:43 +00007369 if (Kind == TTK_Enum) {
Chris Lattner776fac82007-06-09 00:53:06 +00007370 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
7371 // enum X { A, B, C } D; D should chain to X.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007372 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
Douglas Gregor0bf31402010-10-08 23:50:27 +00007373 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00007374 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
Chris Lattner5f521502007-01-25 06:27:24 +00007375 // If this is an undefined enum, warn.
Douglas Gregorc9ea2d52010-06-22 14:26:35 +00007376 if (TUK != TUK_Definition && !Invalid) {
7377 TagDecl *Def;
Douglas Gregor0bf31402010-10-08 23:50:27 +00007378 if (getLangOptions().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) {
7379 // C++0x: 7.2p2: opaque-enum-declaration.
7380 // Conflicts are diagnosed above. Do nothing.
7381 }
7382 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
Douglas Gregorc9ea2d52010-06-22 14:26:35 +00007383 Diag(Loc, diag::ext_forward_ref_enum_def)
7384 << New;
7385 Diag(Def->getLocation(), diag::note_previous_definition);
7386 } else {
Francois Pichet488b4a72010-09-12 05:06:55 +00007387 unsigned DiagID = diag::ext_forward_ref_enum;
7388 if (getLangOptions().Microsoft)
7389 DiagID = diag::ext_ms_forward_ref_enum;
7390 else if (getLangOptions().CPlusPlus)
7391 DiagID = diag::err_forward_ref_enum;
7392 Diag(Loc, DiagID);
Douglas Gregor0bf31402010-10-08 23:50:27 +00007393
7394 // If this is a forward-declared reference to an enumeration, make a
7395 // note of it; we won't actually be introducing the declaration into
7396 // the declaration context.
7397 if (TUK == TUK_Reference)
7398 IsForwardReference = true;
Douglas Gregorc9ea2d52010-06-22 14:26:35 +00007399 }
Douglas Gregord45b93b2009-03-06 18:34:03 +00007400 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00007401
7402 if (EnumUnderlying) {
7403 EnumDecl *ED = cast<EnumDecl>(New);
7404 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
7405 ED->setIntegerTypeSourceInfo(TI);
7406 else
7407 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
7408 ED->setPromotionType(ED->getIntegerType());
7409 }
7410
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00007411 } else {
7412 // struct/union/class
7413
Chris Lattner776fac82007-06-09 00:53:06 +00007414 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
7415 // struct X { int A; } D; D should chain to X.
Douglas Gregor87f54062009-09-15 22:30:29 +00007416 if (getLangOptions().CPlusPlus) {
Ted Kremenek6ddf53e2008-09-05 17:39:33 +00007417 // FIXME: Look for a way to use RecordDecl for simple structs.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007418 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007419 cast_or_null<CXXRecordDecl>(PrevDecl));
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007420
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007421 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
Douglas Gregor87f54062009-09-15 22:30:29 +00007422 StdBadAlloc = cast<CXXRecordDecl>(New);
7423 } else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007424 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007425 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007426 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007427
John McCall3e11ebe2010-03-15 10:12:16 +00007428 // Maybe add qualifier info.
7429 if (SS.isNotEmpty()) {
Fariborz Jahanian862fac92010-05-14 21:35:02 +00007430 if (SS.isSet()) {
Douglas Gregor14454802011-02-25 02:25:35 +00007431 New->setQualifierInfo(SS.getWithLocInContext(Context));
Abramo Bagnara60804e12011-03-18 15:16:37 +00007432 if (TemplateParameterLists.size() > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00007433 New->setTemplateParameterListsInfo(Context,
Abramo Bagnara60804e12011-03-18 15:16:37 +00007434 TemplateParameterLists.size(),
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00007435 (TemplateParameterList**) TemplateParameterLists.release());
7436 }
Fariborz Jahanian862fac92010-05-14 21:35:02 +00007437 }
7438 else
7439 Invalid = true;
John McCall3e11ebe2010-03-15 10:12:16 +00007440 }
7441
Daniel Dunbar8804f2e2010-05-27 01:53:40 +00007442 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
7443 // Add alignment attributes if necessary; these attributes are checked when
7444 // the ASTContext lays out the structure.
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007445 //
7446 // It is important for implementing the correct semantics that this
7447 // happen here (in act on tag decl). The #pragma pack stack is
7448 // maintained as a result of parser callbacks which can occur at
7449 // many points during the parsing of a struct declaration (because
7450 // the #pragma tokens are effectively skipped over during the
7451 // parsing of the struct).
Daniel Dunbar8804f2e2010-05-27 01:53:40 +00007452 AddAlignmentAttributesForRecord(RD);
Fariborz Jahanian6b4e26b2011-04-26 17:54:40 +00007453
7454 AddMsStructLayoutForRecord(RD);
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007455 }
7456
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007457 // If this is a specialization of a member class (of a class template),
7458 // check the specialization.
John McCall1f82f242009-11-18 22:49:29 +00007459 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
Douglas Gregorbbe8f462009-10-08 15:14:33 +00007460 Invalid = true;
Daniel Dunbar8804f2e2010-05-27 01:53:40 +00007461
Douglas Gregordee1be82009-01-17 00:42:38 +00007462 if (Invalid)
7463 New->setInvalidDecl();
7464
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007465 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00007466 ProcessDeclAttributeList(S, New, Attr);
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007467
Douglas Gregordee1be82009-01-17 00:42:38 +00007468 // If we're declaring or defining a tag in function prototype scope
7469 // in C, note that this type can only be used within the function.
Douglas Gregor658b9552009-01-09 22:42:13 +00007470 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
7471 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
7472
Douglas Gregorc811d8f2008-12-15 16:32:14 +00007473 // Set the lexical context. If the tag has a C++ scope specifier, the
7474 // lexical context will be different from the semantic context.
Douglas Gregor8761da52009-02-03 00:34:39 +00007475 New->setLexicalDeclContext(CurContext);
Douglas Gregordee1be82009-01-17 00:42:38 +00007476
John McCallaa74a0c2009-08-28 07:59:38 +00007477 // Mark this as a friend decl if applicable.
Francois Pichete37eeba2011-06-01 04:14:20 +00007478 // In Microsoft mode, a friend declaration also acts as a forward
7479 // declaration so we always pass true to setObjectOfFriendDecl to make
7480 // the tag name visible.
John McCallaa74a0c2009-08-28 07:59:38 +00007481 if (TUK == TUK_Friend)
Francois Pichete37eeba2011-06-01 04:14:20 +00007482 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() ||
7483 getLangOptions().Microsoft);
John McCallaa74a0c2009-08-28 07:59:38 +00007484
Anders Carlsson5558ca12009-03-26 01:19:02 +00007485 // Set the access specifier.
John McCalle9eaf8e2010-03-25 21:28:06 +00007486 if (!Invalid && SearchDC->isRecord())
Douglas Gregorb8006faf2009-05-27 17:30:49 +00007487 SetMemberAccessSpecifier(New, PrevDecl, AS);
Douglas Gregor6c2adff2009-03-25 22:00:53 +00007488
John McCall9bb74a52009-07-31 02:45:11 +00007489 if (TUK == TUK_Definition)
Douglas Gregordee1be82009-01-17 00:42:38 +00007490 New->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00007491
Chris Lattner18b19622007-01-22 07:39:13 +00007492 // If this has an identifier, add it to the scope stack.
John McCall2dc078f2009-09-02 00:55:30 +00007493 if (TUK == TUK_Friend) {
John McCallf8bd8612009-09-02 19:32:14 +00007494 // We might be replacing an existing declaration in the lookup tables;
7495 // if so, borrow its access specifier.
7496 if (PrevDecl)
7497 New->setAccess(PrevDecl->getAccess());
7498
Sebastian Redl50c68252010-08-31 00:36:30 +00007499 DeclContext *DC = New->getDeclContext()->getRedeclContext();
John McCalle9eaf8e2010-03-25 21:28:06 +00007500 DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
7501 if (Name) // can be null along some error paths
John McCall2dc078f2009-09-02 00:55:30 +00007502 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
7503 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
John McCall2dc078f2009-09-02 00:55:30 +00007504 } else if (Name) {
Douglas Gregor45a33ec2009-01-12 18:45:55 +00007505 S = getNonFieldDeclScope(S);
Douglas Gregor0bf31402010-10-08 23:50:27 +00007506 PushOnScopeChains(New, S, !IsForwardReference);
7507 if (IsForwardReference)
7508 SearchDC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
7509
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00007510 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007511 CurContext->addDecl(New);
Chris Lattner18b19622007-01-22 07:39:13 +00007512 }
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00007513
Douglas Gregor27821ce2009-07-07 16:35:42 +00007514 // If this is the C FILE type, notify the AST context.
7515 if (IdentifierInfo *II = New->getIdentifier())
7516 if (!New->isInvalidDecl() &&
Sebastian Redl50c68252010-08-31 00:36:30 +00007517 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
Douglas Gregor27821ce2009-07-07 16:35:42 +00007518 II->isStr("FILE"))
7519 Context.setFILEDecl(New);
Mike Stump11289f42009-09-09 15:08:12 +00007520
Douglas Gregord6ab8742009-05-28 23:31:59 +00007521 OwnedDecl = true;
John McCall48871652010-08-21 09:40:31 +00007522 return New;
Chris Lattner18b19622007-01-22 07:39:13 +00007523}
Chris Lattner1300fb92007-01-23 23:42:53 +00007524
John McCall48871652010-08-21 09:40:31 +00007525void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00007526 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00007527 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregorba41d012010-04-24 16:38:41 +00007528
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007529 // Enter the tag context.
7530 PushDeclContext(S, Tag);
John McCall1c7e6ec2009-12-20 07:58:13 +00007531}
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007532
John McCall48871652010-08-21 09:40:31 +00007533void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
Anders Carlsson30f29442011-03-25 14:31:08 +00007534 SourceLocation FinalLoc,
John McCall1c7e6ec2009-12-20 07:58:13 +00007535 SourceLocation LBraceLoc) {
7536 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00007537 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007538
John McCall1c7e6ec2009-12-20 07:58:13 +00007539 FieldCollector->StartClass();
7540
7541 if (!Record->getIdentifier())
7542 return;
7543
Anders Carlsson30f29442011-03-25 14:31:08 +00007544 if (FinalLoc.isValid())
7545 Record->addAttr(new (Context) FinalAttr(FinalLoc, Context));
Anders Carlssonfc1eef42011-01-22 17:51:53 +00007546
John McCall1c7e6ec2009-12-20 07:58:13 +00007547 // C++ [class]p2:
7548 // [...] The class-name is also inserted into the scope of the
7549 // class itself; this is known as the injected-class-name. For
7550 // purposes of access checking, the injected-class-name is treated
7551 // as if it were a public member name.
7552 CXXRecordDecl *InjectedClassName
Abramo Bagnara29c2d462011-03-09 14:09:51 +00007553 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
7554 Record->getLocStart(), Record->getLocation(),
John McCall1c7e6ec2009-12-20 07:58:13 +00007555 Record->getIdentifier(),
Argyrios Kyrtzidis470c4542010-10-14 20:14:21 +00007556 /*PrevDecl=*/0,
7557 /*DelayTypeCreation=*/true);
7558 Context.getTypeDeclType(InjectedClassName, Record);
John McCall1c7e6ec2009-12-20 07:58:13 +00007559 InjectedClassName->setImplicit();
7560 InjectedClassName->setAccess(AS_public);
7561 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
7562 InjectedClassName->setDescribedClassTemplate(Template);
7563 PushOnScopeChains(InjectedClassName, S);
7564 assert(InjectedClassName->isInjectedClassName() &&
7565 "Broken injected-class-name");
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007566}
7567
John McCall48871652010-08-21 09:40:31 +00007568void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +00007569 SourceLocation RBraceLoc) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00007570 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00007571 TagDecl *Tag = cast<TagDecl>(TagD);
Argyrios Kyrtzidis23e1f1d2009-07-14 03:17:52 +00007572 Tag->setRBraceLoc(RBraceLoc);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007573
7574 if (isa<CXXRecordDecl>(Tag))
7575 FieldCollector->FinishClass();
7576
7577 // Exit this scope of this tag's definition.
7578 PopDeclContext();
Douglas Gregor859f0ae2010-01-06 17:00:51 +00007579
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007580 // Notify the consumer that we've defined a tag.
7581 Consumer.HandleTagDeclDefinition(Tag);
7582}
Chris Lattner535b8302008-06-21 19:39:06 +00007583
John McCall48871652010-08-21 09:40:31 +00007584void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
John McCall2ff380a2010-03-17 00:38:33 +00007585 AdjustDeclIfTemplate(TagD);
John McCall48871652010-08-21 09:40:31 +00007586 TagDecl *Tag = cast<TagDecl>(TagD);
John McCall2ff380a2010-03-17 00:38:33 +00007587 Tag->setInvalidDecl();
7588
John McCall71ba5f22010-03-17 19:25:57 +00007589 // We're undoing ActOnTagStartDefinition here, not
7590 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
7591 // the FieldCollector.
John McCall2ff380a2010-03-17 00:38:33 +00007592
7593 PopDeclContext();
7594}
7595
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007596// Note that FieldName may be null for anonymous bitfields.
Mike Stump11289f42009-09-09 15:08:12 +00007597bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Eli Friedmanc96d4962009-08-15 21:55:26 +00007598 QualType FieldTy, const Expr *BitWidth,
7599 bool *ZeroWidth) {
7600 // Default to true; that shouldn't confuse checks for emptiness
7601 if (ZeroWidth)
7602 *ZeroWidth = true;
7603
Chris Lattner73bf7b42009-03-05 22:45:59 +00007604 // C99 6.7.2.1p4 - verify the field type.
Chris Lattnerd26760a2009-03-05 23:01:03 +00007605 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregorb90df602010-06-16 00:17:44 +00007606 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
Chris Lattner73bf7b42009-03-05 22:45:59 +00007607 // Handle incomplete types with specific error.
Douglas Gregor81457422009-03-10 21:58:27 +00007608 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
7609 return true;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007610 if (FieldName)
7611 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
7612 << FieldName << FieldTy << BitWidth->getSourceRange();
7613 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
7614 << FieldTy << BitWidth->getSourceRange();
Douglas Gregora02a72a2010-12-15 23:18:36 +00007615 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
7616 UPPC_BitFieldWidth))
7617 return true;
Douglas Gregor1efa4372009-03-11 18:59:21 +00007618
7619 // If the bit-width is type- or value-dependent, don't try to check
7620 // it now.
7621 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
7622 return false;
7623
Anders Carlsson5df391e2008-12-06 20:33:04 +00007624 llvm::APSInt Value;
7625 if (VerifyIntegerConstantExpression(BitWidth, &Value))
7626 return true;
7627
Eli Friedmanc96d4962009-08-15 21:55:26 +00007628 if (Value != 0 && ZeroWidth)
7629 *ZeroWidth = false;
7630
Chris Lattner81ed6802008-12-12 04:56:04 +00007631 // Zero-width bitfield is ok for anonymous field.
7632 if (Value == 0 && FieldName)
7633 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00007634
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007635 if (Value.isSigned() && Value.isNegative()) {
7636 if (FieldName)
Mike Stump11289f42009-09-09 15:08:12 +00007637 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007638 << FieldName << Value.toString(10);
7639 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
7640 << Value.toString(10);
7641 }
Anders Carlsson5df391e2008-12-06 20:33:04 +00007642
Douglas Gregor1efa4372009-03-11 18:59:21 +00007643 if (!FieldTy->isDependentType()) {
7644 uint64_t TypeSize = Context.getTypeSize(FieldTy);
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007645 if (Value.getZExtValue() > TypeSize) {
Anders Carlssond5635fe2010-04-16 15:16:32 +00007646 if (!getLangOptions().CPlusPlus) {
7647 if (FieldName)
7648 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
7649 << FieldName << (unsigned)Value.getZExtValue()
7650 << (unsigned)TypeSize;
7651
7652 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
7653 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
7654 }
7655
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007656 if (FieldName)
Anders Carlssond5635fe2010-04-16 15:16:32 +00007657 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
7658 << FieldName << (unsigned)Value.getZExtValue()
7659 << (unsigned)TypeSize;
7660 else
7661 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
7662 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
Chris Lattnerf9b00eb2009-04-20 17:29:38 +00007663 }
Douglas Gregor1efa4372009-03-11 18:59:21 +00007664 }
Anders Carlsson5df391e2008-12-06 20:33:04 +00007665
7666 return false;
7667}
7668
Richard Smith938f40b2011-06-11 17:19:42 +00007669/// ActOnField - Each field of a C struct/union is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +00007670/// to create a FieldDecl object for it.
Richard Smith938f40b2011-06-11 17:19:42 +00007671Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
7672 Declarator &D, ExprTy *BitfieldWidth) {
John McCall48871652010-08-21 09:40:31 +00007673 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
Chris Lattner83f095c2009-03-28 19:18:32 +00007674 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
Richard Smith938f40b2011-06-11 17:19:42 +00007675 /*HasInit=*/false, AS_public);
John McCall48871652010-08-21 09:40:31 +00007676 return Res;
Chris Lattner73bf7b42009-03-05 22:45:59 +00007677}
7678
7679/// HandleField - Analyze a field of a C struct or a C++ data member.
7680///
7681FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
7682 SourceLocation DeclStart,
Richard Smith938f40b2011-06-11 17:19:42 +00007683 Declarator &D, Expr *BitWidth, bool HasInit,
Douglas Gregor4261e4c2009-03-11 20:50:30 +00007684 AccessSpecifier AS) {
Chris Lattner1300fb92007-01-23 23:42:53 +00007685 IdentifierInfo *II = D.getIdentifier();
Chris Lattner1300fb92007-01-23 23:42:53 +00007686 SourceLocation Loc = DeclStart;
7687 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +00007688
John McCall8cb7bdf2010-06-04 23:28:52 +00007689 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
7690 QualType T = TInfo->getType();
Douglas Gregora02a72a2010-12-15 23:18:36 +00007691 if (getLangOptions().CPlusPlus) {
Douglas Gregor1efa4372009-03-11 18:59:21 +00007692 CheckExtraCXXDefaultArguments(D);
Douglas Gregor0c880302009-03-11 23:00:04 +00007693
Douglas Gregora02a72a2010-12-15 23:18:36 +00007694 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
7695 UPPC_DataMemberType)) {
7696 D.setInvalidType();
7697 T = Context.IntTy;
7698 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
7699 }
7700 }
7701
Eli Friedman574c7452009-04-07 19:37:57 +00007702 DiagnoseFunctionSpecifiers(D);
7703
Eli Friedmand5c0eed2009-04-19 20:27:55 +00007704 if (D.getDeclSpec().isThreadSpecified())
7705 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
Douglas Gregor2c7d9292010-08-30 14:32:14 +00007706
7707 // Check to see if this name was declared as a member previously
7708 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
7709 LookupName(Previous, S);
7710 assert((Previous.empty() || Previous.isOverloadedResult() ||
7711 Previous.isSingleResult())
7712 && "Lookup of member name should be either overloaded, single or null");
Eli Friedmand5c0eed2009-04-19 20:27:55 +00007713
Douglas Gregor2c7d9292010-08-30 14:32:14 +00007714 // If the name is overloaded then get any declaration else get the single result
7715 NamedDecl *PrevDecl = Previous.isOverloadedResult() ?
7716 Previous.getRepresentativeDecl() : Previous.getAsSingle<NamedDecl>();
Douglas Gregorf187420f2009-06-17 23:37:01 +00007717
7718 if (PrevDecl && PrevDecl->isTemplateParameter()) {
7719 // Maybe we will complain about the shadowed template parameter.
7720 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
7721 // Just pretend that we didn't see the previous declaration.
7722 PrevDecl = 0;
7723 }
7724
Douglas Gregor1efa4372009-03-11 18:59:21 +00007725 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
7726 PrevDecl = 0;
7727
Steve Naroff5ec6ff72009-07-14 14:58:18 +00007728 bool Mutable
7729 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
7730 SourceLocation TSSL = D.getSourceRange().getBegin();
7731 FieldDecl *NewFD
Richard Smith938f40b2011-06-11 17:19:42 +00007732 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, HasInit,
7733 TSSL, AS, PrevDecl, &D);
Rafael Espindola568586f2010-03-21 22:56:43 +00007734
7735 if (NewFD->isInvalidDecl())
7736 Record->setInvalidDecl();
7737
Douglas Gregor1efa4372009-03-11 18:59:21 +00007738 if (NewFD->isInvalidDecl() && PrevDecl) {
7739 // Don't introduce NewFD into scope; there's already something
7740 // with the same name in the same scope.
7741 } else if (II) {
7742 PushOnScopeChains(NewFD, S);
7743 } else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007744 Record->addDecl(NewFD);
Douglas Gregor1efa4372009-03-11 18:59:21 +00007745
7746 return NewFD;
7747}
7748
7749/// \brief Build a new FieldDecl and check its well-formedness.
7750///
7751/// This routine builds a new FieldDecl given the fields name, type,
7752/// record, etc. \p PrevDecl should refer to any previous declaration
7753/// with the same name and in the same scope as the field to be
7754/// created.
7755///
7756/// \returns a new FieldDecl.
7757///
Mike Stump11289f42009-09-09 15:08:12 +00007758/// \todo The Declarator argument is a hack. It will be removed once
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00007759FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
John McCallbcd03502009-12-07 02:54:59 +00007760 TypeSourceInfo *TInfo,
Douglas Gregor1efa4372009-03-11 18:59:21 +00007761 RecordDecl *Record, SourceLocation Loc,
Richard Smith938f40b2011-06-11 17:19:42 +00007762 bool Mutable, Expr *BitWidth, bool HasInit,
Steve Naroff5ec6ff72009-07-14 14:58:18 +00007763 SourceLocation TSSL,
Douglas Gregor4261e4c2009-03-11 20:50:30 +00007764 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor1efa4372009-03-11 18:59:21 +00007765 Declarator *D) {
7766 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Narofff93b6722007-08-28 20:14:24 +00007767 bool InvalidDecl = false;
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007768 if (D) InvalidDecl = D->isInvalidType();
Sebastian Redlbaad4e72009-01-05 20:52:13 +00007769
Douglas Gregor1efa4372009-03-11 18:59:21 +00007770 // If we receive a broken type, recover by assuming 'int' and
7771 // marking this declaration as invalid.
7772 if (T.isNull()) {
7773 InvalidDecl = true;
7774 T = Context.IntTy;
7775 }
7776
Eli Friedmand0e8de22009-12-07 00:22:08 +00007777 QualType EltTy = Context.getBaseElementType(T);
7778 if (!EltTy->isDependentType() &&
John McCall2677e102010-08-16 23:42:35 +00007779 RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
7780 // Fields of incomplete type force their record to be invalid.
7781 Record->setInvalidDecl();
Eli Friedmand0e8de22009-12-07 00:22:08 +00007782 InvalidDecl = true;
John McCall2677e102010-08-16 23:42:35 +00007783 }
Eli Friedmand0e8de22009-12-07 00:22:08 +00007784
Steve Naroff8eeeb132007-05-08 21:09:37 +00007785 // C99 6.7.2.1p8: A member of a structure or union may have any type other
7786 // than a variably modified type.
Eli Friedmand0e8de22009-12-07 00:22:08 +00007787 if (!InvalidDecl && T->isVariablyModifiedType()) {
Eli Friedmana3b1d032009-02-21 00:44:51 +00007788 bool SizeIsNegative;
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00007789 llvm::APSInt Oversized;
Eli Friedmana3b1d032009-02-21 00:44:51 +00007790 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00007791 SizeIsNegative,
7792 Oversized);
Eli Friedmana3b1d032009-02-21 00:44:51 +00007793 if (!FixedTy.isNull()) {
7794 Diag(Loc, diag::warn_illegal_constant_array_size);
7795 T = FixedTy;
7796 } else {
7797 if (SizeIsNegative)
7798 Diag(Loc, diag::err_typecheck_negative_array_size);
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00007799 else if (Oversized.getBoolValue())
7800 Diag(Loc, diag::err_array_too_large)
7801 << Oversized.toString(10);
Eli Friedmana3b1d032009-02-21 00:44:51 +00007802 else
7803 Diag(Loc, diag::err_typecheck_field_variable_size);
Eli Friedmana3b1d032009-02-21 00:44:51 +00007804 InvalidDecl = true;
7805 }
Steve Naroff8eeeb132007-05-08 21:09:37 +00007806 }
Mike Stump11289f42009-09-09 15:08:12 +00007807
Anders Carlsson576cc6f2009-03-22 20:18:17 +00007808 // Fields can not have abstract class types
Eli Friedmand0e8de22009-12-07 00:22:08 +00007809 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
7810 diag::err_abstract_type_in_decl,
7811 AbstractFieldType))
Anders Carlsson576cc6f2009-03-22 20:18:17 +00007812 InvalidDecl = true;
Mike Stump11289f42009-09-09 15:08:12 +00007813
Eli Friedmanc96d4962009-08-15 21:55:26 +00007814 bool ZeroWidth = false;
Douglas Gregor1efa4372009-03-11 18:59:21 +00007815 // If this is declared as a bit-field, check the bit-field.
Eli Friedmand0e8de22009-12-07 00:22:08 +00007816 if (!InvalidDecl && BitWidth &&
7817 VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
Douglas Gregor1efa4372009-03-11 18:59:21 +00007818 InvalidDecl = true;
Douglas Gregor1efa4372009-03-11 18:59:21 +00007819 BitWidth = 0;
Eli Friedmanc96d4962009-08-15 21:55:26 +00007820 ZeroWidth = false;
Anders Carlsson5df391e2008-12-06 20:33:04 +00007821 }
Mike Stump11289f42009-09-09 15:08:12 +00007822
John McCallb1cd7da2010-06-04 08:34:12 +00007823 // Check that 'mutable' is consistent with the type of the declaration.
7824 if (!InvalidDecl && Mutable) {
7825 unsigned DiagID = 0;
7826 if (T->isReferenceType())
7827 DiagID = diag::err_mutable_reference;
7828 else if (T.isConstQualified())
7829 DiagID = diag::err_mutable_const;
7830
7831 if (DiagID) {
7832 SourceLocation ErrLoc = Loc;
7833 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
7834 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
7835 Diag(ErrLoc, DiagID);
7836 Mutable = false;
7837 InvalidDecl = true;
7838 }
7839 }
7840
Abramo Bagnaradff19302011-03-08 08:55:46 +00007841 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00007842 BitWidth, Mutable, HasInit);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00007843 if (InvalidDecl)
7844 NewFD->setInvalidDecl();
Douglas Gregor91f84212008-12-11 16:49:14 +00007845
Douglas Gregor1efa4372009-03-11 18:59:21 +00007846 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
7847 Diag(Loc, diag::err_duplicate_member) << II;
7848 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
7849 NewFD->setInvalidDecl();
Douglas Gregor82ac25e2009-01-08 20:45:30 +00007850 }
7851
John McCall67da35c2010-02-04 22:26:26 +00007852 if (!InvalidDecl && getLangOptions().CPlusPlus) {
Anders Carlsson2ceb3472010-11-07 19:13:55 +00007853 if (Record->isUnion()) {
7854 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
7855 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
7856 if (RDecl->getDefinition()) {
7857 // C++ [class.union]p1: An object of a class with a non-trivial
7858 // constructor, a non-trivial copy constructor, a non-trivial
7859 // destructor, or a non-trivial copy assignment operator
7860 // cannot be a member of a union, nor can an array of such
7861 // objects.
Alexis Hunt97ab5542011-05-16 22:41:40 +00007862 if (!getLangOptions().CPlusPlus0x && CheckNontrivialField(NewFD))
Anders Carlsson2ceb3472010-11-07 19:13:55 +00007863 NewFD->setInvalidDecl();
7864 }
7865 }
7866
7867 // C++ [class.union]p1: If a union contains a member of reference type,
7868 // the program is ill-formed.
7869 if (EltTy->isReferenceType()) {
7870 Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
7871 << NewFD->getDeclName() << EltTy;
7872 NewFD->setInvalidDecl();
Douglas Gregor8a273912009-07-22 18:25:24 +00007873 }
7874 }
7875 }
7876
Douglas Gregor1efa4372009-03-11 18:59:21 +00007877 // FIXME: We need to pass in the attributes given an AST
7878 // representation, not a parser representation.
7879 if (D)
Douglas Gregor758a8692009-06-17 21:51:59 +00007880 // FIXME: What to pass instead of TUScope?
7881 ProcessDeclAttributes(TUScope, NewFD, *D);
Douglas Gregor1efa4372009-03-11 18:59:21 +00007882
John McCall31168b02011-06-15 23:02:42 +00007883 // In auto-retain/release, infer strong retension for fields of
7884 // retainable type.
7885 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
7886 NewFD->setInvalidDecl();
7887
Fariborz Jahaniand29fecd2009-02-19 00:22:47 +00007888 if (T.isObjCGCWeak())
Fariborz Jahaniand35c7922009-02-18 18:14:41 +00007889 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlsson28e71082008-02-16 00:29:18 +00007890
Douglas Gregor4261e4c2009-03-11 20:50:30 +00007891 NewFD->setAccess(AS);
Steve Narofff93b6722007-08-28 20:14:24 +00007892 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +00007893}
7894
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00007895bool Sema::CheckNontrivialField(FieldDecl *FD) {
7896 assert(FD);
7897 assert(getLangOptions().CPlusPlus && "valid check only for C++");
7898
7899 if (FD->isInvalidDecl())
7900 return true;
7901
7902 QualType EltTy = Context.getBaseElementType(FD->getType());
7903 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
7904 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
7905 if (RDecl->getDefinition()) {
7906 // We check for copy constructors before constructors
7907 // because otherwise we'll never get complaints about
7908 // copy constructors.
7909
7910 CXXSpecialMember member = CXXInvalid;
7911 if (!RDecl->hasTrivialCopyConstructor())
7912 member = CXXCopyConstructor;
Alexis Huntf479f1b2011-05-09 18:22:59 +00007913 else if (!RDecl->hasTrivialDefaultConstructor())
Alexis Hunt80f00ff2011-05-10 19:08:14 +00007914 member = CXXDefaultConstructor;
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00007915 else if (!RDecl->hasTrivialCopyAssignment())
7916 member = CXXCopyAssignment;
7917 else if (!RDecl->hasTrivialDestructor())
7918 member = CXXDestructor;
7919
7920 if (member != CXXInvalid) {
John McCall31168b02011-06-15 23:02:42 +00007921 if (getLangOptions().ObjCAutoRefCount && RDecl->hasObjectMember()) {
7922 // Objective-C++ ARC: it is an error to have a non-trivial field of
7923 // a union. However, system headers in Objective-C programs
7924 // occasionally have Objective-C lifetime objects within unions,
7925 // and rather than cause the program to fail, we make those
7926 // members unavailable.
7927 SourceLocation Loc = FD->getLocation();
7928 if (getSourceManager().isInSystemHeader(Loc)) {
7929 if (!FD->hasAttr<UnavailableAttr>())
7930 FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00007931 "this system field has retaining ownership"));
John McCall31168b02011-06-15 23:02:42 +00007932 return false;
7933 }
7934 }
7935
Argyrios Kyrtzidis33aee392010-08-16 17:27:08 +00007936 Diag(FD->getLocation(), diag::err_illegal_union_or_anon_struct_member)
7937 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
7938 DiagnoseNontrivial(RT, member);
7939 return true;
7940 }
7941 }
7942 }
7943
7944 return false;
7945}
7946
Douglas Gregor8a273912009-07-22 18:25:24 +00007947/// DiagnoseNontrivial - Given that a class has a non-trivial
7948/// special member, figure out why.
7949void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
7950 QualType QT(T, 0U);
7951 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
7952
7953 // Check whether the member was user-declared.
7954 switch (member) {
Douglas Gregorfceea362010-04-22 14:36:26 +00007955 case CXXInvalid:
7956 break;
7957
Alexis Hunt80f00ff2011-05-10 19:08:14 +00007958 case CXXDefaultConstructor:
Douglas Gregor8a273912009-07-22 18:25:24 +00007959 if (RD->hasUserDeclaredConstructor()) {
7960 typedef CXXRecordDecl::ctor_iterator ctor_iter;
Sebastian Redle24b1622009-10-25 22:31:45 +00007961 for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
7962 const FunctionDecl *body = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007963 ci->hasBody(body);
Anders Carlssonb7229932010-04-20 23:32:58 +00007964 if (!body || !cast<CXXConstructorDecl>(body)->isImplicitlyDefined()) {
Douglas Gregor8a273912009-07-22 18:25:24 +00007965 SourceLocation CtorLoc = ci->getLocation();
7966 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
7967 return;
7968 }
Sebastian Redle24b1622009-10-25 22:31:45 +00007969 }
Douglas Gregor8a273912009-07-22 18:25:24 +00007970
7971 assert(0 && "found no user-declared constructors");
7972 return;
7973 }
7974 break;
7975
7976 case CXXCopyConstructor:
7977 if (RD->hasUserDeclaredCopyConstructor()) {
7978 SourceLocation CtorLoc =
Alexis Huntfcaeae42011-05-25 20:50:04 +00007979 RD->getCopyConstructor(0)->getLocation();
7980 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
7981 return;
7982 }
7983 break;
7984
7985 case CXXMoveConstructor:
7986 if (RD->hasUserDeclaredMoveConstructor()) {
7987 SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation();
Douglas Gregor8a273912009-07-22 18:25:24 +00007988 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
7989 return;
7990 }
7991 break;
7992
7993 case CXXCopyAssignment:
7994 if (RD->hasUserDeclaredCopyAssignment()) {
7995 // FIXME: this should use the location of the copy
7996 // assignment, not the type.
7997 SourceLocation TyLoc = RD->getSourceRange().getBegin();
7998 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
7999 return;
8000 }
8001 break;
8002
Alexis Huntfcaeae42011-05-25 20:50:04 +00008003 case CXXMoveAssignment:
8004 if (RD->hasUserDeclaredMoveAssignment()) {
8005 SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation();
8006 Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member;
8007 return;
8008 }
8009 break;
8010
Douglas Gregor8a273912009-07-22 18:25:24 +00008011 case CXXDestructor:
8012 if (RD->hasUserDeclaredDestructor()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00008013 SourceLocation DtorLoc = LookupDestructor(RD)->getLocation();
Douglas Gregor8a273912009-07-22 18:25:24 +00008014 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
8015 return;
8016 }
8017 break;
8018 }
8019
8020 typedef CXXRecordDecl::base_class_iterator base_iter;
8021
8022 // Virtual bases and members inhibit trivial copying/construction,
8023 // but not trivial destruction.
8024 if (member != CXXDestructor) {
8025 // Check for virtual bases. vbases includes indirect virtual bases,
8026 // so we just iterate through the direct bases.
8027 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
8028 if (bi->isVirtual()) {
8029 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
8030 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
8031 return;
8032 }
8033
8034 // Check for virtual methods.
8035 typedef CXXRecordDecl::method_iterator meth_iter;
8036 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
8037 ++mi) {
8038 if (mi->isVirtual()) {
8039 SourceLocation MLoc = mi->getSourceRange().getBegin();
8040 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
8041 return;
8042 }
8043 }
8044 }
Mike Stump11289f42009-09-09 15:08:12 +00008045
Douglas Gregor8a273912009-07-22 18:25:24 +00008046 bool (CXXRecordDecl::*hasTrivial)() const;
8047 switch (member) {
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008048 case CXXDefaultConstructor:
Alexis Huntf479f1b2011-05-09 18:22:59 +00008049 hasTrivial = &CXXRecordDecl::hasTrivialDefaultConstructor; break;
Douglas Gregor8a273912009-07-22 18:25:24 +00008050 case CXXCopyConstructor:
8051 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
8052 case CXXCopyAssignment:
8053 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
8054 case CXXDestructor:
8055 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
8056 default:
8057 assert(0 && "unexpected special member"); return;
8058 }
8059
8060 // Check for nontrivial bases (and recurse).
8061 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008062 const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
Sebastian Redl1054fae2009-10-25 17:03:50 +00008063 assert(BaseRT && "Don't know how to handle dependent bases");
Douglas Gregor8a273912009-07-22 18:25:24 +00008064 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
8065 if (!(BaseRecTy->*hasTrivial)()) {
8066 SourceLocation BaseLoc = bi->getSourceRange().getBegin();
8067 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
8068 DiagnoseNontrivial(BaseRT, member);
8069 return;
8070 }
8071 }
Mike Stump11289f42009-09-09 15:08:12 +00008072
Douglas Gregor8a273912009-07-22 18:25:24 +00008073 // Check for nontrivial members (and recurse).
8074 typedef RecordDecl::field_iterator field_iter;
8075 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
8076 ++fi) {
Douglas Gregor79f83ed2009-07-23 23:49:00 +00008077 QualType EltTy = Context.getBaseElementType((*fi)->getType());
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008078 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
Douglas Gregor8a273912009-07-22 18:25:24 +00008079 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
8080
8081 if (!(EltRD->*hasTrivial)()) {
8082 SourceLocation FLoc = (*fi)->getLocation();
8083 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
8084 DiagnoseNontrivial(EltRT, member);
8085 return;
8086 }
8087 }
John McCall31168b02011-06-15 23:02:42 +00008088
8089 if (EltTy->isObjCLifetimeType()) {
8090 switch (EltTy.getObjCLifetime()) {
8091 case Qualifiers::OCL_None:
8092 case Qualifiers::OCL_ExplicitNone:
8093 break;
8094
8095 case Qualifiers::OCL_Autoreleasing:
8096 case Qualifiers::OCL_Weak:
8097 case Qualifiers::OCL_Strong:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008098 Diag((*fi)->getLocation(), diag::note_nontrivial_objc_ownership)
John McCall31168b02011-06-15 23:02:42 +00008099 << QT << EltTy.getObjCLifetime();
8100 return;
8101 }
8102 }
Douglas Gregor8a273912009-07-22 18:25:24 +00008103 }
8104
8105 assert(0 && "found no explanation for non-trivial member");
8106}
8107
Mike Stump11289f42009-09-09 15:08:12 +00008108/// TranslateIvarVisibility - Translate visibility from a token ID to an
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00008109/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00008110static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00008111TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +00008112 switch (ivarVisibility) {
Chris Lattner79ef8432008-10-12 00:28:42 +00008113 default: assert(0 && "Unknown visitibility kind");
8114 case tok::objc_private: return ObjCIvarDecl::Private;
8115 case tok::objc_public: return ObjCIvarDecl::Public;
8116 case tok::objc_protected: return ObjCIvarDecl::Protected;
8117 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroff2e688fd2007-09-14 23:09:53 +00008118 }
8119}
8120
Mike Stump11289f42009-09-09 15:08:12 +00008121/// ActOnIvar - Each ivar field of an objective-c class is passed into this
Fariborz Jahanian96376742008-04-11 16:55:42 +00008122/// in order to create an IvarDecl object for it.
John McCall48871652010-08-21 09:40:31 +00008123Decl *Sema::ActOnIvar(Scope *S,
Mike Stump11289f42009-09-09 15:08:12 +00008124 SourceLocation DeclStart,
John McCall48871652010-08-21 09:40:31 +00008125 Decl *IntfDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00008126 Declarator &D, ExprTy *BitfieldWidth,
8127 tok::ObjCKeywordKind Visibility) {
Mike Stump11289f42009-09-09 15:08:12 +00008128
Fariborz Jahaniande615832008-04-10 23:32:45 +00008129 IdentifierInfo *II = D.getIdentifier();
8130 Expr *BitWidth = (Expr*)BitfieldWidth;
8131 SourceLocation Loc = DeclStart;
8132 if (II) Loc = D.getIdentifierLoc();
Mike Stump11289f42009-09-09 15:08:12 +00008133
Fariborz Jahaniande615832008-04-10 23:32:45 +00008134 // FIXME: Unnamed fields can be handled in various different ways, for
8135 // example, unnamed unions inject all members into the struct namespace!
Mike Stump11289f42009-09-09 15:08:12 +00008136
John McCall8cb7bdf2010-06-04 23:28:52 +00008137 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8138 QualType T = TInfo->getType();
Mike Stump11289f42009-09-09 15:08:12 +00008139
Fariborz Jahaniande615832008-04-10 23:32:45 +00008140 if (BitWidth) {
Steve Naroff17b2f5d2009-02-20 17:57:11 +00008141 // 6.7.2.1p3, 6.7.2.1p4
Chris Lattner73bf7b42009-03-05 22:45:59 +00008142 if (VerifyBitField(Loc, II, T, BitWidth)) {
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008143 D.setInvalidType();
Chris Lattner73bf7b42009-03-05 22:45:59 +00008144 BitWidth = 0;
8145 }
Fariborz Jahaniande615832008-04-10 23:32:45 +00008146 } else {
8147 // Not a bitfield.
Mike Stump11289f42009-09-09 15:08:12 +00008148
Fariborz Jahaniande615832008-04-10 23:32:45 +00008149 // validate II.
Mike Stump11289f42009-09-09 15:08:12 +00008150
Fariborz Jahaniande615832008-04-10 23:32:45 +00008151 }
Fariborz Jahanian0103d672010-04-26 22:07:03 +00008152 if (T->isReferenceType()) {
8153 Diag(Loc, diag::err_ivar_reference_type);
8154 D.setInvalidType();
8155 }
Fariborz Jahaniande615832008-04-10 23:32:45 +00008156 // C99 6.7.2.1p8: A member of a structure or union may have any type other
8157 // than a variably modified type.
Fariborz Jahanian0103d672010-04-26 22:07:03 +00008158 else if (T->isVariablyModifiedType()) {
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +00008159 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008160 D.setInvalidType();
Fariborz Jahaniande615832008-04-10 23:32:45 +00008161 }
Mike Stump11289f42009-09-09 15:08:12 +00008162
Ted Kremenek73295fa2008-07-23 18:04:17 +00008163 // Get the visibility (access control) for this ivar.
Mike Stump11289f42009-09-09 15:08:12 +00008164 ObjCIvarDecl::AccessControl ac =
Ted Kremenek73295fa2008-07-23 18:04:17 +00008165 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
8166 : ObjCIvarDecl::None;
Fariborz Jahanian68453832009-06-05 18:16:35 +00008167 // Must set ivar's DeclContext to its enclosing interface.
John McCall48871652010-08-21 09:40:31 +00008168 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(IntfDecl);
Daniel Dunbar229385c2010-04-02 18:29:09 +00008169 ObjCContainerDecl *EnclosingContext;
Mike Stump11289f42009-09-09 15:08:12 +00008170 if (ObjCImplementationDecl *IMPDecl =
Fariborz Jahanian68453832009-06-05 18:16:35 +00008171 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +00008172 if (!LangOpts.ObjCNonFragileABI2) {
Fariborz Jahanian68453832009-06-05 18:16:35 +00008173 // Case of ivar declared in an implementation. Context is that of its class.
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +00008174 EnclosingContext = IMPDecl->getClassInterface();
8175 assert(EnclosingContext && "Implementation has no class interface!");
8176 }
8177 else
8178 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00008179 } else {
8180 if (ObjCCategoryDecl *CDecl =
8181 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
8182 if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) {
8183 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
John McCall48871652010-08-21 09:40:31 +00008184 return 0;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00008185 }
8186 }
Daniel Dunbar229385c2010-04-02 18:29:09 +00008187 EnclosingContext = EnclosingDecl;
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00008188 }
Mike Stump11289f42009-09-09 15:08:12 +00008189
Ted Kremenek73295fa2008-07-23 18:04:17 +00008190 // Construct the decl.
Abramo Bagnaradff19302011-03-08 08:55:46 +00008191 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
8192 DeclStart, Loc, II, T,
John McCallbcd03502009-12-07 02:54:59 +00008193 TInfo, ac, (Expr *)BitfieldWidth);
Mike Stump11289f42009-09-09 15:08:12 +00008194
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008195 if (II) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00008196 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
John McCall5cebab12009-11-18 07:57:50 +00008197 ForRedeclaration);
Fariborz Jahanian68453832009-06-05 18:16:35 +00008198 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008199 && !isa<TagDecl>(PrevDecl)) {
8200 Diag(Loc, diag::err_duplicate_member) << II;
8201 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
8202 NewID->setInvalidDecl();
8203 }
8204 }
8205
Ted Kremenek73295fa2008-07-23 18:04:17 +00008206 // Process attributes attached to the ivar.
Douglas Gregor758a8692009-06-17 21:51:59 +00008207 ProcessDeclAttributes(S, NewID, D);
Mike Stump11289f42009-09-09 15:08:12 +00008208
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00008209 if (D.isInvalidType())
Fariborz Jahaniande615832008-04-10 23:32:45 +00008210 NewID->setInvalidDecl();
Ted Kremenek73295fa2008-07-23 18:04:17 +00008211
John McCall31168b02011-06-15 23:02:42 +00008212 // In ARC, infer 'retaining' for ivars of retainable type.
8213 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
8214 NewID->setInvalidDecl();
8215
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008216 if (II) {
8217 // FIXME: When interfaces are DeclContexts, we'll need to add
8218 // these to the interface.
John McCall48871652010-08-21 09:40:31 +00008219 S->AddDecl(NewID);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008220 IdResolver.AddDecl(NewID);
8221 }
8222
John McCall48871652010-08-21 09:40:31 +00008223 return NewID;
Fariborz Jahaniande615832008-04-10 23:32:45 +00008224}
8225
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00008226/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
8227/// class and class extensions. For every class @interface and class
8228/// extension @interface, if the last ivar is a bitfield of any type,
8229/// then add an implicit `char :0` ivar to the end of that interface.
8230void Sema::ActOnLastBitfield(SourceLocation DeclLoc, Decl *EnclosingDecl,
8231 llvm::SmallVectorImpl<Decl *> &AllIvarDecls) {
8232 if (!LangOpts.ObjCNonFragileABI2 || AllIvarDecls.empty())
8233 return;
8234
8235 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
8236 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
8237
8238 if (!Ivar->isBitField())
8239 return;
8240 uint64_t BitFieldSize =
8241 Ivar->getBitWidth()->EvaluateAsInt(Context).getZExtValue();
8242 if (BitFieldSize == 0)
8243 return;
8244 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl);
8245 if (!ID) {
8246 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
8247 if (!CD->IsClassExtension())
8248 return;
8249 }
8250 // No need to add this to end of @implementation.
8251 else
8252 return;
8253 }
8254 // All conditions are met. Add a new bitfield to the tail end of ivars.
8255 llvm::APInt Zero(Context.getTypeSize(Context.CharTy), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00008256 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.CharTy, DeclLoc);
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00008257
8258 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(EnclosingDecl),
Abramo Bagnaradff19302011-03-08 08:55:46 +00008259 DeclLoc, DeclLoc, 0,
Fariborz Jahanian616d3e72010-08-23 22:46:52 +00008260 Context.CharTy,
8261 Context.CreateTypeSourceInfo(Context.CharTy),
8262 ObjCIvarDecl::Private, BW,
8263 true);
8264 AllIvarDecls.push_back(Ivar);
8265}
8266
Fariborz Jahanian343f7092007-09-29 00:54:24 +00008267void Sema::ActOnFields(Scope* S,
John McCall48871652010-08-21 09:40:31 +00008268 SourceLocation RecLoc, Decl *EnclosingDecl,
8269 Decl **Fields, unsigned NumFields,
Daniel Dunbar15619c72008-10-03 02:03:53 +00008270 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar325601a2008-10-03 17:33:35 +00008271 AttributeList *Attr) {
Steve Naroffdb47ee22007-09-14 22:20:54 +00008272 assert(EnclosingDecl && "missing record or interface decl");
Mike Stump11289f42009-09-09 15:08:12 +00008273
Chris Lattnerd13b8b52009-02-23 22:00:08 +00008274 // If the decl this is being inserted into is invalid, then it may be a
8275 // redeclaration or some other bogus case. Don't try to add fields to it.
8276 if (EnclosingDecl->isInvalidDecl()) {
8277 // FIXME: Deallocate fields?
8278 return;
8279 }
8280
Mike Stump11289f42009-09-09 15:08:12 +00008281
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00008282 // Verify that all the fields are okay.
Chris Lattner82625602007-01-24 02:26:21 +00008283 unsigned NumNamedMembers = 0;
Chris Lattner23b7eb62007-06-15 23:05:46 +00008284 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorf4d33272009-01-07 19:46:03 +00008285
Chris Lattnerd13b8b52009-02-23 22:00:08 +00008286 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
John McCall31168b02011-06-15 23:02:42 +00008287 bool ARCErrReported = false;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00008288 for (unsigned i = 0; i != NumFields; ++i) {
John McCall48871652010-08-21 09:40:31 +00008289 FieldDecl *FD = cast<FieldDecl>(Fields[i]);
Mike Stump11289f42009-09-09 15:08:12 +00008290
Chris Lattner720a0542007-01-25 00:44:24 +00008291 // Get the type for the field.
John McCall424cec92011-01-19 06:33:43 +00008292 const Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorf4d33272009-01-07 19:46:03 +00008293
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008294 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00008295 // Remember all fields written by the user.
8296 RecFields.push_back(FD);
8297 }
Mike Stump11289f42009-09-09 15:08:12 +00008298
Chris Lattner73bf7b42009-03-05 22:45:59 +00008299 // If the field is already invalid for some reason, don't emit more
8300 // diagnostics about it.
Eli Friedmand0e8de22009-12-07 00:22:08 +00008301 if (FD->isInvalidDecl()) {
8302 EnclosingDecl->setInvalidDecl();
Chris Lattner73bf7b42009-03-05 22:45:59 +00008303 continue;
Eli Friedmand0e8de22009-12-07 00:22:08 +00008304 }
Mike Stump11289f42009-09-09 15:08:12 +00008305
Douglas Gregorac1fb652009-03-24 19:52:54 +00008306 // C99 6.7.2.1p2:
8307 // A structure or union shall not contain a member with
8308 // incomplete or function type (hence, a structure shall not
8309 // contain an instance of itself, but may contain a pointer to
8310 // an instance of itself), except that the last member of a
8311 // structure with more than one named member may have incomplete
8312 // array type; such a structure (and any union containing,
8313 // possibly recursively, a member that is such a structure)
8314 // shall not be a member of a structure or an element of an
8315 // array.
Chris Lattner0fd893e2007-07-31 21:33:24 +00008316 if (FDTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00008317 // Field declared as a function.
Chris Lattner651d42d2008-11-20 06:38:18 +00008318 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00008319 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +00008320 FD->setInvalidDecl();
8321 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00008322 continue;
Francois Pichetf657b632010-09-15 00:14:08 +00008323 } else if (FDTy->isIncompleteArrayType() && Record &&
8324 ((i == NumFields - 1 && !Record->isUnion()) ||
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00008325 ((getLangOptions().Microsoft || getLangOptions().CPlusPlus) &&
Francois Pichetf657b632010-09-15 00:14:08 +00008326 (i == NumFields - 1 || Record->isUnion())))) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00008327 // Flexible array member.
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00008328 // Microsoft and g++ is more permissive regarding flexible array.
Francois Pichetf657b632010-09-15 00:14:08 +00008329 // It will accept flexible array in union and also
Anders Carlsson0ea10472010-10-17 23:36:12 +00008330 // as the sole element of a struct/class.
Francois Pichetf657b632010-09-15 00:14:08 +00008331 if (getLangOptions().Microsoft) {
8332 if (Record->isUnion())
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00008333 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
Francois Pichetf657b632010-09-15 00:14:08 +00008334 << FD->getDeclName();
8335 else if (NumFields == 1)
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00008336 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
Francois Pichetf657b632010-09-15 00:14:08 +00008337 << FD->getDeclName() << Record->getTagKind();
Argyrios Kyrtzidis7e25a952011-03-07 20:04:04 +00008338 } else if (getLangOptions().CPlusPlus) {
8339 if (Record->isUnion())
8340 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
8341 << FD->getDeclName();
8342 else if (NumFields == 1)
8343 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
8344 << FD->getDeclName() << Record->getTagKind();
8345 } else if (NumNamedMembers < 1) {
Chris Lattner651d42d2008-11-20 06:38:18 +00008346 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00008347 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +00008348 FD->setInvalidDecl();
8349 EnclosingDecl->setInvalidDecl();
Chris Lattner82625602007-01-24 02:26:21 +00008350 continue;
8351 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00008352 if (!FD->getType()->isDependentType() &&
John McCall31168b02011-06-15 23:02:42 +00008353 !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00008354 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
Fariborz Jahanianb0e28472010-05-26 20:46:24 +00008355 << FD->getDeclName() << FD->getType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00008356 FD->setInvalidDecl();
8357 EnclosingDecl->setInvalidDecl();
8358 continue;
8359 }
Chris Lattner720a0542007-01-25 00:44:24 +00008360 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00008361 if (Record)
8362 Record->setHasFlexibleArrayMember(true);
Douglas Gregorac1fb652009-03-24 19:52:54 +00008363 } else if (!FDTy->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00008364 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregorac1fb652009-03-24 19:52:54 +00008365 diag::err_field_incomplete)) {
8366 // Incomplete type
8367 FD->setInvalidDecl();
8368 EnclosingDecl->setInvalidDecl();
8369 continue;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008370 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
Chris Lattner720a0542007-01-25 00:44:24 +00008371 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
8372 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00008373 if (Record && Record->isUnion()) {
Chris Lattner41943152007-01-25 04:52:46 +00008374 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00008375 } else {
8376 // If this is a struct/class and this is not the last element, reject
8377 // it. Note that GCC supports variable sized arrays in the middle of
8378 // structures.
Douglas Gregor3e06dbf2009-03-06 23:41:27 +00008379 if (i != NumFields-1)
8380 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattnerb28fe9e2009-04-25 18:52:45 +00008381 << FD->getDeclName() << FD->getType();
Douglas Gregor3e06dbf2009-03-06 23:41:27 +00008382 else {
8383 // We support flexible arrays at the end of structs in
8384 // other structs as an extension.
8385 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
8386 << FD->getDeclName();
8387 if (Record)
8388 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00008389 }
Chris Lattner720a0542007-01-25 00:44:24 +00008390 }
8391 }
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00008392 if (Record && FDTTy->getDecl()->hasObjectMember())
8393 Record->setHasObjectMember(true);
John McCall8b07ec22010-05-15 11:32:37 +00008394 } else if (FDTy->isObjCObjectType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00008395 /// A field cannot be an Objective-c object
Steve Naroff32606412009-02-20 22:59:16 +00008396 Diag(FD->getLocation(), diag::err_statically_allocated_object);
Fariborz Jahanianecfe4f12007-10-12 22:10:42 +00008397 FD->setInvalidDecl();
8398 EnclosingDecl->setInvalidDecl();
8399 continue;
John McCall31168b02011-06-15 23:02:42 +00008400 }
8401 else if (!getLangOptions().CPlusPlus) {
8402 if (getLangOptions().ObjCAutoRefCount && Record && !ARCErrReported) {
8403 // It's an error in ARC if a field has lifetime.
8404 // We don't want to report this in a system header, though,
8405 // so we just make the field unavailable.
8406 // FIXME: that's really not sufficient; we need to make the type
8407 // itself invalid to, say, initialize or copy.
8408 QualType T = FD->getType();
8409 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
8410 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
8411 SourceLocation loc = FD->getLocation();
8412 if (getSourceManager().isInSystemHeader(loc)) {
8413 if (!FD->hasAttr<UnavailableAttr>()) {
8414 FD->addAttr(new (Context) UnavailableAttr(loc, Context,
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008415 "this system field has retaining ownership"));
John McCall31168b02011-06-15 23:02:42 +00008416 }
8417 } else {
8418 Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct);
8419 }
8420 ARCErrReported = true;
8421 }
8422 }
8423 else if (getLangOptions().ObjC1 &&
Mike Stump12b8ce12009-08-04 21:02:39 +00008424 getLangOptions().getGCMode() != LangOptions::NonGC &&
John McCall31168b02011-06-15 23:02:42 +00008425 Record && !Record->hasObjectMember()) {
8426 if (FD->getType()->isObjCObjectPointerType() ||
8427 FD->getType().isObjCGCStrong())
8428 Record->setHasObjectMember(true);
8429 else if (Context.getAsArrayType(FD->getType())) {
8430 QualType BaseType = Context.getBaseElementType(FD->getType());
8431 if (BaseType->isRecordType() &&
8432 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
8433 Record->setHasObjectMember(true);
8434 else if (BaseType->isObjCObjectPointerType() ||
8435 BaseType.isObjCGCStrong())
8436 Record->setHasObjectMember(true);
8437 }
8438 }
Fariborz Jahanian021510e2010-06-15 22:44:06 +00008439 }
Chris Lattner82625602007-01-24 02:26:21 +00008440 // Keep track of the number of named members.
Douglas Gregor82ac25e2009-01-08 20:45:30 +00008441 if (FD->getIdentifier())
Chris Lattner82625602007-01-24 02:26:21 +00008442 ++NumNamedMembers;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00008443 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00008444
Chris Lattner82625602007-01-24 02:26:21 +00008445 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +00008446 if (Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00008447 bool Completed = false;
8448 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
8449 if (!CXXRecord->isInvalidDecl()) {
8450 // Set access bits correctly on the directly-declared conversions.
8451 UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions();
8452 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end();
8453 I != E; ++I)
8454 Convs->setAccess(I, (*I)->getAccess());
8455
8456 if (!CXXRecord->isDependentType()) {
John McCall31168b02011-06-15 23:02:42 +00008457 // Objective-C Automatic Reference Counting:
8458 // If a class has a non-static data member of Objective-C pointer
8459 // type (or array thereof), it is a non-POD type and its
8460 // default constructor (if any), copy constructor, copy assignment
8461 // operator, and destructor are non-trivial.
8462 //
8463 // This rule is also handled by CXXRecordDecl::completeDefinition().
8464 // However, here we check whether this particular class is only
8465 // non-POD because of the presence of an Objective-C pointer member.
8466 // If so, objects of this type cannot be shared between code compiled
8467 // with instant objects and code compiled with manual retain/release.
8468 if (getLangOptions().ObjCAutoRefCount &&
8469 CXXRecord->hasObjectMember() &&
8470 CXXRecord->getLinkage() == ExternalLinkage) {
8471 if (CXXRecord->isPOD()) {
8472 Diag(CXXRecord->getLocation(),
8473 diag::warn_arc_non_pod_class_with_object_member)
8474 << CXXRecord;
8475 } else {
8476 // FIXME: Fix-Its would be nice here, but finding a good location
8477 // for them is going to be tricky.
8478 if (CXXRecord->hasTrivialCopyConstructor())
8479 Diag(CXXRecord->getLocation(),
8480 diag::warn_arc_trivial_member_function_with_object_member)
8481 << CXXRecord << 0;
8482 if (CXXRecord->hasTrivialCopyAssignment())
8483 Diag(CXXRecord->getLocation(),
8484 diag::warn_arc_trivial_member_function_with_object_member)
8485 << CXXRecord << 1;
8486 if (CXXRecord->hasTrivialDestructor())
8487 Diag(CXXRecord->getLocation(),
8488 diag::warn_arc_trivial_member_function_with_object_member)
8489 << CXXRecord << 2;
8490 }
8491 }
8492
Sebastian Redl623ea822011-05-19 05:13:44 +00008493 // Adjust user-defined destructor exception spec.
8494 if (getLangOptions().CPlusPlus0x &&
8495 CXXRecord->hasUserDeclaredDestructor())
8496 AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor());
8497
Douglas Gregor8fb95122010-09-29 00:15:42 +00008498 // Add any implicitly-declared members to this class.
8499 AddImplicitlyDeclaredMembersToClass(CXXRecord);
8500
8501 // If we have virtual base classes, we may end up finding multiple
8502 // final overriders for a given virtual function. Check for this
8503 // problem now.
8504 if (CXXRecord->getNumVBases()) {
8505 CXXFinalOverriderMap FinalOverriders;
8506 CXXRecord->getFinalOverriders(FinalOverriders);
8507
8508 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
8509 MEnd = FinalOverriders.end();
8510 M != MEnd; ++M) {
8511 for (OverridingMethods::iterator SO = M->second.begin(),
8512 SOEnd = M->second.end();
8513 SO != SOEnd; ++SO) {
8514 assert(SO->second.size() > 0 &&
8515 "Virtual function without overridding functions?");
8516 if (SO->second.size() == 1)
8517 continue;
8518
8519 // C++ [class.virtual]p2:
8520 // In a derived class, if a virtual member function of a base
8521 // class subobject has more than one final overrider the
8522 // program is ill-formed.
8523 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
8524 << (NamedDecl *)M->first << Record;
8525 Diag(M->first->getLocation(),
8526 diag::note_overridden_virtual_function);
8527 for (OverridingMethods::overriding_iterator
8528 OM = SO->second.begin(),
8529 OMEnd = SO->second.end();
8530 OM != OMEnd; ++OM)
8531 Diag(OM->Method->getLocation(), diag::note_final_overrider)
8532 << (NamedDecl *)M->first << OM->Method->getParent();
8533
8534 Record->setInvalidDecl();
8535 }
8536 }
8537 CXXRecord->completeDefinition(&FinalOverriders);
8538 Completed = true;
8539 }
8540 }
8541 }
8542 }
8543
8544 if (!Completed)
8545 Record->completeDefinition();
Sebastian Redl623ea822011-05-19 05:13:44 +00008546
8547 // Now that the record is complete, do any delayed exception spec checks
8548 // we were missing.
Richard Smith938f40b2011-06-11 17:19:42 +00008549 while (!DelayedDestructorExceptionSpecChecks.empty()) {
Sebastian Redl623ea822011-05-19 05:13:44 +00008550 const CXXDestructorDecl *Dtor =
8551 DelayedDestructorExceptionSpecChecks.back().first;
Richard Smith938f40b2011-06-11 17:19:42 +00008552 if (Dtor->getParent() != Record)
8553 break;
8554
8555 assert(!Dtor->getParent()->isDependentType() &&
8556 "Should not ever add destructors of templates into the list.");
8557 CheckOverridingFunctionExceptionSpec(Dtor,
8558 DelayedDestructorExceptionSpecChecks.back().second);
8559 DelayedDestructorExceptionSpecChecks.pop_back();
Sebastian Redl623ea822011-05-19 05:13:44 +00008560 }
8561
Chris Lattner622c1932008-02-06 00:51:33 +00008562 } else {
Jay Foad7d0479f2009-05-21 09:52:38 +00008563 ObjCIvarDecl **ClsFields =
8564 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
Fariborz Jahanian02225532008-12-13 20:28:25 +00008565 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattner22298722009-02-20 21:35:13 +00008566 ID->setLocEnd(RBrac);
Fariborz Jahanian68453832009-06-05 18:16:35 +00008567 // Add ivar's to class's DeclContext.
8568 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
8569 ClsFields[i]->setLexicalDeclContext(ID);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008570 ID->addDecl(ClsFields[i]);
Fariborz Jahanian68453832009-06-05 18:16:35 +00008571 }
Fariborz Jahaniana599c132008-12-16 01:08:35 +00008572 // Must enforce the rule that ivars in the base classes may not be
8573 // duplicates.
Fariborz Jahanian545643c2010-02-23 23:41:11 +00008574 if (ID->getSuperClass())
8575 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
Mike Stump11289f42009-09-09 15:08:12 +00008576 } else if (ObjCImplementationDecl *IMPDecl =
Chris Lattnerd13b8b52009-02-23 22:00:08 +00008577 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00008578 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Fariborz Jahanian68453832009-06-05 18:16:35 +00008579 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
8580 // Ivar declared in @implementation never belongs to the implementation.
8581 // Only it is in implementation's lexical context.
Douglas Gregor5f662052009-04-23 03:23:08 +00008582 ClsFields[I]->setLexicalDeclContext(IMPDecl);
Fariborz Jahanian95b60762007-10-31 18:48:14 +00008583 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +00008584 } else if (ObjCCategoryDecl *CDecl =
8585 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
Fariborz Jahanian6a0a2e02010-04-06 22:43:48 +00008586 // case of ivars in class extension; all other cases have been
8587 // reported as errors elsewhere.
8588 // FIXME. Class extension does not have a LocEnd field.
8589 // CDecl->setLocEnd(RBrac);
8590 // Add ivar's to class extension's DeclContext.
8591 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
8592 ClsFields[i]->setLexicalDeclContext(CDecl);
8593 CDecl->addDecl(ClsFields[i]);
Fariborz Jahanian4c172c62010-02-22 23:04:20 +00008594 }
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +00008595 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +00008596 }
Daniel Dunbar325601a2008-10-03 17:33:35 +00008597
8598 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +00008599 ProcessDeclAttributeList(S, Record, Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00008600
8601 // If there's a #pragma GCC visibility in scope, and this isn't a subclass,
8602 // set the visibility of this record.
8603 if (Record && !Record->getDeclContext()->isRecord())
8604 AddPushedVisibilityAttribute(Record);
Chris Lattner1300fb92007-01-23 23:42:53 +00008605}
8606
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008607/// \brief Determine whether the given integral value is representable within
8608/// the given type T.
8609static bool isRepresentableIntegerValue(ASTContext &Context,
8610 llvm::APSInt &Value,
8611 QualType T) {
Douglas Gregor6972a622010-06-16 00:35:25 +00008612 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregorc1cf8142010-04-15 15:53:31 +00008613 unsigned BitWidth = Context.getIntWidth(T);
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008614
Douglas Gregor0bf31402010-10-08 23:50:27 +00008615 if (Value.isUnsigned() || Value.isNonNegative()) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00008616 if (T->isSignedIntegerOrEnumerationType())
Douglas Gregor0bf31402010-10-08 23:50:27 +00008617 --BitWidth;
8618 return Value.getActiveBits() <= BitWidth;
8619 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008620 return Value.getMinSignedBits() <= BitWidth;
8621}
8622
8623// \brief Given an integral type, return the next larger integral type
8624// (or a NULL type of no such type exists).
8625static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
8626 // FIXME: Int128/UInt128 support, which also needs to be introduced into
8627 // enum checking below.
Douglas Gregor6972a622010-06-16 00:35:25 +00008628 assert(T->isIntegralType(Context) && "Integral type required!");
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008629 const unsigned NumTypes = 4;
8630 QualType SignedIntegralTypes[NumTypes] = {
8631 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
8632 };
8633 QualType UnsignedIntegralTypes[NumTypes] = {
8634 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
8635 Context.UnsignedLongLongTy
8636 };
8637
8638 unsigned BitWidth = Context.getTypeSize(T);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00008639 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
8640 : UnsignedIntegralTypes;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008641 for (unsigned I = 0; I != NumTypes; ++I)
8642 if (Context.getTypeSize(Types[I]) > BitWidth)
8643 return Types[I];
8644
8645 return QualType();
8646}
8647
Douglas Gregor954f6b272009-03-17 19:05:46 +00008648EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
8649 EnumConstantDecl *LastEnumConst,
8650 SourceLocation IdLoc,
8651 IdentifierInfo *Id,
John McCallb268a282010-08-23 23:25:46 +00008652 Expr *Val) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008653 unsigned IntWidth = Context.Target.getIntWidth();
8654 llvm::APSInt EnumVal(IntWidth);
Douglas Gregor954f6b272009-03-17 19:05:46 +00008655 QualType EltTy;
Douglas Gregor2b988fd2010-12-16 00:24:44 +00008656
8657 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
8658 Val = 0;
8659
Douglas Gregorb2186fe2009-11-06 00:03:12 +00008660 if (Val) {
Douglas Gregordc70c3a2010-03-02 17:53:14 +00008661 if (Enum->isDependentType() || Val->isTypeDependent())
Douglas Gregorb2186fe2009-11-06 00:03:12 +00008662 EltTy = Context.DependentTy;
8663 else {
Douglas Gregorb2186fe2009-11-06 00:03:12 +00008664 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
8665 SourceLocation ExpLoc;
Douglas Gregordc70c3a2010-03-02 17:53:14 +00008666 if (!Val->isValueDependent() &&
8667 VerifyIntegerConstantExpression(Val, &EnumVal)) {
Douglas Gregorb2186fe2009-11-06 00:03:12 +00008668 Val = 0;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008669 } else {
8670 if (!getLangOptions().CPlusPlus) {
8671 // C99 6.7.2.2p2:
8672 // The expression that defines the value of an enumeration constant
8673 // shall be an integer constant expression that has a value
8674 // representable as an int.
8675
8676 // Complain if the value is not representable in an int.
8677 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
8678 Diag(IdLoc, diag::ext_enum_value_not_int)
8679 << EnumVal.toString(10) << Val->getSourceRange()
Douglas Gregorc0b8c812010-02-17 22:40:11 +00008680 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008681 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
8682 // Force the type of the expression to 'int'.
John Wiegley01296292011-04-08 18:41:53 +00008683 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008684 }
8685 }
8686
Douglas Gregor0bf31402010-10-08 23:50:27 +00008687 if (Enum->isFixed()) {
8688 EltTy = Enum->getIntegerType();
8689
8690 // C++0x [dcl.enum]p5:
8691 // ... if the initializing value of an enumerator cannot be
8692 // represented by the underlying type, the program is ill-formed.
Francois Picheta3108062010-10-18 15:01:13 +00008693 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
8694 if (getLangOptions().Microsoft) {
8695 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
John Wiegley01296292011-04-08 18:41:53 +00008696 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Francois Picheta3108062010-10-18 15:01:13 +00008697 } else
8698 Diag(IdLoc, diag::err_enumerator_too_large)
8699 << EltTy;
8700 } else
John Wiegley01296292011-04-08 18:41:53 +00008701 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008702 }
8703 else {
8704 // C++0x [dcl.enum]p5:
8705 // If the underlying type is not fixed, the type of each enumerator
8706 // is the type of its initializing value:
8707 // - If an initializer is specified for an enumerator, the
8708 // initializing value has the same type as the expression.
8709 EltTy = Val->getType();
8710 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +00008711 }
Douglas Gregor954f6b272009-03-17 19:05:46 +00008712 }
8713 }
Mike Stump11289f42009-09-09 15:08:12 +00008714
Douglas Gregor954f6b272009-03-17 19:05:46 +00008715 if (!Val) {
Eli Friedmand0e60972009-12-11 01:34:50 +00008716 if (Enum->isDependentType())
8717 EltTy = Context.DependentTy;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008718 else if (!LastEnumConst) {
8719 // C++0x [dcl.enum]p5:
8720 // If the underlying type is not fixed, the type of each enumerator
8721 // is the type of its initializing value:
8722 // - If no initializer is specified for the first enumerator, the
8723 // initializing value has an unspecified integral type.
8724 //
8725 // GCC uses 'int' for its unspecified integral type, as does
8726 // C99 6.7.2.2p3.
Douglas Gregor0bf31402010-10-08 23:50:27 +00008727 if (Enum->isFixed()) {
8728 EltTy = Enum->getIntegerType();
8729 }
8730 else {
8731 EltTy = Context.IntTy;
8732 }
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008733 } else {
Douglas Gregor954f6b272009-03-17 19:05:46 +00008734 // Assign the last value + 1.
8735 EnumVal = LastEnumConst->getInitVal();
8736 ++EnumVal;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008737 EltTy = LastEnumConst->getType();
Douglas Gregor954f6b272009-03-17 19:05:46 +00008738
8739 // Check for overflow on increment.
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008740 if (EnumVal < LastEnumConst->getInitVal()) {
8741 // C++0x [dcl.enum]p5:
8742 // If the underlying type is not fixed, the type of each enumerator
8743 // is the type of its initializing value:
8744 //
8745 // - Otherwise the type of the initializing value is the same as
8746 // the type of the initializing value of the preceding enumerator
8747 // unless the incremented value is not representable in that type,
8748 // in which case the type is an unspecified integral type
8749 // sufficient to contain the incremented value. If no such type
8750 // exists, the program is ill-formed.
8751 QualType T = getNextLargerIntegralType(Context, EltTy);
Douglas Gregor0bf31402010-10-08 23:50:27 +00008752 if (T.isNull() || Enum->isFixed()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008753 // There is no integral type larger enough to represent this
8754 // value. Complain, then allow the value to wrap around.
8755 EnumVal = LastEnumConst->getInitVal();
Jay Foad6d4db0c2010-12-07 08:25:34 +00008756 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
Douglas Gregor0bf31402010-10-08 23:50:27 +00008757 ++EnumVal;
8758 if (Enum->isFixed())
8759 // When the underlying type is fixed, this is ill-formed.
8760 Diag(IdLoc, diag::err_enumerator_wrapped)
8761 << EnumVal.toString(10)
8762 << EltTy;
8763 else
8764 Diag(IdLoc, diag::warn_enumerator_too_large)
8765 << EnumVal.toString(10);
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008766 } else {
8767 EltTy = T;
8768 }
8769
8770 // Retrieve the last enumerator's value, extent that type to the
8771 // type that is supposed to be large enough to represent the incremented
8772 // value, then increment.
8773 EnumVal = LastEnumConst->getInitVal();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00008774 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Jay Foad6d4db0c2010-12-07 08:25:34 +00008775 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008776 ++EnumVal;
8777
8778 // If we're not in C++, diagnose the overflow of enumerator values,
8779 // which in C99 means that the enumerator value is not representable in
8780 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
8781 // permits enumerator values that are representable in some larger
8782 // integral type.
8783 if (!getLangOptions().CPlusPlus && !T.isNull())
8784 Diag(IdLoc, diag::warn_enum_value_overflow);
8785 } else if (!getLangOptions().CPlusPlus &&
8786 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
8787 // Enforce C99 6.7.2.2p2 even when we compute the next value.
8788 Diag(IdLoc, diag::ext_enum_value_not_int)
8789 << EnumVal.toString(10) << 1;
8790 }
Douglas Gregor954f6b272009-03-17 19:05:46 +00008791 }
8792 }
Mike Stump11289f42009-09-09 15:08:12 +00008793
Douglas Gregordc70c3a2010-03-02 17:53:14 +00008794 if (!EltTy->isDependentType()) {
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008795 // Make the enumerator value match the signedness and size of the
8796 // enumerator's type.
Jay Foad6d4db0c2010-12-07 08:25:34 +00008797 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00008798 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
Douglas Gregor6791a0d2010-02-01 23:36:03 +00008799 }
Douglas Gregorb2186fe2009-11-06 00:03:12 +00008800
Douglas Gregor954f6b272009-03-17 19:05:46 +00008801 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
Mike Stump11289f42009-09-09 15:08:12 +00008802 Val, EnumVal);
Douglas Gregor954f6b272009-03-17 19:05:46 +00008803}
8804
8805
John McCall811a0f52010-10-22 23:36:17 +00008806Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
8807 SourceLocation IdLoc, IdentifierInfo *Id,
8808 AttributeList *Attr,
8809 SourceLocation EqualLoc, ExprTy *val) {
John McCall48871652010-08-21 09:40:31 +00008810 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
Chris Lattner4ef40012007-06-11 01:28:17 +00008811 EnumConstantDecl *LastEnumConst =
John McCall48871652010-08-21 09:40:31 +00008812 cast_or_null<EnumConstantDecl>(lastEnumConst);
Chris Lattner4ef40012007-06-11 01:28:17 +00008813 Expr *Val = static_cast<Expr*>(val);
Chris Lattner8116d1b2007-01-25 22:38:29 +00008814
Chris Lattner1a76a3c2007-08-26 06:24:45 +00008815 // The scope passed in may not be a decl scope. Zip up the scope tree until
8816 // we find one that is.
Douglas Gregor45a33ec2009-01-12 18:45:55 +00008817 S = getNonFieldDeclScope(S);
Mike Stump11289f42009-09-09 15:08:12 +00008818
Chris Lattner8116d1b2007-01-25 22:38:29 +00008819 // Verify that there isn't already something declared with this name in this
8820 // scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00008821 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
Douglas Gregor5204248f2010-01-19 06:06:57 +00008822 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +00008823 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00008824 // Maybe we will complain about the shadowed template parameter.
8825 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
8826 // Just pretend that we didn't see the previous declaration.
8827 PrevDecl = 0;
8828 }
8829
8830 if (PrevDecl) {
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +00008831 // When in C++, we may get a TagDecl with the same name; in this case the
8832 // enum constant will 'hide' the tag.
8833 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
8834 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis5b144d52008-09-09 21:18:04 +00008835 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +00008836 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner4bd8dd82008-11-19 08:23:25 +00008837 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner8116d1b2007-01-25 22:38:29 +00008838 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +00008839 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner0369c572008-11-23 23:12:31 +00008840 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00008841 return 0;
Chris Lattner8116d1b2007-01-25 22:38:29 +00008842 }
8843 }
Chris Lattner4ef40012007-06-11 01:28:17 +00008844
Douglas Gregor36c22a22010-10-15 13:21:21 +00008845 // C++ [class.mem]p13:
8846 // If T is the name of a class, then each of the following shall have a
8847 // name different from T:
8848 // - every enumerator of every member of class T that is an enumerated
8849 // type
8850 if (CXXRecordDecl *Record
8851 = dyn_cast<CXXRecordDecl>(
8852 TheEnumDecl->getDeclContext()->getRedeclContext()))
8853 if (Record->getIdentifier() && Record->getIdentifier() == Id)
8854 Diag(IdLoc, diag::err_member_name_of_class) << Id;
8855
John McCall811a0f52010-10-22 23:36:17 +00008856 EnumConstantDecl *New =
8857 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
Chris Lattner0515e4b2007-08-27 21:16:18 +00008858
John McCall553c0792010-01-23 00:46:32 +00008859 if (New) {
John McCall811a0f52010-10-22 23:36:17 +00008860 // Process attributes.
8861 if (Attr) ProcessDeclAttributeList(S, New, Attr);
8862
8863 // Register this decl in the current scope stack.
John McCall553c0792010-01-23 00:46:32 +00008864 New->setAccess(TheEnumDecl->getAccess());
Douglas Gregor954f6b272009-03-17 19:05:46 +00008865 PushOnScopeChains(New, S);
John McCall553c0792010-01-23 00:46:32 +00008866 }
Douglas Gregor2f521192008-12-17 02:04:30 +00008867
John McCall48871652010-08-21 09:40:31 +00008868 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +00008869}
8870
Mike Stump6814d1c2009-05-16 07:06:02 +00008871void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
John McCall48871652010-08-21 09:40:31 +00008872 SourceLocation RBraceLoc, Decl *EnumDeclX,
8873 Decl **Elements, unsigned NumElements,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008874 Scope *S, AttributeList *Attr) {
John McCall48871652010-08-21 09:40:31 +00008875 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
Douglas Gregor07665a62009-01-05 19:45:36 +00008876 QualType EnumType = Context.getTypeDeclType(Enum);
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008877
8878 if (Attr)
8879 ProcessDeclAttributeList(S, Enum, Attr);
Mike Stump11289f42009-09-09 15:08:12 +00008880
Eli Friedmand0e60972009-12-11 01:34:50 +00008881 if (Enum->isDependentType()) {
8882 for (unsigned i = 0; i != NumElements; ++i) {
8883 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +00008884 cast_or_null<EnumConstantDecl>(Elements[i]);
Eli Friedmand0e60972009-12-11 01:34:50 +00008885 if (!ECD) continue;
8886
8887 ECD->setType(EnumType);
8888 }
8889
John McCall9aa35be2010-05-06 08:49:23 +00008890 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
Eli Friedmand0e60972009-12-11 01:34:50 +00008891 return;
8892 }
8893
Chris Lattner67933c02007-08-28 05:10:31 +00008894 // TODO: If the result value doesn't fit in an int, it must be a long or long
8895 // long value. ISO C does not support this, but GCC does as an extension,
8896 // emit a warning.
Chris Lattner37e05872008-03-05 18:54:05 +00008897 unsigned IntWidth = Context.Target.getIntWidth();
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008898 unsigned CharWidth = Context.Target.getCharWidth();
8899 unsigned ShortWidth = Context.Target.getShortWidth();
Mike Stump11289f42009-09-09 15:08:12 +00008900
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008901 // Verify that all the values are okay, compute the size of the values, and
8902 // reverse the list.
8903 unsigned NumNegativeBits = 0;
8904 unsigned NumPositiveBits = 0;
Mike Stump11289f42009-09-09 15:08:12 +00008905
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008906 // Keep track of whether all elements have type int.
8907 bool AllElementsInt = true;
Mike Stump11289f42009-09-09 15:08:12 +00008908
Chris Lattnerc1915e22007-01-25 07:29:02 +00008909 for (unsigned i = 0; i != NumElements; ++i) {
8910 EnumConstantDecl *ECD =
John McCall48871652010-08-21 09:40:31 +00008911 cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattnerc1915e22007-01-25 07:29:02 +00008912 if (!ECD) continue; // Already issued a diagnostic.
Mike Stump11289f42009-09-09 15:08:12 +00008913
Chris Lattnerbf478cb2007-08-28 05:27:00 +00008914 const llvm::APSInt &InitVal = ECD->getInitVal();
Mike Stump11289f42009-09-09 15:08:12 +00008915
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008916 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +00008917 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +00008918 NumPositiveBits = std::max(NumPositiveBits,
8919 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008920 else
Chris Lattner49f980c2008-01-14 21:47:29 +00008921 NumNegativeBits = std::max(NumNegativeBits,
8922 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +00008923
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008924 // Keep track of whether every enum element has type int (very commmon).
8925 if (AllElementsInt)
Mike Stump11289f42009-09-09 15:08:12 +00008926 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattnerc1915e22007-01-25 07:29:02 +00008927 }
Mike Stump11289f42009-09-09 15:08:12 +00008928
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008929 // Figure out the type that should be used for this enum.
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008930 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +00008931 unsigned BestWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008932
John McCall56774992009-12-09 09:09:27 +00008933 // C++0x N3000 [conv.prom]p3:
8934 // An rvalue of an unscoped enumeration type whose underlying
8935 // type is not fixed can be converted to an rvalue of the first
8936 // of the following types that can represent all the values of
8937 // the enumeration: int, unsigned int, long int, unsigned long
8938 // int, long long int, or unsigned long long int.
8939 // C99 6.4.4.3p2:
8940 // An identifier declared as an enumeration constant has type int.
8941 // The C99 rule is modified by a gcc extension
8942 QualType BestPromotionType;
8943
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008944 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
Argyrios Kyrtzidis74825bc2010-10-08 00:25:19 +00008945 // -fshort-enums is the equivalent to specifying the packed attribute on all
8946 // enum definitions.
8947 if (LangOpts.ShortEnums)
8948 Packed = true;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008949
Douglas Gregor0bf31402010-10-08 23:50:27 +00008950 if (Enum->isFixed()) {
8951 BestType = BestPromotionType = Enum->getIntegerType();
Duncan Sands38b918c2010-10-12 14:07:59 +00008952 // We don't need to set BestWidth, because BestType is going to be the type
8953 // of the enumerators, but we do anyway because otherwise some compilers
8954 // warn that it might be used uninitialized.
8955 BestWidth = CharWidth;
Douglas Gregor0bf31402010-10-08 23:50:27 +00008956 }
8957 else if (NumNegativeBits) {
Mike Stump11289f42009-09-09 15:08:12 +00008958 // If there is a negative value, figure out the smallest integer type (of
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008959 // int/long/longlong) that fits.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008960 // If it's packed, check also if it fits a char or a short.
8961 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
John McCall56774992009-12-09 09:09:27 +00008962 BestType = Context.SignedCharTy;
8963 BestWidth = CharWidth;
Mike Stump11289f42009-09-09 15:08:12 +00008964 } else if (Packed && NumNegativeBits <= ShortWidth &&
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008965 NumPositiveBits < ShortWidth) {
John McCall56774992009-12-09 09:09:27 +00008966 BestType = Context.ShortTy;
8967 BestWidth = ShortWidth;
8968 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008969 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00008970 BestWidth = IntWidth;
8971 } else {
Chris Lattner37e05872008-03-05 18:54:05 +00008972 BestWidth = Context.Target.getLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +00008973
John McCall56774992009-12-09 09:09:27 +00008974 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008975 BestType = Context.LongTy;
John McCall56774992009-12-09 09:09:27 +00008976 } else {
Chris Lattner37e05872008-03-05 18:54:05 +00008977 BestWidth = Context.Target.getLongLongWidth();
Mike Stump11289f42009-09-09 15:08:12 +00008978
Chris Lattner3a370bf2007-08-29 17:31:48 +00008979 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008980 Diag(Enum->getLocation(), diag::warn_enum_too_large);
8981 BestType = Context.LongLongTy;
8982 }
8983 }
John McCall56774992009-12-09 09:09:27 +00008984 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008985 } else {
Douglas Gregora71cc152010-02-02 20:10:50 +00008986 // If there is no negative value, figure out the smallest type that fits
8987 // all of the enumerator values.
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008988 // If it's packed, check also if it fits a char or a short.
8989 if (Packed && NumPositiveBits <= CharWidth) {
John McCall56774992009-12-09 09:09:27 +00008990 BestType = Context.UnsignedCharTy;
8991 BestPromotionType = Context.IntTy;
8992 BestWidth = CharWidth;
Edward O'Callaghanc69169d2009-08-08 14:36:57 +00008993 } else if (Packed && NumPositiveBits <= ShortWidth) {
John McCall56774992009-12-09 09:09:27 +00008994 BestType = Context.UnsignedShortTy;
8995 BestPromotionType = Context.IntTy;
8996 BestWidth = ShortWidth;
8997 } else if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00008998 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00008999 BestWidth = IntWidth;
Douglas Gregora71cc152010-02-02 20:10:50 +00009000 BestPromotionType
9001 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
9002 ? Context.UnsignedIntTy : Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00009003 } else if (NumPositiveBits <=
Chris Lattner37e05872008-03-05 18:54:05 +00009004 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00009005 BestType = Context.UnsignedLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +00009006 BestPromotionType
9007 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
9008 ? Context.UnsignedLongTy : Context.LongTy;
Chris Lattner37e05872008-03-05 18:54:05 +00009009 } else {
9010 BestWidth = Context.Target.getLongLongWidth();
Chris Lattner3a370bf2007-08-29 17:31:48 +00009011 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +00009012 "How could an initializer get larger than ULL?");
9013 BestType = Context.UnsignedLongLongTy;
Douglas Gregora71cc152010-02-02 20:10:50 +00009014 BestPromotionType
9015 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
9016 ? Context.UnsignedLongLongTy : Context.LongLongTy;
Chris Lattnerb8a501c2007-08-28 06:15:15 +00009017 }
9018 }
Mike Stump11289f42009-09-09 15:08:12 +00009019
Chris Lattner3a370bf2007-08-29 17:31:48 +00009020 // Loop over all of the enumerator constants, changing their types to match
9021 // the type of the enum if needed.
9022 for (unsigned i = 0; i != NumElements; ++i) {
John McCall48871652010-08-21 09:40:31 +00009023 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
Chris Lattner3a370bf2007-08-29 17:31:48 +00009024 if (!ECD) continue; // Already issued a diagnostic.
9025
9026 // Standard C says the enumerators have int type, but we allow, as an
9027 // extension, the enumerators to be larger than int size. If each
9028 // enumerator value fits in an int, type it as an int, otherwise type it the
9029 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
9030 // that X has type 'int', not 'unsigned'.
Chris Lattner3a370bf2007-08-29 17:31:48 +00009031
9032 // Determine whether the value fits into an int.
9033 llvm::APSInt InitVal = ECD->getInitVal();
Chris Lattner3a370bf2007-08-29 17:31:48 +00009034
9035 // If it fits into an integer type, force it. Otherwise force it to match
9036 // the enum decl type.
9037 QualType NewTy;
9038 unsigned NewWidth;
9039 bool NewSign;
Douglas Gregor6791a0d2010-02-01 23:36:03 +00009040 if (!getLangOptions().CPlusPlus &&
9041 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
Chris Lattner3a370bf2007-08-29 17:31:48 +00009042 NewTy = Context.IntTy;
9043 NewWidth = IntWidth;
9044 NewSign = true;
9045 } else if (ECD->getType() == BestType) {
9046 // Already the right type!
Douglas Gregor1d248c52008-12-12 02:00:36 +00009047 if (getLangOptions().CPlusPlus)
9048 // C++ [dcl.enum]p4: Following the closing brace of an
9049 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +00009050 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +00009051 ECD->setType(EnumType);
Chris Lattner3a370bf2007-08-29 17:31:48 +00009052 continue;
9053 } else {
9054 NewTy = BestType;
9055 NewWidth = BestWidth;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00009056 NewSign = BestType->isSignedIntegerOrEnumerationType();
Chris Lattner3a370bf2007-08-29 17:31:48 +00009057 }
9058
9059 // Adjust the APSInt value.
Jay Foad6d4db0c2010-12-07 08:25:34 +00009060 InitVal = InitVal.extOrTrunc(NewWidth);
Chris Lattner3a370bf2007-08-29 17:31:48 +00009061 InitVal.setIsSigned(NewSign);
9062 ECD->setInitVal(InitVal);
Mike Stump11289f42009-09-09 15:08:12 +00009063
Chris Lattner3a370bf2007-08-29 17:31:48 +00009064 // Adjust the Expr initializer and type.
Abramo Bagnara77815432010-12-17 15:49:53 +00009065 if (ECD->getInitExpr() &&
Nick Lewycky0bdf13e2011-07-02 02:05:12 +00009066 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
John McCallcf142162010-08-07 06:22:56 +00009067 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
John McCalle3027922010-08-25 11:45:40 +00009068 CK_IntegralCast,
John McCallcf142162010-08-07 06:22:56 +00009069 ECD->getInitExpr(),
9070 /*base paths*/ 0,
John McCall2536c6d2010-08-25 10:28:54 +00009071 VK_RValue));
Douglas Gregor1d248c52008-12-12 02:00:36 +00009072 if (getLangOptions().CPlusPlus)
9073 // C++ [dcl.enum]p4: Following the closing brace of an
9074 // enum-specifier, each enumerator has the type of its
Mike Stump11289f42009-09-09 15:08:12 +00009075 // enumeration.
Douglas Gregor1d248c52008-12-12 02:00:36 +00009076 ECD->setType(EnumType);
9077 else
9078 ECD->setType(NewTy);
Chris Lattner3a370bf2007-08-29 17:31:48 +00009079 }
Mike Stump11289f42009-09-09 15:08:12 +00009080
John McCall9aa35be2010-05-06 08:49:23 +00009081 Enum->completeDefinition(BestType, BestPromotionType,
9082 NumPositiveBits, NumNegativeBits);
Chris Lattnerc1915e22007-01-25 07:29:02 +00009083}
Chris Lattner1300fb92007-01-23 23:42:53 +00009084
Abramo Bagnara348823a2011-03-03 14:20:18 +00009085Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
9086 SourceLocation StartLoc,
9087 SourceLocation EndLoc) {
John McCallb268a282010-08-23 23:25:46 +00009088 StringLiteral *AsmString = cast<StringLiteral>(expr);
Sebastian Redlc675bab2008-12-13 16:23:55 +00009089
Douglas Gregor278f52e2009-05-30 00:08:05 +00009090 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
Abramo Bagnara348823a2011-03-03 14:20:18 +00009091 AsmString, StartLoc,
9092 EndLoc);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009093 CurContext->addDecl(New);
John McCall48871652010-08-21 09:40:31 +00009094 return New;
Anders Carlsson5c6c0592008-02-08 00:33:21 +00009095}
Eli Friedman5ed51982009-06-05 02:44:36 +00009096
9097void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
9098 SourceLocation PragmaLoc,
9099 SourceLocation NameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00009100 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
Eli Friedman5ed51982009-06-05 02:44:36 +00009101
Eli Friedman5ed51982009-06-05 02:44:36 +00009102 if (PrevDecl) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00009103 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
Ryan Flynn7d470f32009-07-30 03:15:39 +00009104 } else {
9105 (void)WeakUndeclaredIdentifiers.insert(
9106 std::pair<IdentifierInfo*,WeakInfo>
9107 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
Eli Friedman5ed51982009-06-05 02:44:36 +00009108 }
Eli Friedman5ed51982009-06-05 02:44:36 +00009109}
9110
9111void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
9112 IdentifierInfo* AliasName,
9113 SourceLocation PragmaLoc,
9114 SourceLocation NameLoc,
9115 SourceLocation AliasNameLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00009116 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
9117 LookupOrdinaryName);
Ryan Flynn7d470f32009-07-30 03:15:39 +00009118 WeakInfo W = WeakInfo(Name, NameLoc);
Eli Friedman5ed51982009-06-05 02:44:36 +00009119
Eli Friedman5ed51982009-06-05 02:44:36 +00009120 if (PrevDecl) {
Ryan Flynn7d470f32009-07-30 03:15:39 +00009121 if (!PrevDecl->hasAttr<AliasAttr>())
9122 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
Ryan Flynnd963a492009-07-31 02:52:19 +00009123 DeclApplyPragmaWeak(TUScope, ND, W);
Ryan Flynn7d470f32009-07-30 03:15:39 +00009124 } else {
9125 (void)WeakUndeclaredIdentifiers.insert(
9126 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
Eli Friedman5ed51982009-06-05 02:44:36 +00009127 }
Eli Friedman5ed51982009-06-05 02:44:36 +00009128}